当前位置: 移动技术网 > IT编程>数据库>其他数据库 > spark 机器学习 随机森林 实现(二)

spark 机器学习 随机森林 实现(二)

2019年06月20日  | 移动技术网IT编程  | 我要评论

通过天气,温度,风速3个特征,建立随机森林,判断特征的优先级
结果 天气 温度 风速
结果(0否,1是)
天气(0晴天,1阴天,2下雨)
温度(0热,1舒适,2冷)
风速(0没风,1微风,2大风)
1 1:0 2:1 3:0
结果去打球 1字段:晴天 2字段:温度舒适 3字段:风速没风
[hadoop@h201 pp]$ cat pp1.txt
1 1:0 2:1 3:0
0 1:2 2:2 3:2
1 1:0 2:0 3:0
1 1:0 2:0 3:1
1 1:0 2:1 3:1
1 1:0 2:1 3:1
1 1:0 2:1 3:0
0 1:1 2:2 3:2
0 1:1 2:2 3:2
0 1:2 2:2 3:2
0 1:2 2:1 3:1
0 1:2 2:1 3:2
0 1:1 2:2 3:2
1 1:0 2:1 3:0
本例子 用官方提供代码进行更改完成
hadoop fs -put pp1.txt /

scala> import org.apache.spark.mllib.tree.randomforest
scala> import org.apache.spark.mllib.tree.model.randomforestmodel
scala> import org.apache.spark.mllib.util.mlutils

val data = mlutils.loadlibsvmfile(sc, "hdfs://h201:9000/pp1.txt")
//标记点是将密集向量或者稀疏向量与应答标签相关联(结果),在mllib中,标记点用于监督学习算法。libsvm是林智仁教授等开发设计的一个简单、易用和快速有效的svm模式识别与回归的软件包。mllib已经提供了mlutils.loadlibsvmfile方法读取存储在libsvm格式文本文件中的训练数据

//数据格式 :空格分割,第一部分为结果,后面为特征向量

scala> val splits = data.randomsplit(array(0.7, 0.3))
scala> val (trainingdata, testdata) = (splits(0), splits(1))

scala> val numclasses = 2
//分类数
scala> val categoricalfeaturesinfo = map[int, int]()
// categoricalfeaturesinfo 为空,意味着所有的特征为连续型变量
scala> val numtrees = 3
//树的个数
scala> val featuresubsetstrategy = "auto"
//特征子集采样策略,auto 表示算法自主选取
scala> val impurity = "gini"

//以性别举例:性别 :1-(1/2)^2-(1/2)^2 =0.5
scala> val maxdepth = 4
//树的最大层次
scala> val maxbins = 32
//特征最大装箱数

val model = randomforest.trainclassifier(trainingdata, numclasses, categoricalfeaturesinfo,
 numtrees, featuresubsetstrategy, impurity, maxdepth, maxbins)
//训练随机森林分类器

val labelandpreds = testdata.map { point =>
 val prediction = model.predict(point.features)
 (point.label, prediction)
}
scala> val testerr = labelandpreds.filter(r => r._1 != r._2).count.todouble / testdata.count()
scala> println("test error = " + testerr)
// 测试数据评价训练好的分类器并计算错误率

scala> println("learned classification forest model:\n" + model.todebugstring)

scala> model.save(sc, "mymodelpath")
//持久化保存随机森林

scala> val samemodel = randomforestmodel.load(sc, "mymodelpath")
//加载随机森林

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网