使用 PySpark 进行机器学习
Andrew Collier
Data Scientist, Fathom Data
这是模型的集合。
"群体智慧"——群体的集体判断往往优于单个专家。
多样性与独立性很重要,因为最优的集体决策源自分歧与竞争,而非一致与妥协。
—— James Surowiecki,《群体的智慧》
随机森林——决策树的集成
创建模型多样性:
森林中的树应当彼此不同。

回到汽车数据:产自美国(0.0)或非美国(1.0)。
创建随机森林分类器。
from pyspark.ml.classification import RandomForestClassifier
forest = RandomForestClassifier(numTrees=5)
拟合训练数据。
forest = forest.fit(cars_train)
如何访问森林中的树?
forest.trees
[DecisionTreeClassificationModel (uid=dtc_aa66702a4ce9) of depth 5 with 17 nodes,
DecisionTreeClassificationModel (uid=dtc_99f7efedafe9) of depth 5 with 31 nodes,
DecisionTreeClassificationModel (uid=dtc_9306e4a5fa1d) of depth 5 with 21 nodes,
DecisionTreeClassificationModel (uid=dtc_d643bd48a8dd) of depth 5 with 23 nodes,
DecisionTreeClassificationModel (uid=dtc_a2d5abd67969) of depth 5 with 27 nodes]
这些都可用于单独预测。
每棵树生成了哪些预测?
+------+------+------+------+------+-----+
|tree 0|tree 1|tree 2|tree 3|tree 4|label|
+------+------+------+------+------+-----+
| 0.0| 0.0| 0.0| 0.0| 0.0| 0.0| <- 完全一致
| 1.0| 1.0| 0.0| 1.0| 0.0| 0.0|
| 0.0| 0.0| 0.0| 1.0| 1.0| 1.0|
| 0.0| 0.0| 0.0| 1.0| 0.0| 0.0|
| 0.0| 1.0| 1.0| 1.0| 0.0| 1.0|
| 1.0| 1.0| 0.0| 1.0| 1.0| 1.0|
| 1.0| 1.0| 1.0| 1.0| 1.0| 1.0| <- 完全一致
+------+------+------+------+------+-----+
使用 .transform() 生成共识预测。
+-----+----------------------------------------+----------+
|label|probability |prediction|
+-----+----------------------------------------+----------+
|0.0 |[0.8,0.2] |0.0 |
|0.0 |[0.4,0.6] |1.0 |
|1.0 |[0.5333333333333333,0.4666666666666666] |0.0 |
|0.0 |[0.7177777777777778,0.28222222222222226]|0.0 |
|1.0 |[0.39396825396825397,0.606031746031746] |1.0 |
|1.0 |[0.17660818713450294,0.823391812865497] |1.0 |
|1.0 |[0.053968253968253964,0.946031746031746]|1.0 |
+-----+----------------------------------------+----------+
模型使用这些特征:cyl、size、mass、length、rpm、consumption。
哪些最重要或最不重要?
forest.featureImportances
SparseVector(6, {0: 0.0205, 1: 0.2701, 2: 0.108, 3: 0.1895, 4: 0.2939, 5: 0.1181})
看起来:
rpm 最重要cyl 最不重要。迭代式提升算法:
模型在每次迭代中改进。
创建梯度提升树分类器。
from pyspark.ml.classification import GBTClassifier
gbt = GBTClassifier(maxIter=10)
拟合训练数据。
gbt = gbt.fit(cars_train)
在测试数据上比较三类树模型。
# 决策树的 AUC
0.5875
# 随机森林的 AUC
0.65
# 梯度提升树的 AUC
0.65
两种集成方法都优于单一决策树。
使用 PySpark 进行机器学习