Spark机器学习库MLlib编程实践

Spark机器学习库MLlib编程实践

文章目录

  • Spark机器学习库MLlib编程实践
      1. 写在前面
      1. 正文
      • 1.1 案例目的
      • 1.2 案例
        • 1.2.1 数据导入
        • 1.2.2 进行主成分分析(**PCA**)
        • 1.2.3 训练分类模型并预测居民收入
        • 1.2.4 超参数调优
      • 1.3 数据集展示
      • 1.4 程序编写

0. 写在前面

  • 操作系统:Linux(CentOS7.5)
  • Spark版本:Spark3.0.0
  • Scala版本:Scala2.12.1

1. 正文

1.1 案例目的

  • 通过实验掌握基本的MLLib编程方法;

  • 掌握用MLLib解决一些常见的数据分析问题,包括数据导入、成分分析和分类和预测等。

1.2 案例

1.2.1 数据导入

从文件中导入数据,并转化为DataFrame。

1.2.2 进行主成分分析(PCA

对6个连续型的数值型变量进行主成分分析。PCA(主成分分析)是通过正交变换把一组相关变量的观测值转化成一组线性无关的变量值,即主成分的一种方法。PCA通过使用主成分把特征向量投影到低维空间,实现对特征向量的降维。请通过setK()方法将主成分数量设置为3,把连续型的特征向量转化成一个3维的主成分。

1.2.3 训练分类模型并预测居民收入

在主成分分析的基础上,采用逻辑斯蒂回归,或者决策树模型预测居民收入是否超过50K;对Test数据集进行验证。

1.2.4 超参数调优

利用CrossValidator确定最优的参数,包括最优主成分PCA的维数、分类器自身的参数等。

1.3 数据集展示

  • 数据集
  • 测试集

1.4 程序编写

本案例是在Spark-Shell环境下执行的

  • (1)针对数据导入,提前导入必要的包,如下所示
scala 复制代码
import org.apache.spark.ml.feature.PCA
import org.apache.spark.sql.Row
import org.apache.spark.ml.linalg.{Vector,Vectors}
import org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import org.apache.spark.ml.{Pipeline,PipelineModel}
import org.apache.spark.ml.feature.{IndexToString, StringIndexer, VectorIndexer,HashingTF, Tokenizer}
import org.apache.spark.ml.classification.LogisticRegression
import org.apache.spark.ml.classification.LogisticRegressionModel
import org.apache.spark.ml.classification.{BinaryLogisticRegressionSummary, LogisticRegression}
import org.apache.spark.sql.functions
import org.apache.spark.ml.tuning.{ CrossValidator, CrossValidatorModel, ParamGridBuilder }
  • 将数据集转换为DataFrame
scala 复制代码
import spark.implicits._
case class Adult(features: org.apache.spark.ml.linalg.Vector, label: String)

val df = sc.textFile("/export/server/spark-3.0.0-bin-hadoop3.2/adult.data.txt").map(_.split(",")).map(p => Adult(Vectors.dense(p(0).toDouble,p(2).toDouble,p(4).toDouble, p(10).toDouble, p(11).toDouble, p(12).toDouble), p(14).toString())).toDF()
  • (2)读取数据集和测试集,进行主成分分析(PCA
scala 复制代码
val test = sc.textFile("/export/server/spark-3.0.0-bin-hadoop3.2/adult.test.txt").map(_.split(",")).map(p => Adult(Vectors.dense(p(0).toDouble,p(2).toDouble,p(4).toDouble, p(10).toDouble, p(11).toDouble, p(12).toDouble), p(14).toString())).toDF()

val pca = new PCA().setInputCol("features").setOutputCol("pcaFeatures").setK(3).fit(df)
val result = pca.transform(df)
val testdata = pca.transform(test)

result.show(false)
testdata.show(false)

可以看到数据集和测试集导入成功,如下图所示:

  • 数据集
  • 测试集
  • (3)训练分类模型并预测居民收入
scala 复制代码
val labelIndexer = new StringIndexer().setInputCol("label").setOutputCol("indexedLabel").fit(result)
labelIndexer.labels.foreach(println)
val featureIndexer = new VectorIndexer().setInputCol("pcaFeatures").setOutputCol("indexedFeatures").fit(result)
println(featureIndexer.numFeatures)
val labelConverter = new IndexToString().setInputCol("prediction").setOutputCol("predictedLabel").setLabels(labelIndexer.labels)
val lr = new LogisticRegression().setLabelCol("indexedLabel").setFeaturesCol("indexedFeatures").setMaxIter(100)
val lrPipeline = new Pipeline().setStages(Array(labelIndexer, featureIndexer, lr, labelConverter))
val lrPipelineModel = lrPipeline.fit(result)
val lrModel = lrPipelineModel.stages(2).asInstanceOf[LogisticRegressionModel]
println("Coefficients: " + lrModel.coefficientMatrix+"Intercept: "+lrModel.interceptVector+"numClasses: "+lrModel.numClasses+"numFeatures: "+lrModel.numFeatures)
val lrPredictions = lrPipelineModel.transform(testdata)
val evaluator = new MulticlassClassificationEvaluator().setLabelCol("indexedLabel").setPredictionCol("prediction")

val lrAccuracy = evaluator.evaluate(lrPredictions)

println("Test Error = " + (1.0 - lrAccuracy))

预测的错误率如下图所示:

  • (4)超参数调优
scala 复制代码
val pca = new PCA().setInputCol("features").setOutputCol("pcaFeatures")
val labelIndexer = new StringIndexer().setInputCol("label").setOutputCol("indexedLabel").fit(df)
val featureIndexer = new VectorIndexer().setInputCol("pcaFeatures").setOutputCol("indexedFeatures")
val labelConverter = new IndexToString().setInputCol("prediction").setOutputCol("predictedLabel").setLabels(labelIndexer.labels)
val lr = new LogisticRegression().setLabelCol("indexedLabel").setFeaturesCol("indexedFeatures").setMaxIter(100)
val lrPipeline = new Pipeline().setStages(Array(pca, labelIndexer, featureIndexer, lr, labelConverter))
val paramGrid = new ParamGridBuilder().addGrid(pca.k, Array(1,2,3,4,5,6)).addGrid(lr.elasticNetParam, Array(0.2,0.8)).addGrid(lr.regParam, Array(0.01, 0.1, 0.5)).build()

paramGrid的结果值如下所示:

scala 复制代码
paramGrid: Array[org.apache.spark.ml.param.ParamMap] =
Array({
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 1,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 2,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 3,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 4,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 5,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.2,
	pca_e02a5078c882-k: 6,
	logreg_9e1b758452ee-regParam: 0.01
}, {
	logreg_9e1b758452ee-elasticNetParam: 0.8,
	pca_e02a5078c882...
scala 复制代码
val cv = new CrossValidator().setEstimator(lrPipeline).setEvaluator(new MulticlassClassificationEvaluator().setLabelCol("indexedLabel").setPredictionCol("prediction")).setEstimatorParamMaps(paramGrid).setNumFolds(3)
val cvModel = cv.fit(df)
val lrPredictions=cvModel.transform(test)
val evaluator = new MulticlassClassificationEvaluator().setLabelCol("indexedLabel").setPredictionCol("prediction")
val lrAccuracy = evaluator.evaluate(lrPredictions)
println("准确率为"+lrAccuracy)
val bestModel= cvModel.bestModel.asInstanceOf[PipelineModel]
val lrModel = bestModel.stages(3).asInstanceOf[LogisticRegressionModel]
println("Coefficients: " + lrModel.coefficientMatrix + "Intercept: "+lrModel.interceptVector+ "numClasses: "+lrModel.numClasses+"numFeatures: "+lrModel.numFeatures)
scala 复制代码
import org.apache.spark.ml.feature.PCAModel
val pcaModel = bestModel.stages(0).asInstanceOf[PCAModel]
println("Primary Component: " + pcaModel.pc)

请先提前导入org.apache.spark.ml.feature.PCAModel这个包

全文结束!!!

相关推荐
BFT白芙堂2 小时前
睿尔曼系列机器人——以创新驱动未来,重塑智能协作新生态(上)
人工智能·机器学习·机器人·协作机器人·复合机器人·睿尔曼机器人
羊小猪~~2 小时前
【NLP入门系列五】中文文本分类案例
人工智能·深度学习·考研·机器学习·自然语言处理·分类·数据挖掘
李师兄说大模型2 小时前
KDD 2025 | 地理定位中的群体智能:一个多智能体大型视觉语言模型协同框架
人工智能·深度学习·机器学习·语言模型·自然语言处理·大模型·deepseek
网安INF3 小时前
深层神经网络:原理与传播机制详解
人工智能·深度学习·神经网络·机器学习
zskj_zhyl4 小时前
智慧养老丨从依赖式养老到自主式养老:如何重构晚年生活新范式
大数据·人工智能·物联网
哲科软件5 小时前
从“电话催维修“到“手机看进度“——售后服务系统开发如何重构客户体验
大数据·智能手机·重构
zzywxc7875 小时前
AI 正在深度重构软件开发的底层逻辑和全生命周期,从技术演进、流程重构和未来趋势三个维度进行系统性分析
java·大数据·开发语言·人工智能·spring
超龄超能程序猿5 小时前
(1)机器学习小白入门 YOLOv:从概念到实践
人工智能·机器学习
专注API从业者5 小时前
构建淘宝评论监控系统:API 接口开发与实时数据采集教程
大数据·前端·数据库·oracle