Spark - ML Tuning

官方文档:https://spark.apache.org/docs/2.2.0/ml-tuning.html

这一章节主要讲述如何通过使用MLlib的工具来调试模型算法和pipeline,内置的交叉验证和其他工具允许用户优化模型和pipeline中的超参数;

目录:

  • 模型选择,也就是调参;
  • 交叉验证;
  • 训练集、验证集划分;

模型选择(调参)

机器学习的一个重要工作就是模型选择,或者说根据给定任务使用数据来发现最优的模型和参数,也叫做调试,既可以针对单个模型进行调试,也可以针对整个pipeline的各个环节进行调试,使用者可以一次对整个pipeline进行调试而不是每次一个pipeline中的部分;

MLlib支持CrossValidator和TrainValidationSplit等模型选择工具,这些工具需要下列参数:

  • Estimator:待调试的算法或者Pipeline;
  • 参数Map列表:用于搜索的参数空间;
  • Evaluator:衡量模型在集外测试集上表现的方法;

这些工具工作方式如下:

  • 分割数据到训练集和测试集;
  • 对每一组训练&测试数据,应用所有参数空间中的可选参数组合:
    • 对每一组参数组合,使用其设置到算法上,得到对应的model,并验证该model的性能;
  • 选择得到最好性能的模型使用的参数组合;

Evaluator针对回归问题可以是RegressionEvaluator,针对二分数据可以是BinaryClassificationEvaluator,针对多分类问题的MulticlassClassificationEvaluator,默认的验证方法可以通过setMetricName来修改;

交叉验证

CrossValidator首先将数据分到一个个的fold中,使用这些fold集合作为训练集和测试集,如果k=3,那么CrossValidator将生成3个(训练,测试)组合,也就是通过3个fold排列组合得到的,每一组使用2个fold作为训练集,另一个fold作为测试集,为了验证一个指定的参数组合,CrossValidator需要计算3个模型的平均性能,每个模型都是通过之前的一组训练&测试集训练得到;

确认了最佳参数后,CrossValidator最终会使用全部数据和最佳参数组合来重新训练预测;

例子:通过交叉验证进行模型选择;

注意:交叉验证在整个参数网格上是十分耗时的,下面的例子中,参数网格中numFeatures有3个可取值,regParam有2个可取值,CrossValidator使用2个fold,这将会训练3*2*2个不同的模型,在实际工作中,通常会设置更多的参数、更多的参数取值以及更多的fold,换句话说,CrossValidator本身就是十分奢侈的,无论如何,与手工调试相比,它依然是一种更加合理和自动化的调参手段;

from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.feature import HashingTF, Tokenizer
from pyspark.ml.tuning import CrossValidator, ParamGridBuilder # Prepare training documents, which are labeled.
training = spark.createDataFrame([
(0, "a b c d e spark", 1.0),
(1, "b d", 0.0),
(2, "spark f g h", 1.0),
(3, "hadoop mapreduce", 0.0),
(4, "b spark who", 1.0),
(5, "g d a y", 0.0),
(6, "spark fly", 1.0),
(7, "was mapreduce", 0.0),
(8, "e spark program", 1.0),
(9, "a e c l", 0.0),
(10, "spark compile", 1.0),
(11, "hadoop software", 0.0)
], ["id", "text", "label"]) # Configure an ML pipeline, which consists of tree stages: tokenizer, hashingTF, and lr.
tokenizer = Tokenizer(inputCol="text", outputCol="words")
hashingTF = HashingTF(inputCol=tokenizer.getOutputCol(), outputCol="features")
lr = LogisticRegression(maxIter=10)
pipeline = Pipeline(stages=[tokenizer, hashingTF, lr]) # We now treat the Pipeline as an Estimator, wrapping it in a CrossValidator instance.
# This will allow us to jointly choose parameters for all Pipeline stages.
# A CrossValidator requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
# We use a ParamGridBuilder to construct a grid of parameters to search over.
# With 3 values for hashingTF.numFeatures and 2 values for lr.regParam,
# this grid will have 3 x 2 = 6 parameter settings for CrossValidator to choose from.
paramGrid = ParamGridBuilder() \
.addGrid(hashingTF.numFeatures, [10, 100, 1000]) \
.addGrid(lr.regParam, [0.1, 0.01]) \
.build() crossval = CrossValidator(estimator=pipeline,
estimatorParamMaps=paramGrid,
evaluator=BinaryClassificationEvaluator(),
numFolds=2) # use 3+ folds in practice # Run cross-validation, and choose the best set of parameters.
cvModel = crossval.fit(training) # Prepare test documents, which are unlabeled.
test = spark.createDataFrame([
(4, "spark i j k"),
(5, "l m n"),
(6, "mapreduce spark"),
(7, "apache hadoop")
], ["id", "text"]) # Make predictions on test documents. cvModel uses the best model found (lrModel).
prediction = cvModel.transform(test)
selected = prediction.select("id", "text", "probability", "prediction")
for row in selected.collect():
print(row)

划分训练、验证集

对于超参数调试,Spark还支持TrainValidationSplit,它一次只能验证一组参数,这与CrossValidator一次进行k次截然不同,因此它更加快速,但是如果训练集不够大的化就无法得到一个真实的结果;

不像是CrossValidator,TrainValidationSplit创建一个训练、测试组合,它根据trainRatio将数据分为两部分,假设trainRatio=0.75,那么数据集的75%作为训练集,25%用于验证;

与CrossValidator类似的是,TrainValidationSplit最终也会使用最佳参数和全部数据来训练一个预测器;

from pyspark.ml.evaluation import RegressionEvaluator
from pyspark.ml.regression import LinearRegression
from pyspark.ml.tuning import ParamGridBuilder, TrainValidationSplit # Prepare training and test data.
data = spark.read.format("libsvm")\
.load("data/mllib/sample_linear_regression_data.txt")
train, test = data.randomSplit([0.9, 0.1], seed=12345) lr = LinearRegression(maxIter=10) # We use a ParamGridBuilder to construct a grid of parameters to search over.
# TrainValidationSplit will try all combinations of values and determine best model using
# the evaluator.
paramGrid = ParamGridBuilder()\
.addGrid(lr.regParam, [0.1, 0.01]) \
.addGrid(lr.fitIntercept, [False, True])\
.addGrid(lr.elasticNetParam, [0.0, 0.5, 1.0])\
.build() # In this case the estimator is simply the linear regression.
# A TrainValidationSplit requires an Estimator, a set of Estimator ParamMaps, and an Evaluator.
tvs = TrainValidationSplit(estimator=lr,
estimatorParamMaps=paramGrid,
evaluator=RegressionEvaluator(),
# 80% of the data will be used for training, 20% for validation.
trainRatio=0.8) # Run TrainValidationSplit, and choose the best set of parameters.
model = tvs.fit(train) # Make predictions on test data. model is the model with combination of parameters
# that performed best.
model.transform(test)\
.select("features", "label", "prediction")\
.show()

Spark 模型选择和调参的更多相关文章

  1. python 机器学习中模型评估和调参

    在做数据处理时,需要用到不同的手法,如特征标准化,主成分分析,等等会重复用到某些参数,sklearn中提供了管道,可以一次性的解决该问题 先展示先通常的做法 import pandas as pd f ...

  2. Spark2 Model selection and tuning 模型选择与调优

    Model selection模型选择 ML中的一个重要任务是模型选择,或使用数据为给定任务找到最佳的模型或参数. 这也称为调优. 可以对诸如Logistic回归的单独Estimators进行调整,或 ...

  3. 模型融合---CatBoost 调参总结

    一.参数速查 1.通用参数 2.性能参数 3.处理单元设置 二.分类 三.回归

  4. Spark机器学习——模型选择与参数调优之交叉验证

    spark 模型选择与超参调优 机器学习可以简单的归纳为 通过数据训练y = f(x) 的过程,因此定义完训练模型之后,就需要考虑如何选择最终我们认为最优的模型. 如何选择最优的模型,就是本篇的主要内 ...

  5. XGB 调参基本方法

    - xgboost 基本方法和默认参数 - 实战经验中调参方法 - 基于实例具体分析 在训练过程中主要用到两个方法:xgboost.train()和xgboost.cv(). xgboost.trai ...

  6. XGboost数据比赛实战之调参篇(完整流程)

    这一篇博客的内容是在上一篇博客Scikit中的特征选择,XGboost进行回归预测,模型优化的实战的基础上进行调参优化的,所以在阅读本篇博客之前,请先移步看一下上一篇文章. 我前面所做的工作基本都是关 ...

  7. 机器学习(ML)七之模型选择、欠拟合和过拟合

    训练误差和泛化误差 需要区分训练误差(training error)和泛化误差(generalization error).前者指模型在训练数据集上表现出的误差,后者指模型在任意一个测试数据样本上表现 ...

  8. Auto ML自动调参

    Auto ML自动调参 本文介绍Auto ML自动调参的算法介绍及操作流程. 操作步骤 登录PAI控制台. 单击左侧导航栏的实验并选择某个实验. 本文以雾霾天气预测实验为例. 在实验画布区,单击左上角 ...

  9. [调参]batch_size的选择

    链接:https://www.zhihu.com/question/61607442/answer/440944387 首先反对上面的尽可能调大batch size的说法,在现在较前沿的视角来看,这种 ...

随机推荐

  1. 如何处理遇到的错误-lammps

    一.认清模型——data文件: 二.读懂in文件: 三.当遇到error时,we can do: 1.查错: (1)从out文件中,复制里边的错误信息(copy一部分,不用全部): (2)进入到lam ...

  2. 【Gin-API系列】Gin中间件之异常处理(六)

    本文我们介绍生产环境上如何通过捕捉异常recovery来完善程序设计和提高用户体验. Golang异常处理 golang 的异常处理比较简单,通常都是在程序遇到异常崩溃panic之后通过defer调用 ...

  3. Fastlane- app自动编译、打包多个版本、上传到app store

    Fastlane是一套使用Ruby写的自动化工具集,用于iOS和Android的自动化打包.发布等工作,可以节省大量的时间. Github:https://github.com/fastlane/fa ...

  4. java基础语法(一)

    一.注释: 行内注释 //这是行内注释 多行注释 /* *这是多行注释 */ 文档注释 /** *这是文档注释 */ 二.标识符 标识符也就是我们所说的关键字 三.数据类型 1.基本数据类型 ​ 数据 ...

  5. 网络协议HTTP、TCP/IP、Socket

    网络协议HTTP.TCP/IP.Socket 网络七层由下往上分别为物理层.数据链路层.网络层.传输层.会话层.表示层和应用层.  其中物理层.数据链路层和网络层通常被称作媒体层,是网络工程师所研究的 ...

  6. Spring JPA 查询创建

    Spring JPA 查询创建 这是JPA内容的核心部分,可以收藏用作参阅文档. 1. 查询转化和关键字 例:一个JPA查询的转化 public interface UserRepository ex ...

  7. 关于HTML基本标签,了解一下!

    目录 1 前言 2 正文 2.1 HTML文档结构 2.1.1 html标签 2.1.2 head标签 2.1.3 title标签 2.1.4 body标签 2.2 HTML常用标签 2.2.1 换行 ...

  8. eleLogger主题评论区(反馈与建议)

    // run $('#blog_post_info, #BlogPostCategory, #post_next_prev, #blog_post_info_block').remove() $('# ...

  9. 内置函数:循环调用函数map和filter

    1.map:循环调用函数,前面一定一定要加list,要不然不会被调用 map的格式:list(map(函数名,循环体)) #这里的函数只能写函数名,不要加() list(map(os.mkdir,[' ...

  10. WebSphere MQ常用命令及配置

    WebSphere MQ常用命令及配置 (2012-06-23 23:09:16) 标签: mq命令 杂谈 分类: MQ [导读]WebSphere MQ常用命令及配置 一,队列管理命令 1,创建队列 ...