Machine Learning with PySpark
Andrew Collier
Data Scientist, Fathom Data
คือกลุ่มของโมเดลหลายตัว
Wisdom of the Crowd — ความเห็นร่วมของกลุ่มมักแม่นยำกว่าผู้เชี่ยวชาญคนเดียว
ความหลากหลาย และ ความเป็นอิสระ มีความสำคัญ เพราะการตัดสินใจร่วมที่ดีที่สุดเกิดจากความขัดแย้งและการแข่งขัน ไม่ใช่ฉันทามติหรือการประนีประนอม
― James Surowiecki, The Wisdom of Crowds
Random Forest — Ensemble ของ Decision Tree
การสร้างความหลากหลายให้โมเดล:
แต่ละต้นไม้ในป่าควรแตกต่างกัน

กลับมาที่ข้อมูลรถยนต์: ผลิตในสหรัฐฯ (0.0) หรือไม่ (1.0)
สร้าง Random Forest classifier
from pyspark.ml.classification import RandomForestClassifier
forest = RandomForestClassifier(numTrees=5)
ฝึกกับข้อมูล training
forest = forest.fit(cars_train)
เข้าถึงต้นไม้แต่ละต้นใน forest ได้อย่างไร?
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| <- perfect agreement
| 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| <- perfect agreement
+------+------+------+------+------+-----+
ใช้เมธอด .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 สำคัญน้อยที่สุดอัลกอริทึม boosting แบบวนซ้ำ:
โมเดลดีขึ้นในแต่ละรอบ
สร้าง Gradient-Boosted Tree classifier
from pyspark.ml.classification import GBTClassifier
gbt = GBTClassifier(maxIter=10)
ฝึกกับข้อมูล training
gbt = gbt.fit(cars_train)
เปรียบเทียบโมเดล tree ทั้ง 3 ประเภทบนข้อมูล testing
# AUC for Decision Tree
0.5875
# AUC for Random Forest
0.65
# AUC for Gradient-Boosted Tree
0.65
ทั้ง ensemble method ให้ผลดีกว่า Decision Tree แบบเดี่ยว
Machine Learning with PySpark