Spark2 ML包之决策树分类Decision tree classifier详细解说

所用数据源,请参考本人博客http://www.cnblogs.com/wwxbi/p/6063613.html

1.导入包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import  org.apache.spark.sql.SparkSession
import  org.apache.spark.sql.Dataset
import  org.apache.spark.sql.Row
import  org.apache.spark.sql.DataFrame
import  org.apache.spark.sql.Column
import  org.apache.spark.sql.DataFrameReader
import  org.apache.spark.rdd.RDD
import  org.apache.spark.sql.catalyst.encoders.ExpressionEncoder
import  org.apache.spark.sql.Encoder
import  org.apache.spark.sql.DataFrameStatFunctions
import  org.apache.spark.sql.functions. _
 
import  org.apache.spark.ml.Pipeline
import  org.apache.spark.ml.classification.DecisionTreeClassificationModel
import  org.apache.spark.ml.classification.DecisionTreeClassifier
import  org.apache.spark.ml.evaluation.MulticlassClassificationEvaluator
import  org.apache.spark.ml.feature.VectorAssembler
import  org.apache.spark.ml.feature.StringIndexer
import  org.apache.spark.ml.feature.IndexToString
import  org.apache.spark.ml.feature.VectorIndexer
import  org.apache.spark.ml.feature.VectorSlicer

 

2.加载数据源

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
val  spark  =  SparkSession.builder().appName( "Spark decision tree classifier" ).config( "spark.some.config.option" "some-value" ).getOrCreate()
 
// For implicit conversions like converting RDDs to DataFrames
import  spark.implicits. _
 
// 这里仅仅是示例数据,数据源,请参考本人博客http://www.cnblogs.com/wwxbi/p/6063613.html
val  dataList :  List[(Double, String, Double, Double, String, Double, Double, Double, Double)]  =  List(
   ( 0 "male" 37 10 "no" 3 18 7 4 ),
   ( 0 "female" 27 4 "no" 4 14 6 4 ),
   ( 0 "female" 32 15 "yes" 1 12 1 4 ),
   ( 0 "male" 57 15 "yes" 5 18 6 5 ),
   ( 0 "male" 22 0.75 "no" 2 17 6 3 ),
   ( 0 "female" 32 1.5 "no" 2 17 5 5 ))
 
val  data  =  dataList.toDF( "affairs" "gender" "age" "yearsmarried" "children" "religiousness" "education" "occupation" "rating" )
 
data.createOrReplaceTempView( "data" )
 
// 字符类型转换成数值
val  labelWhere  =  "case when affairs=0 then 0 else cast(1 as double) end as label"
val  genderWhere  =  "case when gender='female' then 0 else cast(1 as double) end as gender"
val  childrenWhere  =  "case when children='no' then 0 else cast(1 as double) end as children"
 
val  dataLabelDF  =  spark.sql(s "select $labelWhere, $genderWhere,age,yearsmarried,$childrenWhere,religiousness,education,occupation,rating from data" )

 

 3.创建决策树模型

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
val  featuresArray  =  Array( "gender" "age" "yearsmarried" "children" "religiousness" "education" "occupation" "rating" )
 
// 字段转换成特征向量
val  assembler  =  new  VectorAssembler().setInputCols(featuresArray).setOutputCol( "features" )
val  vecDF :  DataFrame  =  assembler.transform(dataLabelDF)
vecDF.show( 10 , truncate  =  false )
 
// 索引标签,将元数据添加到标签列中
val  labelIndexer  =  new  StringIndexer().setInputCol( "label" ).setOutputCol( "indexedLabel" ).fit(vecDF)
labelIndexer.transform(vecDF).show( 10 , truncate  =  false )
 
// 自动识别分类的特征,并对它们进行索引
// 具有大于5个不同的值的特征被视为连续。
val  featureIndexer  =  new  VectorIndexer().setInputCol( "features" ).setOutputCol( "indexedFeatures" ).setMaxCategories( 5 ).fit(vecDF)
featureIndexer.transform(vecDF).show( 10 , truncate  =  false )
 
// 将数据分为训练和测试集(30%进行测试)
val  Array(trainingData, testData)  =  vecDF.randomSplit(Array( 0.7 0.3 ))
 
// 训练决策树模型
val  dt  =  new  DecisionTreeClassifier()
.setLabelCol( "indexedLabel" )
.setFeaturesCol( "indexedFeatures" )
.setImpurity( "entropy" // 不纯度
.setMaxBins( 100 // 离散化"连续特征"的最大划分数
.setMaxDepth( 5 // 树的最大深度
.setMinInfoGain( 0.01 //一个节点分裂的最小信息增益,值为[0,1]
.setMinInstancesPerNode( 10 //每个节点包含的最小样本数
.setSeed( 123456 )
 
// 将索引标签转换回原始标签
val  labelConverter  =  new  IndexToString().setInputCol( "prediction" ).setOutputCol( "predictedLabel" ).setLabels(labelIndexer.labels)
 
// Chain indexers and tree in a Pipeline.
val  pipeline  =  new  Pipeline().setStages(Array(labelIndexer, featureIndexer, dt, labelConverter))
 
// Train model. This also runs the indexers.
val  model  =  pipeline.fit(trainingData)
 
// 作出预测
val  predictions  =  model.transform(testData)
 
// 选择几个示例行展示
predictions.select( "predictedLabel" "label" "features" ).show( 10 , truncate  =  false )
 
// 选择(预测标签,实际标签),并计算测试误差。
val  evaluator  =  new  MulticlassClassificationEvaluator().setLabelCol( "indexedLabel" ).setPredictionCol( "prediction" ).setMetricName( "accuracy" )
val  accuracy  =  evaluator.evaluate(predictions)
println( "Test Error = "  + ( 1.0  - accuracy))
 
// 这里的stages(2)中的“2”对应pipeline中的“dt”,将model强制转换为DecisionTreeClassificationModel类型
val  treeModel  =  model.stages( 2 ).asInstanceOf[DecisionTreeClassificationModel]
treeModel.getLabelCol
treeModel.getFeaturesCol
treeModel.featureImportances
treeModel.getPredictionCol
treeModel.getProbabilityCol
 
treeModel.numClasses
treeModel.numFeatures
treeModel.depth
treeModel.numNodes
 
treeModel.getImpurity
treeModel.getMaxBins
treeModel.getMaxDepth
treeModel.getMaxMemoryInMB
treeModel.getMinInfoGain
treeModel.getMinInstancesPerNode
 
println( "Learned classification tree model:\n"  + treeModel.toDebugString)

 

4.代码执行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
val  data  =  dataList.toDF( "affairs" "gender" "age" "yearsmarried" "children" "religiousness" "education" "occupation" "rating" )
 
data.show( 10 , truncate  =  false )
+-------+------+----+------------+--------+-------------+---------+----------+------+
|affairs|gender|age |yearsmarried|children|religiousness|education|occupation|rating|
+-------+------+----+------------+--------+-------------+---------+----------+------+
| 0.0     |male  | 37.0 | 10.0         |no      | 3.0           | 18.0      | 7.0        | 4.0    |
| 0.0     |female| 27.0 | 4.0          |no      | 4.0           | 14.0      | 6.0        | 4.0    |
| 0.0     |female| 32.0 | 15.0         |yes     | 1.0           | 12.0      | 1.0        | 4.0    |
| 0.0     |male  | 57.0 | 15.0         |yes     | 5.0           | 18.0      | 6.0        | 5.0    |
| 0.0     |male  | 22.0 | 0.75         |no      | 2.0           | 17.0      | 6.0        | 3.0    |
| 0.0     |female| 32.0 | 1.5          |no      | 2.0           | 17.0      | 5.0        | 5.0    |
| 0.0     |female| 22.0 | 0.75         |no      | 2.0           | 12.0      | 1.0        | 3.0    |
| 0.0     |male  | 57.0 | 15.0         |yes     | 2.0           | 14.0      | 4.0        | 4.0    |
| 0.0     |female| 32.0 | 15.0         |yes     | 4.0           | 16.0      | 1.0        | 2.0    |
| 0.0     |male  | 22.0 | 1.5          |no      | 4.0           | 14.0      | 4.0        | 5.0    |
+-------+------+----+------------+--------+-------------+---------+----------+------+
only showing top  10  rows
 
 
data.createOrReplaceTempView( "data" )
 
// 字符类型转换成数值
val  labelWhere  =  "case when affairs=0 then 0 else cast(1 as double) end as label"
val  genderWhere  =  "case when gender='female' then 0 else cast(1 as double) end as gender"
val  childrenWhere  =  "case when children='no' then 0 else cast(1 as double) end as children"
 
val  dataLabelDF  =  spark.sql(s "select $labelWhere, $genderWhere,age,yearsmarried,$childrenWhere,religiousness,education,occupation,rating from data" )
 
dataLabelDF.show( 10 , truncate  =  false )
+-----+------+----+------------+--------+-------------+---------+----------+------+
|label|gender|age |yearsmarried|children|religiousness|education|occupation|rating|
+-----+------+----+------------+--------+-------------+---------+----------+------+
| 0.0   | 1.0    | 37.0 | 10.0         | 0.0      | 3.0           | 18.0      | 7.0        | 4.0    |
| 0.0   | 0.0    | 27.0 | 4.0          | 0.0      | 4.0           | 14.0      | 6.0        | 4.0    |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 1.0           | 12.0      | 1.0        | 4.0    |
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 5.0           | 18.0      | 6.0        | 5.0    |
| 0.0   | 1.0    | 22.0 | 0.75         | 0.0      | 2.0           | 17.0      | 6.0        | 3.0    |
| 0.0   | 0.0    | 32.0 | 1.5          | 0.0      | 2.0           | 17.0      | 5.0        | 5.0    |
| 0.0   | 0.0    | 22.0 | 0.75         | 0.0      | 2.0           | 12.0      | 1.0        | 3.0    |
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 2.0           | 14.0      | 4.0        | 4.0    |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 4.0           | 16.0      | 1.0        | 2.0    |
| 0.0   | 1.0    | 22.0 | 1.5          | 0.0      | 4.0           | 14.0      | 4.0        | 5.0    |
+-----+------+----+------------+--------+-------------+---------+----------+------+
only showing top  10  rows
 
 
val  featuresArray  =  Array( "gender" "age" "yearsmarried" "children" "religiousness" "education" "occupation" "rating" )
 
// 字段转换成特征向量
val  assembler  =  new  VectorAssembler().setInputCols(featuresArray).setOutputCol( "features" )
val  vecDF :  DataFrame  =  assembler.transform(dataLabelDF)
vecDF.show( 10 , truncate  =  false )
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+
|label|gender|age |yearsmarried|children|religiousness|education|occupation|rating|features                            |
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+
| 0.0   | 1.0    | 37.0 | 10.0         | 0.0      | 3.0           | 18.0      | 7.0        | 4.0    |[ 1.0 , 37.0 , 10.0 , 0.0 , 3.0 , 18.0 , 7.0 , 4.0 ]|
| 0.0   | 0.0    | 27.0 | 4.0          | 0.0      | 4.0           | 14.0      | 6.0        | 4.0    |[ 0.0 , 27.0 , 4.0 , 0.0 , 4.0 , 14.0 , 6.0 , 4.0 ] |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 1.0           | 12.0      | 1.0        | 4.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 1.0 , 12.0 , 1.0 , 4.0 ]|
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 5.0           | 18.0      | 6.0        | 5.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 5.0 , 18.0 , 6.0 , 5.0 ]|
| 0.0   | 1.0    | 22.0 | 0.75         | 0.0      | 2.0           | 17.0      | 6.0        | 3.0    |[ 1.0 , 22.0 , 0.75 , 0.0 , 2.0 , 17.0 , 6.0 , 3.0 ]|
| 0.0   | 0.0    | 32.0 | 1.5          | 0.0      | 2.0           | 17.0      | 5.0        | 5.0    |[ 0.0 , 32.0 , 1.5 , 0.0 , 2.0 , 17.0 , 5.0 , 5.0 ] |
| 0.0   | 0.0    | 22.0 | 0.75         | 0.0      | 2.0           | 12.0      | 1.0        | 3.0    |[ 0.0 , 22.0 , 0.75 , 0.0 , 2.0 , 12.0 , 1.0 , 3.0 ]|
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 2.0           | 14.0      | 4.0        | 4.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 2.0 , 14.0 , 4.0 , 4.0 ]|
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 4.0           | 16.0      | 1.0        | 2.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 4.0 , 16.0 , 1.0 , 2.0 ]|
| 0.0   | 1.0    | 22.0 | 1.5          | 0.0      | 4.0           | 14.0      | 4.0        | 5.0    |[ 1.0 , 22.0 , 1.5 , 0.0 , 4.0 , 14.0 , 4.0 , 5.0 ] |
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+
only showing top  10  rows
 
 
// 索引标签,将元数据添加到标签列中
val  labelIndexer  =  new  StringIndexer().setInputCol( "label" ).setOutputCol( "indexedLabel" ).fit(vecDF)
labelIndexer.transform(vecDF).show( 10 , truncate  =  false )
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------+
|label|gender|age |yearsmarried|children|religiousness|education|occupation|rating|features                            |indexedLabel|
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------+
| 0.0   | 1.0    | 37.0 | 10.0         | 0.0      | 3.0           | 18.0      | 7.0        | 4.0    |[ 1.0 , 37.0 , 10.0 , 0.0 , 3.0 , 18.0 , 7.0 , 4.0 ]| 0.0          |
| 0.0   | 0.0    | 27.0 | 4.0          | 0.0      | 4.0           | 14.0      | 6.0        | 4.0    |[ 0.0 , 27.0 , 4.0 , 0.0 , 4.0 , 14.0 , 6.0 , 4.0 ] | 0.0          |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 1.0           | 12.0      | 1.0        | 4.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 1.0 , 12.0 , 1.0 , 4.0 ]| 0.0          |
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 5.0           | 18.0      | 6.0        | 5.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 5.0 , 18.0 , 6.0 , 5.0 ]| 0.0          |
| 0.0   | 1.0    | 22.0 | 0.75         | 0.0      | 2.0           | 17.0      | 6.0        | 3.0    |[ 1.0 , 22.0 , 0.75 , 0.0 , 2.0 , 17.0 , 6.0 , 3.0 ]| 0.0          |
| 0.0   | 0.0    | 32.0 | 1.5          | 0.0      | 2.0           | 17.0      | 5.0        | 5.0    |[ 0.0 , 32.0 , 1.5 , 0.0 , 2.0 , 17.0 , 5.0 , 5.0 ] | 0.0          |
| 0.0   | 0.0    | 22.0 | 0.75         | 0.0      | 2.0           | 12.0      | 1.0        | 3.0    |[ 0.0 , 22.0 , 0.75 , 0.0 , 2.0 , 12.0 , 1.0 , 3.0 ]| 0.0          |
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 2.0           | 14.0      | 4.0        | 4.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 2.0 , 14.0 , 4.0 , 4.0 ]| 0.0          |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 4.0           | 16.0      | 1.0        | 2.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 4.0 , 16.0 , 1.0 , 2.0 ]| 0.0          |
| 0.0   | 1.0    | 22.0 | 1.5          | 0.0      | 4.0           | 14.0      | 4.0        | 5.0    |[ 1.0 , 22.0 , 1.5 , 0.0 , 4.0 , 14.0 , 4.0 , 5.0 ] | 0.0          |
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------+
only showing top  10  rows
 
 
// 自动识别分类的特征,并对它们进行索引
// 具有大于5个不同的值的特征被视为连续。
val  featureIndexer  =  new  VectorIndexer().setInputCol( "features" ).setOutputCol( "indexedFeatures" ).setMaxCategories( 5 ).fit(vecDF)
featureIndexer.transform(vecDF).show( 10 , truncate  =  false )
featureIndexer.transform(vecDF).show( 10 , truncate  =  false )
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------------------------------+
|label|gender|age |yearsmarried|children|religiousness|education|occupation|rating|features                            |indexedFeatures                     |
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------------------------------+
| 0.0   | 1.0    | 37.0 | 10.0         | 0.0      | 3.0           | 18.0      | 7.0        | 4.0    |[ 1.0 , 37.0 , 10.0 , 0.0 , 3.0 , 18.0 , 7.0 , 4.0 ]|[ 1.0 , 37.0 , 10.0 , 0.0 , 2.0 , 18.0 , 7.0 , 3.0 ]|
| 0.0   | 0.0    | 27.0 | 4.0          | 0.0      | 4.0           | 14.0      | 6.0        | 4.0    |[ 0.0 , 27.0 , 4.0 , 0.0 , 4.0 , 14.0 , 6.0 , 4.0 ] |[ 0.0 , 27.0 , 4.0 , 0.0 , 3.0 , 14.0 , 6.0 , 3.0 ] |
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 1.0           | 12.0      | 1.0        | 4.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 1.0 , 12.0 , 1.0 , 4.0 ]|[ 0.0 , 32.0 , 15.0 , 1.0 , 0.0 , 12.0 , 1.0 , 3.0 ]|
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 5.0           | 18.0      | 6.0        | 5.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 5.0 , 18.0 , 6.0 , 5.0 ]|[ 1.0 , 57.0 , 15.0 , 1.0 , 4.0 , 18.0 , 6.0 , 4.0 ]|
| 0.0   | 1.0    | 22.0 | 0.75         | 0.0      | 2.0           | 17.0      | 6.0        | 3.0    |[ 1.0 , 22.0 , 0.75 , 0.0 , 2.0 , 17.0 , 6.0 , 3.0 ]|[ 1.0 , 22.0 , 0.75 , 0.0 , 1.0 , 17.0 , 6.0 , 2.0 ]|
| 0.0   | 0.0    | 32.0 | 1.5          | 0.0      | 2.0           | 17.0      | 5.0        | 5.0    |[ 0.0 , 32.0 , 1.5 , 0.0 , 2.0 , 17.0 , 5.0 , 5.0 ] |[ 0.0 , 32.0 , 1.5 , 0.0 , 1.0 , 17.0 , 5.0 , 4.0 ] |
| 0.0   | 0.0    | 22.0 | 0.75         | 0.0      | 2.0           | 12.0      | 1.0        | 3.0    |[ 0.0 , 22.0 , 0.75 , 0.0 , 2.0 , 12.0 , 1.0 , 3.0 ]|[ 0.0 , 22.0 , 0.75 , 0.0 , 1.0 , 12.0 , 1.0 , 2.0 ]|
| 0.0   | 1.0    | 57.0 | 15.0         | 1.0      | 2.0           | 14.0      | 4.0        | 4.0    |[ 1.0 , 57.0 , 15.0 , 1.0 , 2.0 , 14.0 , 4.0 , 4.0 ]|[ 1.0 , 57.0 , 15.0 , 1.0 , 1.0 , 14.0 , 4.0 , 3.0 ]|
| 0.0   | 0.0    | 32.0 | 15.0         | 1.0      | 4.0           | 16.0      | 1.0        | 2.0    |[ 0.0 , 32.0 , 15.0 , 1.0 , 4.0 , 16.0 , 1.0 , 2.0 ]|[ 0.0 , 32.0 , 15.0 , 1.0 , 3.0 , 16.0 , 1.0 , 1.0 ]|
| 0.0   | 1.0    | 22.0 | 1.5          | 0.0      | 4.0           | 14.0      | 4.0        | 5.0    |[ 1.0 , 22.0 , 1.5 , 0.0 , 4.0 , 14.0 , 4.0 , 5.0 ] |[ 1.0 , 22.0 , 1.5 , 0.0 , 3.0 , 14.0 , 4.0 , 4.0 ] |
+-----+------+----+------------+--------+-------------+---------+----------+------+------------------------------------+------------------------------------+
only showing top  10  rows
 
 
// 将数据分为训练和测试集(30%进行测试)
val  Array(trainingData, testData)  =  vecDF.randomSplit(Array( 0.7 0.3 ))
 
// 训练决策树模型
val  dt  =  new  DecisionTreeClassifier().setLabelCol( "indexedLabel" ).setFeaturesCol( "indexedFeatures" ).setImpurity( "entropy" ).setMaxBins( 100 ).setMaxDepth( 5 ).setMinInfoGain( 0.01 ).setMinInstancesPerNode( 10 ).setSeed( 123456 )
//.setLabelCol("indexedLabel")
//.setFeaturesCol("indexedFeatures")
//.setImpurity("entropy") // 不纯度
//.setMaxBins(100) // 离散化"连续特征"的最大划分数
//.setMaxDepth(5) // 树的最大深度
//.setMinInfoGain(0.01) //一个节点分裂的最小信息增益,值为[0,1]
//.setMinInstancesPerNode(10) //每个节点包含的最小样本数
//.setSeed(123456)
 
// 将索引标签转换回原始标签
val  labelConverter  =  new  IndexToString().setInputCol( "prediction" ).setOutputCol( "predictedLabel" ).setLabels(labelIndexer.labels)
 
// Chain indexers and tree in a Pipeline.
val  pipeline  =  new  Pipeline().setStages(Array(labelIndexer, featureIndexer, dt, labelConverter))
 
// Train model. This also runs the indexers.
val  model  =  pipeline.fit(trainingData)
 
// 作出预测
val  predictions  =  model.transform(testData)
 
// 选择几个示例行展示
predictions.select( "predictedLabel" "label" "features" ).show( 10 , truncate  =  false )
+--------------+-----+-------------------------------------+
|predictedLabel|label|features                             |
+--------------+-----+-------------------------------------+
| 0.0            | 0.0   |[ 0.0 , 22.0 , 0.125 , 0.0 , 2.0 , 14.0 , 4.0 , 5.0 ]|
| 0.0            | 0.0   |[ 0.0 , 22.0 , 0.417 , 0.0 , 1.0 , 17.0 , 6.0 , 4.0 ]|
| 0.0            | 0.0   |[ 0.0 , 22.0 , 0.75 , 0.0 , 2.0 , 18.0 , 6.0 , 5.0 ] |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 0.75 , 0.0 , 3.0 , 16.0 , 1.0 , 5.0 ] |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 0.75 , 0.0 , 4.0 , 16.0 , 1.0 , 5.0 ] |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 1.5 , 0.0 , 1.0 , 14.0 , 1.0 , 5.0 ]  |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 1.5 , 0.0 , 2.0 , 14.0 , 1.0 , 5.0 ]  |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 1.5 , 0.0 , 2.0 , 16.0 , 5.0 , 5.0 ]  |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 1.5 , 0.0 , 2.0 , 16.0 , 5.0 , 5.0 ]  |
| 0.0            | 0.0   |[ 0.0 , 22.0 , 1.5 , 0.0 , 2.0 , 17.0 , 5.0 , 4.0 ]  |
+--------------+-----+-------------------------------------+
 
 
// 选择(预测标签,实际标签),并计算测试误差。
val  evaluator  =  new  MulticlassClassificationEvaluator().setLabelCol( "indexedLabel" ).setPredictionCol( "prediction" ).setMetricName( "accuracy" )
val  accuracy  =  evaluator.evaluate(predictions)
accuracy :  Double  =  0.6972972972972973
 
println( "Test Error = "  + ( 1.0  - accuracy))
Test Error  =  0.3027027027027027
 
 
// 这里的stages(2)中的“2”对应pipeline中的“dt”,将model强制转换为DecisionTreeClassificationModel类型
val  treeModel  =  model.stages( 2 ).asInstanceOf[DecisionTreeClassificationModel]
DecisionTreeClassificationModel (uid = dtc _ b 950 f 91 d 35 f 8 ) of depth  5  with  43  nodes
 
treeModel.getLabelCol
String  =  indexedLabel
 
treeModel.getFeaturesCol
String  =  indexedFeatures
 
treeModel.featureImportances
Vector  =  ( 8 ,[ 0 , 1 , 2 , 4 , 5 , 6 , 7 ],[ 0.012972759843658999 , 0.1075317063921102 , 0.11654682273543511 , 0.17869552275855793 , 0.07532637852021348 , 0.27109893303920024 , 0.237827
876710824 ])
treeModel.getPredictionCol
String  =  prediction
 
treeModel.getProbabilityCol
String  =  probability
 
treeModel.numClasses
Int  =  2
 
treeModel.numFeatures
Int  =  8
 
treeModel.depth
Int  =  5
 
treeModel.numNodes
Int  =  43
 
treeModel.getImpurity
String  =  entropy
 
treeModel.getMaxBins
Int  =  100
 
treeModel.getMaxDepth
Int  =  5
 
treeModel.getMaxMemoryInMB
Int  =  256
 
treeModel.getMinInfoGain
Double  =  0.01
 
treeModel.getMinInstancesPerNode
Int  =  10
 
// 查看决策树
println( "Learned classification tree model:\n"  + treeModel.toDebugString)
Learned classification tree model :
DecisionTreeClassificationModel (uid = dtc _ b 950 f 91 d 35 f 8 ) of depth  5  with  43  nodes
// 例如“feature 7 in {0.0,1.0,2.0}”中的“{0.0,1.0,2.0}”
// 具体解释请参考本人博客http://www.cnblogs.com/wwxbi/p/6125493.html“VectorIndexer自动识别分类的特征,并对它们进行索引”
   If (feature  7  in { 0.0 , 1.0 , 2.0 })
    If (feature  7  in { 0.0 , 2.0 })
     If (feature  4  in { 0.0 , 4.0 })
      Predict :  1.0
     Else (feature  4  not in { 0.0 , 4.0 })
      If (feature  1  < =  32.0 )
       If (feature  1  < =  27.0 )
        Predict :  0.0
       Else (feature  1  27.0 )
        Predict :  1.0
      Else (feature  1  32.0 )
       If (feature  5  < =  16.0 )
        Predict :  0.0
       Else (feature  5  16.0 )
        Predict :  0.0
    Else (feature  7  not in { 0.0 , 2.0 })
     If (feature  4  in { 0.0 , 1.0 , 3.0 , 4.0 })
      If (feature  0  in { 0.0 })
       If (feature  2  < =  7.0 )
        Predict :  0.0
       Else (feature  2  7.0 )
        Predict :  0.0
      Else (feature  0  not in { 0.0 })
       Predict :  0.0
     Else (feature  4  not in { 0.0 , 1.0 , 3.0 , 4.0 })
      Predict :  1.0
   Else (feature  7  not in { 0.0 , 1.0 , 2.0 })
    If (feature  2  < =  4.0 )
     If (feature  6  < =  3.0 )
      If (feature  6  < =  1.0 )
       Predict :  0.0
      Else (feature  6  1.0 )
       Predict :  0.0
     Else (feature  6  3.0 )
      If (feature  5  < =  16.0 )
       If (feature  2  < =  0.75 )
        Predict :  0.0
       Else (feature  2  0.75 )
        Predict :  0.0
      Else (feature  5  16.0 )
       If (feature  7  in { 4.0 })
        Predict :  0.0
       Else (feature  7  not in { 4.0 })
        Predict :  0.0
    Else (feature  2  4.0 )
     If (feature  6  < =  3.0 )
      If (feature  4  in { 0.0 , 1.0 , 2.0 })
       Predict :  0.0
      Else (feature  4  not in { 0.0 , 1.0 , 2.0 })
       If (feature  7  in { 4.0 })
        Predict :  0.0
       Else (feature  7  not in { 4.0 })
        Predict :  0.0
     Else (feature  6  3.0 )
      If (feature  4  in { 0.0 , 2.0 , 3.0 , 4.0 })
       If (feature  6  < =  4.0 )
        Predict :  0.0
       Else (feature  6  4.0 )
        Predict :  0.0
      Else (feature  4  not in { 0.0 , 2.0 , 3.0 , 4.0 })
       If (feature  1  < =  37.0 )
        Predict :  1.0
       Else (feature  1  37.0 )
        Predict :  0.0
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值