逻辑回归算法原理及Spark MLlib调用实例(Scala/Java/python)

逻辑回归

算法原理:

        逻辑回归是一个流行的二分类问题预测方法。它是Generalized Linear models 的一个特殊应用以预测结果概率。它是一个线性模型如下列方程所示,其中损失函数为逻辑损失:

 

 

        对于二分类问题,算法产出一个二值逻辑回归模型。给定一个新数据,由x表示,则模型通过下列逻辑方程来预测:

 

 

        其中 。默认情况下,如果 ,结果为正,否则为负。和线性SVMs不同,逻辑回归的原始输出有概率解释(x为正的概率)。

        二分类逻辑回归可以扩展为多分类逻辑回归来训练和预测多类别分类问题。如一个分类问题有K种可能结果,我们可以选取其中一种结果作为“中心点“,其他K-1个结果分别视为中心点结果的对立点。在spark.mllib中,取第一个类别为中心点类别。

*目前spark.ml逻辑回归工具仅支持二分类问题,多分类回归将在未来完善。

*当使用无拦截的连续非零列训练LogisticRegressionModel时,Spark MLlib为连续非零列输出零系数。这种处理不同于libsvm与R glmnet相似。

参数:

elasticNetParam:

类型:双精度型。

含义:弹性网络混合参数,范围[0,1]。

featuresCol:

类型:字符串型。

含义:特征列名。

fitIntercept:

类型:布尔型。

含义:是否训练拦截对象。

labelCol:

类型:字符串型。

含义:标签列名。

maxIter:

类型:整数型。

含义:最多迭代次数(>=0)。

predictionCol:

类型:字符串型。

含义:预测结果列名。

probabilityCol:

类型:字符串型。

含义:用以预测类别条件概率的列名。

regParam:

类型:双精度型。

含义:正则化参数(>=0)。

standardization:

类型:布尔型。

含义:训练模型前是否需要对训练特征进行标准化处理。

threshold:

类型:双精度型。

含义:二分类预测的阀值,范围[0,1]。

thresholds:

类型:双精度数组型。

含义:多分类预测的阀值,以调整预测结果在各个类别的概率。

tol:

类型:双精度型。

含义:迭代算法的收敛性。

weightCol:

类型:字符串型。

含义:列权重。

示例:

       下面的例子展示如何训练使用弹性网络正则化的逻辑回归模型。elasticNetParam对应于 ,regParam对应于 。

Scala:

 

[plain] view plain copy

 

  1. import org.apache.spark.ml.classification.LogisticRegression  
  2.   
  3. // Load training data  
  4. val training = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")  
  5.   
  6. val lr = new LogisticRegression()  
  7.   .setMaxIter(10)  
  8.   .setRegParam(0.3)  
  9.   .setElasticNetParam(0.8)  
  10.   
  11. // Fit the model  
  12. val lrModel = lr.fit(training)  
  13.   
  14. // Print the coefficients and intercept for logistic regression  
  15. println(s"Coefficients: ${lrModel.coefficients} Intercept: ${lrModel.intercept}")  

Java:

 

 

[java] view plain copy

 

  1. import org.apache.spark.ml.classification.LogisticRegression;  
  2. import org.apache.spark.ml.classification.LogisticRegressionModel;  
  3. import org.apache.spark.sql.Dataset;  
  4. import org.apache.spark.sql.Row;  
  5. import org.apache.spark.sql.SparkSession;  
  6.   
  7. // Load training data  
  8. Dataset<Row> training = spark.read().format("libsvm")  
  9.   .load("data/mllib/sample_libsvm_data.txt");  
  10.   
  11. LogisticRegression lr = new LogisticRegression()  
  12.   .setMaxIter(10)  
  13.   .setRegParam(0.3)  
  14.   .setElasticNetParam(0.8);  
  15.   
  16. // Fit the model  
  17. LogisticRegressionModel lrModel = lr.fit(training);  
  18.   
  19. // Print the coefficients and intercept for logistic regression  
  20. System.out.println("Coefficients: "  
  21.   + lrModel.coefficients() + " Intercept: " + lrModel.intercept());  

Python:

 

 

[python] view plain copy

 

  1. from pyspark.ml.classification import LogisticRegression  
  2.   
  3. # Load training data  
  4. training = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")  
  5.   
  6. lr = LogisticRegression(maxIter=10, regParam=0.3, elasticNetParam=0.8)  
  7.   
  8. # Fit the model  
  9. lrModel = lr.fit(training)  
  10.   
  11. # Print the coefficients and intercept for logistic regression  
  12. print("Coefficients: " + str(lrModel.coefficients))  
  13. print("Intercept: " + str(lrModel.intercept))  

 

        spark.ml逻辑回归工具同样支持提取模总结。LogisticRegressionTrainingSummary提供LogisticRegressionModel的总结。目前仅支持二分类问题,所以总结必须明确投掷到BinaryLogisticRegressionTrainingSummary。支持多分类问题后可能有所改善。

继续上面的例子:

Scala:

 

[plain] view plain copy

 

  1. import org.apache.spark.ml.Pipeline  
  2. import org.apache.spark.ml.classification.DecisionTreeClassificationModel  
  3. import org.apache.spark.ml.classification.DecisionTreeClassifier  
  4. import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator  
  5. import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer}  
  6.   
  7. // Load the data stored in LIBSVM format as a DataFrame.  
  8. val data = spark.read.format("libsvm").load("data/mllib/sample_libsvm_data.txt")  
  9.   
  10. // Index labels, adding metadata to the label column.  
  11. // Fit on whole dataset to include all labels in index.  
  12. val labelIndexer = new StringIndexer()  
  13.   .setInputCol("label")  
  14.   .setOutputCol("indexedLabel")  
  15.   .fit(data)  
  16. // Automatically identify categorical features, and index them.  
  17. val featureIndexer = new VectorIndexer()  
  18.   .setInputCol("features")  
  19.   .setOutputCol("indexedFeatures")  
  20.   .setMaxCategories(4) // features with > 4 distinct values are treated as continuous.  
  21.   .fit(data)  
  22.   
  23. // Split the data into training and test sets (30% held out for testing).  
  24. val Array(trainingData, testData) = data.randomSplit(Array(0.7, 0.3))  
  25.   
  26. // Train a DecisionTree model.  
  27. val dt = new DecisionTreeClassifier()  
  28.   .setLabelCol("indexedLabel")  
  29.   .setFeaturesCol("indexedFeatures")  
  30.   
  31. // Convert indexed labels back to original labels.  
  32. val labelConverter = new IndexToString()  
  33.   .setInputCol("prediction")  
  34.   .setOutputCol("predictedLabel")  
  35.   .setLabels(labelIndexer.labels)  
  36.   
  37. // Chain indexers and tree in a Pipeline.  
  38. val pipeline = new Pipeline()  
  39.   .setStages(Array(labelIndexer, featureIndexer, dt, labelConverter))  
  40.   
  41. // Train model. This also runs the indexers.  
  42. val model = pipeline.fit(trainingData)  
  43.   
  44. // Make predictions.  
  45. val predictions = model.transform(testData)  
  46.   
  47. // Select example rows to display.  
  48. predictions.select("predictedLabel", "label", "features").show(5)  
  49.   
  50. // Select (prediction, true label) and compute test error.  
  51. val evaluator = new MulticlassClassificationEvaluator()  
  52.   .setLabelCol("indexedLabel")  
  53.   .setPredictionCol("prediction")  
  54.   .setMetricName("accuracy")  
  55. val accuracy = evaluator.evaluate(predictions)  
  56. println("Test Error = " + (1.0 - accuracy))  
  57.   
  58. val treeModel = model.stages(2).asInstanceOf[DecisionTreeClassificationModel]  
  59. println("Learned classification tree model:\n" + treeModel.toDebugString)  

Java:

 

 

[python] view plain copy

 

  1. import org.apache.spark.ml.Pipeline;  
  2. import org.apache.spark.ml.PipelineModel;  
  3. import org.apache.spark.ml.PipelineStage;  
  4. import org.apache.spark.ml.classification.DecisionTreeClassifier;  
  5. import org.apache.spark.ml.classification.DecisionTreeClassificationModel;  
  6. import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator;  
  7. import org.apache.spark.ml.feature.*;  
  8. import org.apache.spark.sql.Dataset;  
  9. import org.apache.spark.sql.Row;  
  10. import org.apache.spark.sql.SparkSession;  
  11.   
  12. // Load the data stored in LIBSVM format as a DataFrame.  
  13. Dataset<Row> data = spark  
  14.   .read()  
  15.   .format("libsvm")  
  16.   .load("data/mllib/sample_libsvm_data.txt");  
  17.   
  18. // Index labels, adding metadata to the label column.  
  19. // Fit on whole dataset to include all labels in index.  
  20. StringIndexerModel labelIndexer = new StringIndexer()  
  21.   .setInputCol("label")  
  22.   .setOutputCol("indexedLabel")  
  23.   .fit(data);  
  24.   
  25. // Automatically identify categorical features, and index them.  
  26. VectorIndexerModel featureIndexer = new VectorIndexer()  
  27.   .setInputCol("features")  
  28.   .setOutputCol("indexedFeatures")  
  29.   .setMaxCategories(4) // features with > 4 distinct values are treated as continuous.  
  30.   .fit(data);  
  31.   
  32. // Split the data into training and test sets (30% held out for testing).  
  33. Dataset<Row>[] splits = data.randomSplit(new double[]{0.7, 0.3});  
  34. Dataset<Row> trainingData = splits[0];  
  35. Dataset<Row> testData = splits[1];  
  36.   
  37. // Train a DecisionTree model.  
  38. DecisionTreeClassifier dt = new DecisionTreeClassifier()  
  39.   .setLabelCol("indexedLabel")  
  40.   .setFeaturesCol("indexedFeatures");  
  41.   
  42. // Convert indexed labels back to original labels.  
  43. IndexToString labelConverter = new IndexToString()  
  44.   .setInputCol("prediction")  
  45.   .setOutputCol("predictedLabel")  
  46.   .setLabels(labelIndexer.labels());  
  47.   
  48. // Chain indexers and tree in a Pipeline.  
  49. Pipeline pipeline = new Pipeline()  
  50.   .setStages(new PipelineStage[]{labelIndexer, featureIndexer, dt, labelConverter});  
  51.   
  52. // Train model. This also runs the indexers.  
  53. PipelineModel model = pipeline.fit(trainingData);  
  54.   
  55. // Make predictions.  
  56. Dataset<Row> predictions = model.transform(testData);  
  57.   
  58. // Select example rows to display.  
  59. predictions.select("predictedLabel", "label", "features").show(5);  
  60.   
  61. // Select (prediction, true label) and compute test error.  
  62. MulticlassClassificationEvaluator evaluator = new MulticlassClassificationEvaluator()  
  63.   .setLabelCol("indexedLabel")  
  64.   .setPredictionCol("prediction")  
  65.   .setMetricName("accuracy");  
  66. double accuracy = evaluator.evaluate(predictions);  
  67. System.out.println("Test Error = " + (1.0 - accuracy));  
  68.   
  69. DecisionTreeClassificationModel treeModel =  
  70.   (DecisionTreeClassificationModel) (model.stages()[2]);  
  71. System.out.println("Learned classification tree model:\n" + treeModel.toDebugString());  

 

 

转载于:https://my.oschina.net/hblt147/blog/1596832

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值