Classification and regression(分类和回归)

本页面介绍了分类和回归的算法。它还包括讨论特定类别的算法部分,如:线性方法,树和集成。

目录如下:

 

Classification(分类)

Logistic Regression(逻辑回归)

逻辑回归是预测分类反应的流行方法。 广义线性模型的一个特例是预测结果的可能性。 在spark.ml逻辑回归中可以使用二项式逻辑回归来预测二进制结果,也可以通过使用多项Logistic回归来预测多类结果。 使用系列参数在这两种算法之间进行选择,或者将其设置为未设置,Spark将推断出正确的变体。

通过将家族参数设置为“多项式”,可以将多项Logistic回归用于二进制分类。它将产生两组系数和两个截距。

当在具有常量非零列的数据集上对LogisticRegressionModel进行拟合时,Spark MLlib为常数非零列输出零系数。此行为与R glmnet相同,但与LIBSVM不同。

  

Binomial logistic regression(二项式逻辑回归)

有关二项式逻辑回归实现的更多背景和更多细节,请参阅spark.mllib中逻辑回归的文档

示例

以下示例显示了如何用弹性网络正则化来训练二项分类的二项式和多项Logistic回归模型。 elasticNetParam对应于αα,regParam对应于λ。

 

Scala
import org.apache.spark.ml.classification.LogisticRegression

// Load training data
val training = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

val lr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)

// Fit the model
val lrModel = lr.fit(training)

// Print the coefficients and intercept for logistic regression
println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")

// We can also use the multinomial family for binary classification
val mlr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)
  .setFamily("multinomial")

val mlrModel = mlr.fit(training)

// Print the coefficients and intercepts for logistic regression with multinomial family
println(s"Multinomial coefficients: ${mlrModel.coefficientMatrix}")
println(s"Multinomial intercepts: ${mlrModel.interceptVector}")

有关参数的更多详细信息,请参见Scala API文档 

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/LogisticRegressionWithElasticNetExample.scala”中查找完整示例代码。

逻辑回归的spark.ml实现也支持在训练集中提取模型的摘要。 请注意,在BinaryLogisticRegressionSummary中存储为DataFrame的预测和度量标注为@transient,因此仅在驱动程序上可用。
LogisticRegressionTrainingSummaryLogisticRegressionModel提供了一个摘要。 目前,只支持二进制分类,必须将摘要显式转换为BinaryLogisticRegressionTrainingSummary。 当支持多类分类时,这可能会发生变化。

继续前面的例子:

 

Scala
import org.apache.spark.ml.classification.{BinaryLogisticRegressionSummary, LogisticRegression}

// Extract the summary from the returned LogisticRegressionModel instance trained in the earlier
// example
val trainingSummary = lrModel.summary

// Obtain the objective per iteration.
val objectiveHistory = trainingSummary.objectiveHistory
println("objectiveHistory:")
objectiveHistory.foreach(loss => println(loss))

// Obtain the metrics useful to judge performance on test data.
// We cast the summary to a BinaryLogisticRegressionSummary since the problem is a
// binary classification problem.
val binarySummary = trainingSummary.asInstanceOf[BinaryLogisticRegressionSummary]

// Obtain the receiver-operating characteristic as a dataframe and areaUnderROC.
val roc = binarySummary.roc
roc.show()
println(s"areaUnderROC: ${binarySummary.areaUnderROC}")

// Set the model threshold to maximize F-Measure
val fMeasure = binarySummary.fMeasureByThreshold
val maxFMeasure = fMeasure.select(max("F-Measure")).head().getDouble(0)
val bestThreshold = fMeasure.where($"F-Measure" === maxFMeasure)
  .select("threshold").head().getDouble(0)
lrModel.setThreshold(bestThreshold)
 在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/LogisticRegressionSummaryExample.scala”中查找完整示例代码。

Multinomial logistic regression(多项Logistic回归

通过多项Logistic(softmax)回归支持多类分类。 在多项Logistic回归中,该算法产生K个系数集,或K×J矩阵,其中K是结果类的数量,J是特征数。 如果算法与截距项拟合,则截距的长度K向量是可用的。

多项式系数可用作系数矩阵,截距可作为interceptVector使用。
不支持用多项式族训练的逻辑回归模型的系数和截距方法。 改用系数矩阵和interceptVector。
使用softmax函数对结果类k∈1,2,...,K的条件概率进行建模。

我们使用多项式响应模型将加权负对数似然值最小化,并用弹性网络惩罚来控制过拟合。
有关详细的推导,请参见这里
示例
以下示例展示了如何使用弹性网络正则化来训练多元逻辑回归模型。

 

Scala
import org.apache.spark.ml.classification.LogisticRegression

// Load training data
val training = spark
  .read
  .format("libsvm")
  .load("data/mllib/sample_multiclass_classification_data.txt")

val lr = new LogisticRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)

// Fit the model
val lrModel = lr.fit(training)

// Print the coefficients and intercept for multinomial logistic regression
println(s"Coefficients: \n${lrModel.coefficientMatrix}")
println(s"Intercepts: ${lrModel.interceptVector}")
 查找Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/MulticlassLogisticRegressionWithElasticNetExample.scala”的完整示例代码。
 

Decision tree classifier(决策树分类器

决策树是一种流行的分类和回归方法。有关spark.ml实现的更多信息,请参见决策树部分

 示例

以下示例以LibSVM格式加载数据集,将其拆分为训练和测试集,在第一个数据集上训练,然后对所保留的测试集进行评估。 我们使用两个特征变压器来准备数据; 这些帮助索引类别的标签和分类功能,添加元数据到决策树算法可以识别的DataFrame。

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.classification.DecisionTreeClassificationModel
import org.apache.spark.ml.classification.DecisionTreeClassifier
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}

// Load the data stored in LIBSVM format as a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Index labels, adding metadata to the label column.
// Fit on whole dataset to include all labels in index.
val labelIndexer = new StringIndexer()
  .setInputCol("label")
  .setOutputCol("indexedLabel")
  .fit(data)
// Automatically identify categorical features, and index them.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4) // features with > 4 distinct values are treated as continuous.
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a DecisionTree model.
val dt = new DecisionTreeClassifier()
  .setLabelCol("indexedLabel")
  .setFeaturesCol("indexedFeatures")

// Convert indexed labels back to original labels.
val labelConverter = new IndexToString()
  .setInputCol("prediction")
  .setOutputCol("predictedLabel")
  .setLabels(labelIndexer.labels)

// Chain indexers and tree in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(labelIndexer, featureIndexer, dt, labelConverter))

// Train model. This also runs the indexers.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("predictedLabel", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("indexedLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("Test Error = " + (1.0 - accuracy))

val treeModel = model.stages(2).asInstanceOf[DecisionTreeClassificationModel]
println("Learned classification tree model:\n" + treeModel.toDebugString)

有关参数的更多详细信息,请参见Scala API文档

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/DecisionTreeClassificationExample.scala”中查找完整示例代码。

 

Random forest classifier(随机森林分类

随机森林是一类受欢迎的分类和回归方法。有关spark.ml实现的更多信息,请参见随机林部分。

 示例

以下示例以LibSVM格式加载数据集,将其拆分为训练和测试集,在第一个数据集上训练,然后对所保留的测试集进行评估。 我们使用两个特征变压器来准备数据; 这些帮助索引类别的标签和分类功能,添加元数据到基于树的算法可以识别的DataFrame。

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.classification.{RandomForestClassificationModel, RandomForestClassifier}
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}

// Load and parse the data file, converting it to a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Index labels, adding metadata to the label column.
// Fit on whole dataset to include all labels in index.
val labelIndexer = new StringIndexer()
  .setInputCol("label")
  .setOutputCol("indexedLabel")
  .fit(data)
// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a RandomForest model.
val rf = new RandomForestClassifier()
  .setLabelCol("indexedLabel")
  .setFeaturesCol("indexedFeatures")
  .setNumTrees(10)

// Convert indexed labels back to original labels.
val labelConverter = new IndexToString()
  .setInputCol("prediction")
  .setOutputCol("predictedLabel")
  .setLabels(labelIndexer.labels)

// Chain indexers and forest in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(labelIndexer, featureIndexer, rf, labelConverter))

// Train model. This also runs the indexers.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("predictedLabel", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("indexedLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("Test Error = " + (1.0 - accuracy))

val rfModel = model.stages(2).asInstanceOf[RandomForestClassificationModel]
println("Learned classification forest model:\n" + rfModel.toDebugString)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/RandomForestClassifierExample.scala”中查找完整示例代码。


Gradient-boosted tree classifier(梯度增强树分类器

梯度增强树(GBT)是使用决策树组合的流行分类和回归方法。 有关spark.ml实现的更多信息,请参见GBT部分

Example

以下示例以LibSVM格式加载数据集,将其分解为训练和测试集,在第一个数据集上训练,然后在被测试的集合上进行训练。 我们使用两个特征变压器来准备数据; 这些帮助索引类别的标签和分类功能,添加元数据到基于树的算法可以识别的DataFrame

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.classification.{GBTClassificationModel, GBTClassifier}
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}

// Load and parse the data file, converting it to a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Index labels, adding metadata to the label column.
// Fit on whole dataset to include all labels in index.
val labelIndexer = new StringIndexer()
  .setInputCol("label")
  .setOutputCol("indexedLabel")
  .fit(data)
// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a GBT model.
val gbt = new GBTClassifier()
  .setLabelCol("indexedLabel")
  .setFeaturesCol("indexedFeatures")
  .setMaxIter(10)

// Convert indexed labels back to original labels.
val labelConverter = new IndexToString()
  .setInputCol("prediction")
  .setOutputCol("predictedLabel")
  .setLabels(labelIndexer.labels)

// Chain indexers and GBT in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(labelIndexer, featureIndexer, gbt, labelConverter))

// Train model. This also runs the indexers.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("predictedLabel", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("indexedLabel")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("Test Error = " + (1.0 - accuracy))

val gbtModel = model.stages(2).asInstanceOf[GBTClassificationModel]
println("Learned classification GBT model:\n" + gbtModel.toDebugString)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/GradientBoostedTreeClassifierExample.scala”中查找完整示例代码。


Multilayer perceptron classifier(多层感知器分类器)

多层感知器分类器(MLPC)是基于前馈人工神经网络的分类器。 MLPC由多层节点组成。 每个层完全连接到网络中的下一层。 输入层中的节点表示输入数据。 所有其他节点通过输入与节点权重ww和偏差bb的线性组合将输入映射到输出,并应用激活功能。 这可以用矩阵形式写入具有K + 1层的MLPC,如下所示:

中间层节点使用Sigmoid(logistic)函数:

输出层节点使用softmax函数:

               

输出层中的节点数N对应于类的数量。

MLPC采用反向传播来学习模型。我们使用物流损失函数进行优化和L-BFGS作为优化程序。

Example

 

Scala
import org.apache.spark.ml.classification.MultilayerPerceptronClassifier
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator

// Load the data stored in LIBSVM format as a DataFrame.
val data = spark.read.format("libsvm")
  .load("data/mllib/sample_multiclass_classification_data.txt")

// Split the data into train and test
val splits = data.randomSplit(Array(0.6, 0.4), seed = 1234L)
val train = splits(0)
val test = splits(1)

// specify layers for the neural network:
// input layer of size 4 (features), two intermediate of size 5 and 4
// and output of size 3 (classes)
val layers = Array[Int](4, 5, 4, 3)

// create the trainer and set its parameters
val trainer = new MultilayerPerceptronClassifier()
  .setLayers(layers)
  .setBlockSize(128)
  .setSeed(1234L)
  .setMaxIter(100)

// train the model
val model = trainer.fit(train)

// compute accuracy on the test set
val result = model.transform(test)
val predictionAndLabels = result.select("prediction", "label")
val evaluator = new MulticlassClassificationEvaluator()
  .setMetricName("accuracy")

println("Test set accuracy = " + evaluator.evaluate(predictionAndLabels))

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/MultilayerPerceptronClassifierExample.scala”中查找完整示例代码。

One-vs-Rest classifier (a.k.a. One-vs-All)( 一对一休息分类器(a.k.a.一对全) 

OneVsRest是用于执行多类别分类的机器学习简化的示例,给定可以有效地执行二进制分类的基本分类器。它也被称为“一对一”。

OneVsRest作为估计器实现。对于基类分类器,它需要分类器的实例,并为每个k类创建二进制分类问题。对i类的分类器进行训练,以预测标签是否为我,将i类与所有其他类区分开来。
预测是通过评估每个二进制分类器来完成的,最可靠的分类器的索引作为标签输出。
Example
下面的示例演示如何加载Iris数据集,将其解析为DataFrame,并使用OneVsRest执行多类分类。计算出测试误差来测量算法的准确性。

 

Scala
import org.apache.spark.ml.classification.{LogisticRegression, OneVsRest}
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator

// load data file.
val inputData = spark.read.format("libsvm")
  .load("data/mllib/sample_multiclass_classification_data.txt")

// generate the train/test split.
val Array(train, test) = inputData.randomSplit(Array(0.8, 0.2))

// instantiate the base classifier
val classifier = new LogisticRegression()
  .setMaxIter(10)
  .setTol(1E-6)
  .setFitIntercept(true)

// instantiate the One Vs Rest Classifier.
val ovr = new OneVsRest().setClassifier(classifier)

// train the multiclass model.
val ovrModel = ovr.fit(train)

// score the model on test data.
val predictions = ovrModel.transform(test)

// obtain evaluator.
val evaluator = new MulticlassClassificationEvaluator()
  .setMetricName("accuracy")

// compute the classification error on test data.
val accuracy = evaluator.evaluate(predictions)
println(s"Test Error = ${1 - accuracy}")

请参阅Scala的API文档的更多细节

查找Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/OneVsRestExample.scala”的完整示例代码。

Naive Bayes(朴素贝叶斯

朴素贝叶斯分类器是一个简单概率分类器的家族,基于贝叶斯定理与特征之间的强烈(天真)独立假设。spark.ml实现目前支持多项朴素贝叶斯伯努利天真贝叶斯。有关更多信息,请参阅MLlib中Naive Bayes部分

Example

Scala
import org.apache.spark.ml.classification.NaiveBayes
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator

// Load the data stored in LIBSVM format as a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Split the data into training and test sets (30% held out for testing)
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3), seed = 1234L)

// Train a NaiveBayes model.
val model = new NaiveBayes()
  .fit(trainingData)

// Select example rows to display.
val predictions = model.transform(testData)
predictions.show()

// Select (prediction, true label) and compute test error
val evaluator = new MulticlassClassificationEvaluator()
  .setLabelCol("label")
  .setPredictionCol("prediction")
  .setMetricName("accuracy")
val accuracy = evaluator.evaluate(predictions)
println("Test set accuracy = " + accuracy)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/NaiveBayesExample.scala”中查找完整示例代码。

 

Regression(回归)

Linear regression(线性回归

使用线性回归模型和模型摘要的界面类似于逻辑回归案例。 

在使用“l-bfgs”求解器的常量非零列的数据集上对LinearRegressionModel进行拟合时,Spark MLlib为常数非零列输出零系数。此行为与R glmnet相同,但与LIBSVM不同。

Example

以下示例演示了训练弹性网络正则化线性回归模型并提取模型汇总统计量。

Scala
import org.apache.spark.ml.regression.LinearRegression

// Load training data
val training = spark.read.format("libsvm")
  .load("data/mllib/sample_linear_regression_data.txt")

val lr = new LinearRegression()
  .setMaxIter(10)
  .setRegParam(0.3)
  .setElasticNetParam(0.8)

// Fit the model
val lrModel = lr.fit(training)

// Print the coefficients and intercept for linear regression
println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")

// Summarize the model over the training set and print out some metrics
val trainingSummary = lrModel.summary
println(s"numIterations: ${trainingSummary.totalIterations}")
println(s"objectiveHistory: [${trainingSummary.objectiveHistory.mkString(",")}]")
trainingSummary.residuals.show()
println(s"RMSE: ${trainingSummary.rootMeanSquaredError}")
println(s"r2: ${trainingSummary.r2}")

有关参数的更多详细信息,请参见Scala API文档

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/LinearRegressionWithElasticNetExample.scala”中查找完整示例代码。

 

Generalized linear regression(广义线性回归

与线性回归相比,输出被假设为跟随高斯分布,广义线性模型(GLM)是线性模型的规范,其中响应变量Yi遵循指数族分布的一些分布。 Spark的GeneralizedLinearRegression界面允许灵活的GLM规范,可用于各种类型的预测问题,包括线性回归,泊松回归,逻辑回归等。 目前在spark.ml中,仅支持指数族分布的一部分,下面列出它们。

NOTESpark目前仅通过其GeneralizedLinearRegression接口支持多达4096个功能,如果超出此约束,则会抛出异常。 有关详细信息,请参阅高级部分。 然而,对于线性和逻辑回归,可以使用线性回归和逻辑回归估计器来训练具有增加的特征数量的模型。

GLM需要指数族分布,可以用他们的“canonical(规范)”或“natural(自然)”形式,即自然指数族分布。 自然指数族分布的形式如下:

其中θ是感兴趣的参数,τ是色散参数。在GLM中,假设响应变量YiYi是从自然指数族分布中得出的:

其中感兴趣的参数θi与响应变量μi的预期值相关

这里,A'(θi) 由所选分布的形式定义。 GLM还允许指定链接功能,其定义响应变量μi的期望值与所谓的线性预测器ηi之间的关系:

通常,选择链接函数使得A'= g-1,其产生关注参数θθ和线性预测器η之间的简化关系。 在这种情况下,链接函数 g(μ) 被称为“canonical(规范)”链接功能。

 

GLM找到使似然函数最大化的回归系数

其中感兴趣的参数θi与回归系数相关

Spark的广义线性回归界面还提供诊断GLM模型拟合的汇总统计量,包括残差,p值,偏差,Akaike信息准则等。

参见这里,对GLM及其应用进行更全面的综述。


 

Available families(有用家族)

Family Response Type Supported Links
Gaussian Continuous Identity*, Log, Inverse
Binomial Binary Logit*, Probit, CLogLog
Poisson Count Log*, Identity, Sqrt
Gamma Continuous Inverse*, Idenity, Log

* 规范链接

Example

以下示例演示了使用高斯响应和身份链接功能训练GLM并提取模型汇总统计信息。

Scala
import org.apache.spark.ml.regression.GeneralizedLinearRegression

// Load training data
val dataset = spark.read.format("libsvm")
  .load("data/mllib/sample_linear_regression_data.txt")

val glr = new GeneralizedLinearRegression()
  .setFamily("gaussian")
  .setLink("identity")
  .setMaxIter(10)
  .setRegParam(0.3)

// Fit the model
val model = glr.fit(dataset)

// Print the coefficients and intercept for generalized linear regression model
println(s"Coefficients: ${model.coefficients}")
println(s"Intercept: ${model.intercept}")

// Summarize the model over the training set and print out some metrics
val summary = model.summary
println(s"Coefficient Standard Errors: ${summary.coefficientStandardErrors.mkString(",")}")
println(s"T Values: ${summary.tValues.mkString(",")}")
println(s"P Values: ${summary.pValues.mkString(",")}")
println(s"Dispersion: ${summary.dispersion}")
println(s"Null Deviance: ${summary.nullDeviance}")
println(s"Residual Degree Of Freedom Null: ${summary.residualDegreeOfFreedomNull}")
println(s"Deviance: ${summary.deviance}")
println(s"Residual Degree Of Freedom: ${summary.residualDegreeOfFreedom}")
println(s"AIC: ${summary.aic}")
println("Deviance Residuals: ")
summary.residuals().show()

 请参阅Scala的API文档的更多细节 

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/GeneralizedLinearRegressionExample.scala”中查找完整示例代码。

 

Decision tree regression(决策树回归

决策树是一种流行的分类和回归方法。有关spark.ml实现的更多信息,请参见决策树部分

Example

以下示例以LibSVM格式加载数据集,将其拆分为训练和测试集,在第一个数据集上训练,然后对所保留的测试集进行评估。我们使用特征变换器来对分类特征进行索引,将元数据添加到决策树算法可以识别的DataFrame中。

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.evaluation.RegressionEvaluator
import org.apache.spark.ml.feature.VectorIndexer
import org.apache.spark.ml.regression.DecisionTreeRegressionModel
import org.apache.spark.ml.regression.DecisionTreeRegressor

// Load the data stored in LIBSVM format as a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Automatically identify categorical features, and index them.
// Here, we treat features with > 4 distinct values as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a DecisionTree model.
val dt = new DecisionTreeRegressor()
  .setLabelCol("label")
  .setFeaturesCol("indexedFeatures")

// Chain indexer and tree in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(featureIndexer, dt))

// Train model. This also runs the indexer.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("prediction", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new RegressionEvaluator()
  .setLabelCol("label")
  .setPredictionCol("prediction")
  .setMetricName("rmse")
val rmse = evaluator.evaluate(predictions)
println("Root Mean Squared Error (RMSE) on test data = " + rmse)

val treeModel = model.stages(1).asInstanceOf[DecisionTreeRegressionModel]
println("Learned regression tree model:\n" + treeModel.toDebugString)

有关参数的更多详细信息,请参见Scala API文档 

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/DecisionTreeRegressionExample.scala”中查找完整示例代码。

Random forest regression(随机森林回归

随机森林是一类受欢迎的分类和回归方法。有关spark.ml实现的更多信息,请参见随机林部分

Example

以下示例以LibSVM格式加载数据集,将其拆分为训练和测试集,在第一个数据集上训练,然后对所保留的测试集进行评估。我们使用特征变换器对分类特征进行索引,将元数据添加到基于树的算法可以识别的DataFrame中。我们使用特征变换器对分类特征进行索引,将元数据添加到基于树的算法可以识别的DataFrame中。

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.evaluation.RegressionEvaluator
import org.apache.spark.ml.feature.VectorIndexer
import org.apache.spark.ml.regression.{RandomForestRegressionModel, RandomForestRegressor}

// Load and parse the data file, converting it to a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a RandomForest model.
val rf = new RandomForestRegressor()
  .setLabelCol("label")
  .setFeaturesCol("indexedFeatures")

// Chain indexer and forest in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(featureIndexer, rf))

// Train model. This also runs the indexer.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("prediction", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new RegressionEvaluator()
  .setLabelCol("label")
  .setPredictionCol("prediction")
  .setMetricName("rmse")
val rmse = evaluator.evaluate(predictions)
println("Root Mean Squared Error (RMSE) on test data = " + rmse)

val rfModel = model.stages(1).asInstanceOf[RandomForestRegressionModel]
println("Learned regression forest model:\n" + rfModel.toDebugString)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/RandomForestRegressorExample.scala”中查找完整示例代码。

 

Gradient-boosted tree regression(梯度增强树回归

梯度增强树(GBT)是使用决策树组合的流行回归方法。有关spark.ml实现的更多信息,请参见GBT部分
Example
注意:对于此示例数据集,GBTRegressor实际上只需要1次迭代,但这一般不会是真的。

 

Scala
import org.apache.spark.ml.Pipeline
import org.apache.spark.ml.evaluation.RegressionEvaluator
import org.apache.spark.ml.feature.VectorIndexer
import org.apache.spark.ml.regression.{GBTRegressionModel, GBTRegressor}

// Load and parse the data file, converting it to a DataFrame.
val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")

// Automatically identify categorical features, and index them.
// Set maxCategories so features with > 4 distinct values are treated as continuous.
val featureIndexer = new VectorIndexer()
  .setInputCol("features")
  .setOutputCol("indexedFeatures")
  .setMaxCategories(4)
  .fit(data)

// Split the data into training and test sets (30% held out for testing).
val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))

// Train a GBT model.
val gbt = new GBTRegressor()
  .setLabelCol("label")
  .setFeaturesCol("indexedFeatures")
  .setMaxIter(10)

// Chain indexer and GBT in a Pipeline.
val pipeline = new Pipeline()
  .setStages(Array(featureIndexer, gbt))

// Train model. This also runs the indexer.
val model = pipeline.fit(trainingData)

// Make predictions.
val predictions = model.transform(testData)

// Select example rows to display.
predictions.select("prediction", "label", "features").show(5)

// Select (prediction, true label) and compute test error.
val evaluator = new RegressionEvaluator()
  .setLabelCol("label")
  .setPredictionCol("prediction")
  .setMetricName("rmse")
val rmse = evaluator.evaluate(predictions)
println("Root Mean Squared Error (RMSE) on test data = " + rmse)

val gbtModel = model.stages(1).asInstanceOf[GBTRegressionModel]
println("Learned regression GBT model:\n" + gbtModel.toDebugString)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/GradientBoostedTreeRegressorExample.scala”中查找完整示例代码。

Survival regression(生存回归

在spark.ml中,我们实现了加速失效时间(AFT)模型,该模型是用于截尾数据的参数生存回归模型。 它描述了生存时间对数的模型,因此通常将其称为生存分析的对数线性模型。 与为同一目的设计的比例危害模型不同,AFT模型更容易并行化,因为每个实例独立地有助于目标函数。

给定协变量x'的值,对于主体i = 1,...,n的随机寿命 ti,具有可能的右检查,AFT模型下的似然函数给出为:

其中 是事件发生的指示符,即未被审查。使用 ,对数似然函数假设为:

其中  和基线幸存者功能,和 和相应的密度函数。

最常用的AFT模型是基于Weibull分布的生存时间。寿命的威布尔分布对应于寿命日志的极值分布,函数为:

函数为:

具有威布尔寿命分布的AFT模型的对数似然函数为:

由于最小化与最大后验概率相等的负对数似然,我们用于优化的损失函数为。 β和log⁡σ的梯度函数分别为:

AFT模型可以表示为凸优化问题,即根据系数向量ββ和比例参数对数,找到凸函数的最小值的任务log⁡σ。实现的优化算法是L-BFGS。该实现与R的存活功能的结果相匹配

当在固定非零列的数据集上对AFTSurvivalRegressionModel进行拟合时,Spark MLlib将为常数非零列输出零系数。这种行为与R存活::幸存者不同。

Example

Scala
import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.ml.regression.AFTSurvivalRegression

val training = spark.createDataFrame(Seq(
  (1.218, 1.0, Vectors.dense(1.560, -0.605)),
  (2.949, 0.0, Vectors.dense(0.346, 2.158)),
  (3.627, 0.0, Vectors.dense(1.380, 0.231)),
  (0.273, 1.0, Vectors.dense(0.520, 1.151)),
  (4.199, 0.0, Vectors.dense(0.795, -0.226))
)).toDF("label", "censor", "features")
val quantileProbabilities = Array(0.3, 0.6)
val aft = new AFTSurvivalRegression()
  .setQuantileProbabilities(quantileProbabilities)
  .setQuantilesCol("quantiles")

val model = aft.fit(training)

// Print the coefficients, intercept and scale parameter for AFT survival regression
println(s"Coefficients: ${model.coefficients}")
println(s"Intercept: ${model.intercept}")
println(s"Scale: ${model.scale}")
model.transform(training).show(false)

请参阅Scala的API文档的更多细节

在Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/AFTSurvivalRegressionExample.scala”中查找完整示例代码。

Isotonic regression(保序回归

保序回归属于回归算法族。 正则等式回归是一个问题,其中给出了一个有限的实数集Y = y1,y2,...,表示观察到的响应,X = x1,x2,...,xn 要拟合的未知响应值,找到最小化的函数

对于满足x1≤x2≤...≤xn的完整订单,其中wiwi是正权重。所得到的函数称为等渗回归,它是唯一的。它可以被视为订单限制下的最小二乘问题。基本等渗回归是最接近原始数据点的单调函数。

我们实施一个相邻违反算法的池,它使用一种方法来平行等渗回归。训练输入是一个DataFrame,它包含三列标签,特征和重量。另外,IsotonicRegression算法有一个可选参数,称为等渗偏差默认为true。这个参数指定等渗回归是等渗的(单调递增)还是反对(单调递减)。

训练返回一个可以用于预测已知和未知特征的标签的等渗回归模型。等渗回归的结果被视为分段线性函数。因此,预测规则是:

  • 如果预测输入与训练特征完全匹配,则返回相关预测。 如果有多个具有相同特征的预测,则返回其中一个。 哪一个是未定义的(与java.util.Arrays.binarySearch相同)。
  • 如果预测输入低于或高于所有训练特征,则返回具有最低或最高特征的预测。 如果存在具有相同特征的多个预测,则分别返回最低或最高。
  • 如果预测输入落在两个训练特征之间,则预测被视为分段线性函数,并且根据两个最接近的特征的预测来计算内插值。 如果有多个具有相同特征的值,则使用与前一点相同的规则。

Examples

Scala
import org.apache.spark.ml.regression.IsotonicRegression

// Loads data.
val dataset = spark.read.format("libsvm")
  .load("data/mllib/sample_isotonic_regression_libsvm_data.txt")

// Trains an isotonic regression model.
val ir = new IsotonicRegression()
val model = ir.fit(dataset)

println(s"Boundaries in increasing order: ${model.boundaries}\n")
println(s"Predictions associated with the boundaries: ${model.predictions}\n")

// Makes predictions.
model.transform(dataset).show()

有关API的详细信息,请参阅IsotonicRegression Scala文档 

查找Spark repo中的“examples/src/main/scala/org/apache/spark/examples/ml/IsotonicRegressionExample.scala”的完整示例代码。

 

Linear methods(线性方法)

我们通过L1、L2正则化实现了逻辑回归和线性最小二乘法等常用的线性方法。关于实现和调优的详细信息请参考线性方法指南(RDD-based API )。


我们也提供了Elastic net的DataFrame API。它发表在Zou et al, Regularization and variable selection via the elastic net,是L1、L2正则化的混合。在数学上定义为L1和L2正则项的凸组合:

 

我们实现流行的线性方法,如逻辑回归和L1或L2正则化的线性最小二乘法。 有关实现和调优的详细信息,请参考基于RDD的API的线性方法指南; 这个信息仍然是有关系的。

我们还包括一个用于elastic net的DataFrame API,Zou等人提出的L1和L2正则化的混合,通过elastic net进行正则化和可变选择。 在数学上,它被定义为L1和L2正则化项的凸组合:

通过正确设置α,elastic net包含L1和L2正则化作为特殊情况。 例如,如果使用elastic net参数α设置为1来训练线性回归模型,则相当于Lasso模型。 另一方面,如果α设定为0,训练模型减少到  回归模型。 我们通过elastic net正规化来实现线性回归和逻辑回归的管道API。

 

Decision Tree(决策树)

决策树及其合奏是分类和回归机器学习任务的流行方法。决策树被广泛使用,因为它们易于解释,处理分类特征,扩展到多类分类设置,不需要特征缩放,并且能够捕获非线性和特征交互。诸如随机森林和提升等树的集成算法是分类和回归任务的最佳表现者之一。

spark.ml实现支持二分类、多分类和回归的决策树,使用连续和分类特征。该实现按行分隔数据,允许分布式培训,数百万甚至数十亿个实例。

用户可以在MLlib决策树指南中找到有关决策树算法的更多信息。该API和原始MLlib决策树API之间的主要区别是:

  • 支持ML管道
  • 决策树的分离与回归分离
  • 使用DataFrame元数据来区分连续和分类特征

决策树的管道API提供比原始API更多的功能。特别地,对于分类,用户可以得到每个类的预测概率(a.k.a.类条件概率);为了回归,用户可以获得预测的偏差样本方差。

树的集成方法【Random Forests (随机森林)和  Gradient-Boosted Trees(渐变树)】将在下面的 树的集成方法部分 中进行描述。

Inputs and Outputs(输入与输出)

我们在这里列出输入和输出(预测)列类型。所有输出列都是可选的;要排除输出列,将其对应的Param设置为空字符串。

Input Columns(输入列)

参数名称 类型 默认值 描述
labelCol Double "label" label预测
featuresCol Vector "features"

特征向量

Output Columns(输出列)

参数名称

类型

默认值

描述

笔记

predictionCol

Double

"prediction"

预测的 label

 

rawPredictionCol

Vector

"rawPrediction"

向量的长度#类,在树节点处的训练实例标签的计数进行预测

仅限分类

probabilityCol

Vector

"probability"

向量的长度#类 等于rawPrediction归一化为多项分布

仅限分类

varianceCol

Double

 

预测的偏差样本方差

仅限回归

Tree Ensambles(树集合)

DataFrame API 支持两种主要的数集合算法:Random Forests(随机森林)和(Gradient-Boosted Trees ,GBTs)(迭代树)。两者都用spark.ml决策树作为自己的基础模型。

用户可以在机器学习库-集合指南(mllib-ensembles guide)找到更多的集合算法。在这里,我们演示用于 Ensambles(集合) 的 DataFrame API 。

API 原始MLlib集合API(original MLlib ensembles API)的差异如下:

  • 支持 DataFrame 和机器学习管道( ML pipeline )。
  • 分类(classification )与回归(regression)的分离。
  • 使用DataFrame元数据( DataFrame metadata )来分辨特征( features )是持续的(continus)还是分类的(categorical)。
  • 随机森林有更多功能:: 评估特征( feature )重要性和分类( classification )中各类的预测概率(即条件概率)。

Random Forests(随机森林)

随机森林是 决策树的集合. 随机森林结合多多个决策树来避免 过拟合(overfitting) 带来的风险。 spark机器学习(spark.ml) 的实现支持持续的(continus)还是分类的(categorical)的特征,支持二元分类和多元分类的随机森林及回归。

更多关于算法本身的资料,可以查看链接 spark.mllib documentation on random forests.

Inputs and Outputs(输入与输出)

我们在这里列举了输入和输出(预测)列类型。所有的输出列都是可选的;要排除输出列,就把对应参数设为空字符串。

Input Columns(输入列)

参数名称 类型 默认值 描述
labelCol Double "label" 要预测的标签(Label to predict)
featuresCol Vector "features" 特征向量(Feature vector)

Output Columns(Predictions)输出列(预测)

参数名称 类型 默认值 描述 注意
predictionCol Double "prediction" 预测后的标签(Predicted label)  
rawPredictionCol Vector "rawPrediction" 长度向量,类及用于预测的树节点上的训练实例标签数量。 只用于分类
probabilityCol Vector "probability" 长度向量,与rawPrediction 相等的类被正则化为多元分布。 只用于分类

Gradient-Boosted Trees(GBTs) 

Gradient-Boosted Trees (GBTs) 是 决策树的集合. GBTs 迭代决策树以最小化 loss function(损失函数) spark机器学习库 的实现使用 持续的(continus)  分类的(categorical) 的特征来支持 GBTs ,以用于 二元分类(binary classification)回归(regression) 。 

更多关于算法本身的资料,可以查看链接 spark.mllib documentation on GBTs.

Inputs and Outputs(输入和输出)

我们在这里列举了输入和输出(预测)列类型。所有的输出列都是可选的;要排除输出列,就把对应参数设为空字符串。

Input Columns(输入列)

参数名称 类型(s) 默认值 描述
labelCol Double "label" 要预测的标签(Label to predict)
featuresCol Vector "features" 特征向量(Feature vector)

注意:GBTClassifier目前只支持 二元标签( binary labels.) 

Output Columns(Predictions)输出列(预测)

参数名称 类型(s) 默认值 描述 注意点
predictionCol Double "prediction" Predicted label  

在以后,GBTClassifier将会支持 rawPrediction 和 probability 输出列,跟 RandomForestClassifier 一样。