Spark MLlib例項 決策樹

2021-07-15 15:37:41 字數 3092 閱讀 4134

spark-mllib例項——決策樹

通俗來說,決策樹分類的思想類似於找物件。現想象乙個女孩的母親要給這個女孩介紹男朋友,於是有了下面的對話:

女兒:多大年紀了?

母親:26。

女兒:長的帥不帥?

母親:挺帥的。

女兒:收入高不?

母親:不算很高,中等情況。

女兒:是公務員不?

母親:是,在稅務局上班呢。

女兒:那好,我去見見。

以上是決策的經典例子,用spark-mllib怎麼實現訓練與**呢

1、首先準備測試資料集

訓練資料集 tree1

字段說明:

是否見面, 年齡  是否帥  收入(1 高 2 中等 0 少)  是否公務員

0,32 1 1 0

0,25 1 2 0

1,29 1 2 1

1,24 1 1 0

0,31 1 1 0

1,35 1 2 1

0,30 0 1 0

0,31 1 1 0

1,30 1 2 1

1,21 1 1 0

0,21 1 2 0

1,21 1 2 1

0,29 0 2 1

0,29 1 0 1

0,29 0 2 1

1,30 1 1 0

測試資料集 tree2

0,32 1 2 0

1,27 1 1 1

1,29 1 1 0

1,25 1 2 1

0,23 0 2 1

2、spark-mllib決策樹應用**

import org.apache.log4j.

import org.apache.spark.mllib.feature.hashingtf

import org.apache.spark.mllib.linalg.vectors

import org.apache.spark.mllib.regression.labeledpoint

import org.apache.spark.mllib.tree.decisiontree

import org.apache.spark.mllib.util.mlutils

import org.apache.spark.

/** * 決策樹分類

*/object treedemo

val tree2 = data2.map

//賦值

val (trainingdata, testdata) = (tree1, tree2)

//分類

val numclasses = 2

val categoricalfeaturesinfo = map[int, int]()

val impurity = "gini"

//最大深度

val maxdepth = 5

//最大分支

val maxbins = 32

//模型訓練

val model = decisiontree.trainclassifier(trainingdata, numclasses, categoricalfeaturesinfo,

impurity, maxdepth, maxbins)

//模型**

val labelandpreds = testdata.map

//測試值與真實值對比

val print_predict = labelandpreds.take(15)

println("label" + "\t" + "prediction")

for (i

//樹的錯誤率

val testerr = labelandpreds.filter(r => r._1 != r._2).count.todouble / testdata.count()

println("test error = " + testerr)

//列印樹的判斷值

println("learned classification tree model:\n" + model.todebugstring)

}}

3、測試結果:

label	prediction

0.0 0.0

1.0 1.0

1.0 1.0

1.0 1.0

0.0 0.0

test error = 0.0

learned classification tree model:

可見真實值與**值一致,error為0

列印決策樹的分支值,這裡最大深度為 5 ,對應的樹結構:

learned classification tree model:

decisiontreemodel classifier of depth 4 with 11 nodes

if (feature 1 <= 0.0)

predict: 0.0

else (feature 1 > 0.0)

if (feature 3 <= 0.0)

if (feature 0 <= 30.0)

if (feature 2 <= 1.0)

predict: 1.0

else (feature 2 > 1.0)

predict: 0.0

else (feature 0 > 30.0)

predict: 0.0

else (feature 3 > 0.0)

if (feature 2 <= 0.0)

predict: 0.0

else (feature 2 > 0.0)

predict: 1.0

可見**出的分界值與真實一致,準確率與決策樹演算法,引數設定及訓練樣本的選擇覆蓋有關!

spark mllib 決策樹演算法

該樣例取自spark高階資料分析第四章的內容,資料集來自 r2wmisi,包含乙個 csv 格式的壓縮資料檔案 covtype.data.gz,附帶乙個描述資料檔案的 資訊檔案 covtype.info spark mllib將特徵向量抽象為labeledpoint,它由乙個包含多個特徵值的spar...

決策樹例項及原理

鐵達尼號 生死 import pandas as pd from sklearn.tree import decisiontreeclassifier 決策樹分類器。from sklearn.feature extraction import dictvectorizer 將特徵值對映列表轉換為向量...

決策樹和CART決策樹

首先簡單介紹下決策樹 說到決策樹肯定離不開資訊熵 什麼是資訊熵 不要被這名字唬住,其實很簡單 乙個不太可能的時間居然發生了,要比乙個非常可能的時間發生提供更多的資訊。訊息說 今天早上太陽公升起 資訊量是很少的,以至於沒有必要傳送。但另一條訊息說 今天早上日食 資訊量就很豐富。概率越大資訊量就越少,與...