使用 PySpark 的機器學習
Andrew Collier
Data Scientist, Fathom Data
它是一組模型的集合。
群眾智慧——群體的整體判斷往往優於單一專家。
多樣性與獨立性很重要,因為最好的集體決策來自分歧與競爭,而非共識或妥協。
― James Surowiecki,《The Wisdom of Crowds》
Random Forest——由多棵 Decision Tree 組成的集成
打造模型多樣性:
森林中的樹不該有兩棵一樣。

回到汽車資料:產地在 USA(0.0)或非 USA(1.0)。
建立 Random Forest 分類器。
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 最不重要。迭代式提升演算法:
模型在每次迭代都會改進。
建立一個 Gradient-Boosted Tree 分類器。
from pyspark.ml.classification import GBTClassifier
gbt = GBTClassifier(maxIter=10)
將模型擬合到訓練資料。
gbt = gbt.fit(cars_train)
我們來比較 3 種樹模型在測試資料上的表現。
# AUC for Decision Tree
0.5875
# AUC for Random Forest
0.65
# AUC for Gradient-Boosted Tree
0.65
兩種集成方法都優於單一的 Decision Tree。
使用 PySpark 的機器學習