ID3

优秀相关博客参考链接:http://www.cnblogs.com/pinard/p/6053344.html

一、基础知识——信息熵与条件信息熵







二、决策树的定义与直观理解






































三、决策树类库介绍——DecisionTreeClassifier  和  DecisionTreeRegressor 





   






   
   
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. # Author:ZhengzhengLiu
  4. #鸢尾花数据分类——决策树
  5. from sklearn import tree #决策树
  6. from sklearn.tree import DecisionTreeClassifier #决策分类树
  7. from sklearn.model_selection import train_test_split
  8. from sklearn.model_selection import GridSearchCV #网格搜索交叉验证
  9. from sklearn.pipeline import Pipeline #管道
  10. from sklearn.preprocessing import MinMaxScaler #数据归一化
  11. from sklearn.feature_selection import SelectKBest #特征选择
  12. from sklearn.feature_selection import chi2 #卡方统计量
  13. from sklearn.decomposition import PCA #主成分分析
  14. import numpy as np
  15. import pandas as pd
  16. import matplotlib as mpl
  17. import matplotlib.pyplot as plt
  18. #解决中文显示问题
  19. mpl.rcParams[ ‘font.sans-serif’]=[ u’simHei’]
  20. mpl.rcParams[ ‘axes.unicode_minus’]= False
  21. #导入数据
  22. path = “./datas/iris.data”
  23. data = pd.read_csv(path,header= None)
  24. iris_feature_E = “sepal length”, “sepal width”, “petal length”, “petal width”
  25. iris_feature_C = u”花萼长度”, u”花萼宽度”, u”花瓣长度”, u”花瓣宽度”
  26. iris_class = “Iris-setosa”, “Iris-versicolor”, “Iris-virginica”
  27. #数据分割
  28. x = data[np.arange( 0, 4)] #获取x变量
  29. #x = data[list(range(4))] #与上面一句等价
  30. #print(x.head())
  31. y = pd.Categorical(data[ 4]).codes #Categorical:编码包含大量重复文本的数据,codes把数据y转换成分类型的0,1,2
  32. print( “样本总数:%d;特征属性数目:%d” %x.shape)
  33. print(y)
  34. #划分训练集与测试集
  35. x_train1, x_test1, y_train1, y_test1 = train_test_split(x,y,test_size= 0.2,random_state= 14)
  36. x_train, x_test, y_train, y_test = x_train1, x_test1, y_train1, y_test1
  37. print( “训练数据集样本总数:%d;测试数据集样本总数:%d” %(x_train.shape[ 0],x_test.shape[ 0]))
  38. #对数据集进行标准化
  39. ss = MinMaxScaler()
  40. x_train = ss.fit_transform(x_train,y_train)
  41. x_test = ss.transform(x_test)
  42. print( “原始数据各个特征的调整最小值:”,ss.min_)
  43. print( “原始数据各个特征的缩放数据值:”,ss.scale_)
  44. #特征选择:从已有的特征属性中选择出影响目标最大的特征属性
  45. #常用方法:{分类:F统计量、卡方系数、互信息mutual_info_classif
  46. # 连续:皮尔逊相关系数、F统计量、互信息mutual_info_classif}
  47. #SelectKBest(卡方系数)
  48. ch2 = SelectKBest(chi2,k= 3) #当前案例中,用SelectKBest方法从四个原始特征属性中选择出最能影响目标的3个特征属性
  49. # k 默认为10,指定后会返回想要的特征个数
  50. x_train = ch2.fit_transform(x_train,y_train) #训练并转换
  51. x_test = ch2.transform(x_test) #转换
  52. select_name_index = ch2.get_support(indices= True)
  53. print( “对类别判别影响最大的三个特征属性分别是:”,ch2.get_support(indices= False))
  54. print(select_name_index)
  55. #降维:对于数据而言,如果特征属性比较多,在构建过程中会比较复杂,
  56. # 这时将多维(高维)降到低维空间中
  57. #常用的降维方法:PCA 主成分分析(无监督);人脸识别通常先做一次PCA
  58. # LDA 线性判别分析(有监督),类内方差最小
  59. pca = PCA(n_components= 2) #构建一个PCA对象,设置最终维度为2维
  60. #这里为了后边画图方便,将数据维度设置为 2,一般用默认不设置就可以
  61. x_train = pca.fit_transform(x_train)
  62. x_test = pca.transform(x_test)
  63. #模型构建
  64. model = DecisionTreeClassifier(criterion= “entropy”,random_state= 0)
  65. #模型训练
  66. model.fit(x_train,y_train)
  67. #模型预测
  68. y_test_hat = model.predict(x_test)
  69. #利用数据可视化软件Graphviz打印出决策树
  70. #from sklearn.externals.six import StringIO
  71. #with open(“iris.dot”) as f:
  72. #f = tree.export_graphviz(model,out_file=f)
  73. print( “Score:”,model.score(x_test,y_test))
  74. print( “Classes:”,model.classes_)
  75. N = 100
  76. x1_min = np.min((x_train.T[ 0].min(),x_test.T[ 0].min()))
  77. x1_max = np.max((x_train.T[ 0].max(),x_test.T[ 0].max()))
  78. x2_min = np.min((x_train.T[ 1].min(),x_test.T[ 1].min()))
  79. x2_max = np.max((x_train.T[ 1].max(),x_test.T[ 1].max()))
  80. t1 = np.linspace(x1_min,x1_max,N)
  81. t2 = np.linspace(x2_min,x2_max,N)
  82. x1,x2 = np.meshgrid(t1,t2) #生成网格采样点
  83. x_show = np.dstack((x1.flat,x2.flat))[ 0]
  84. y_show_hat = model.predict(x_show)
  85. y_show_hat = y_show_hat.reshape(x1.shape)
  86. print(y_show_hat.shape)
  87. print(y_show_hat[ 0])
  88. #画图
  89. plt_light = mpl.colors.ListedColormap([ ‘#A0FFA0’, ‘#FFA0A0’, ‘#A0A0FF’])
  90. plt_dark = mpl.colors.ListedColormap([ ‘g’, ‘r’, ‘b’])
  91. plt.figure(facecolor= “w”)
  92. plt.pcolormesh(x1,x2,y_show_hat,cmap=plt_light)
  93. plt.scatter(x_test.T[ 0],x_test.T[ 1],c=y_test.ravel(),edgecolors= “k”,
  94. s= 150,zorder= 10,cmap=plt_dark,marker= “*”) #测试数据
  95. plt.scatter(x_train.T[ 0],x_train.T[ 1],c=y_train.ravel(),edgecolors= “k”,
  96. s= 40,cmap=plt_dark) #全部数据
  97. plt.xlabel( u”特征属性1”,fontsize= 15)
  98. plt.ylabel( u”特征属性2”,fontsize= 15)
  99. plt.xlim(x1_min,x1_max)
  100. plt.ylim(x2_min,x2_max)
  101. plt.grid( True)
  102. plt.title( u”鸢尾花数据的决策树分类”,fontsize= 18)
  103. plt.savefig( “鸢尾花数据的决策树分类.png”)
  104. plt.show()
  105. #参数优化
  106. pipe = Pipeline([
  107. ( ‘mms’, MinMaxScaler()),
  108. ( ‘skb’, SelectKBest(chi2)),
  109. ( ‘pca’, PCA()),
  110. ( ‘decision’, DecisionTreeClassifier())
  111. ])
  112. # 参数
  113. parameters = {
  114. “skb__k”: [ 1, 2, 3, 4],
  115. “pca__n_components”: [ 0.5, 1.0],
  116. “decision__criterion”: [ “gini”, “entropy”],
  117. “decision__max_depth”: [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
  118. }
  119. x_train2, x_test2, y_train2, y_test2 = x_train1, x_test1, y_train1, y_test1
  120. gscv = GridSearchCV(pipe, param_grid=parameters)
  121. gscv.fit(x_train2, y_train2)
  122. print( “最优参数列表:”,gscv.best_params_)
  123. print ( “score值:”,gscv.best_score_)
  124. y_test_hat2 = gscv.predict(x_test2)
  125. mms_best = MinMaxScaler()
  126. skb_best = SelectKBest(chi2,k= 2)
  127. pca_best = PCA(n_components= 0.5)
  128. decision3 = DecisionTreeClassifier(criterion= “gini”,max_depth= 2)
  129. x_train3, x_test3, y_train3, y_test3 = x_train1, x_test1, y_train1, y_test1
  130. x_train3 = pca_best.fit_transform(skb_best.fit_transform(mms_best.fit_transform(x_train3,y_train3),y_train3))
  131. x_test3 = pca_best.transform(skb_best.transform(mms_best.transform(x_test3)))
  132. decision3.fit(x_train3,y_train3)
  133. print( “正确率:”,decision3.score(x_test3,y_test3))
  134. x_train4, x_test4, y_train4, y_test4 = train_test_split(x.iloc[:, : 2], y, train_size= 0.7, random_state= 14)
  135. depths = np.arange( 1, 15)
  136. err_list = []
  137. for d in depths:
  138. clf = DecisionTreeClassifier(criterion= ‘gini’, max_depth=d)
  139. clf.fit(x_train4, y_train4)
  140. score = clf.score(x_test4, y_test4)
  141. err = 1 - score
  142. err_list.append(err)
  143. print( “%d深度,正确率%.5f” % (d, score))
  144. ## 画图
  145. plt.figure(facecolor= ‘w’)
  146. plt.plot(depths, err_list, ‘ro-‘, lw= 3)
  147. plt.xlabel( u’决策树深度’, fontsize= 16)
  148. plt.ylabel( u’错误率’, fontsize= 16)
  149. plt.grid( True)
  150. plt.title( u’决策树层次太多导致的拟合问题(欠拟合和过拟合)’, fontsize= 18)
  151. plt.savefig( “决策树层次太多导致的拟合问题(欠拟合和过拟合).png”)
  152. plt.show()
  153. #运行结果:
  154. 样本总数: 150;特征属性数目: 4
  155. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
  156. 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  157. 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2 2 2 2
  158. 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2
  159. 2 2]
  160. 训练数据集样本总数: 120;测试数据集样本总数: 30
  161. 原始数据各个特征的调整最小值: [ -1.19444444 -0.83333333 -0.18965517 -0.04166667]
  162. 原始数据各个特征的缩放数据值: [ 0.27777778 0.41666667 0.17241379 0.41666667]
  163. 对类别判别影响最大的三个特征属性分别是: [ True False True True]
  164. [ 0 2 3]
  165. Score: 0.966666666667
  166. Classes: [ 0 1 2]
  167. ( 100, 100)
  168. [ 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 1
  169. 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 2 2 2 2
  170. 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2]
  171. 最优参数列表: { ‘skb__k’: 2, ‘decision__max_depth’: 2, ‘pca__n_components’: 0.5, ‘decision__criterion’: ‘gini’}
  172. score值: 0.933333333333
  173. 正确率: 1.0
  174. 1深度,正确率 0.55556
  175. 2深度,正确率 0.73333
  176. 3深度,正确率 0.77778
  177. 4深度,正确率 0.73333
  178. 5深度,正确率 0.68889
  179. 6深度,正确率 0.68889
  180. 7深度,正确率 0.68889
  181. 8深度,正确率 0.66667
  182. 9深度,正确率 0.66667
  183. 10深度,正确率 0.66667
  184. 11深度,正确率 0.66667
  185. 12深度,正确率 0.66667
  186. 13深度,正确率 0.66667
  187. 14深度,正确率 0.66667



猜你喜欢

转载自blog.csdn.net/xiekuang4922/article/details/82661854
ID3