美赛python学习d11——决策树,随机森林

Decision Trees

Classification Trees

几种常用的决策树

  1. ID3:由增熵原理决定
  2. C4.5:ID3用训练集的数据进行细小分割,这对新的数据没有意义,还会造成过拟合(overfitting)的问题,C4.5中增加了信息增益率,降低了过拟合的概率
  3. CART:用GINI指数决定如何分裂,但也存在过拟合的问题

实例

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv("Social_Network_Ads.csv")

x = dataset.iloc[:, [2,3]].values

y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

from sklearn.preprocessing import StandardScaler

sc_x = StandardScaler()

x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)
#利用决策树进行分类
from sklearn.tree import DecisionTreeClassifier
classifier=DecisionTreeClassifier(criterion="entropy",random_state=0)
classifier.fit(x_train,y_train)
y_pred=classifier.predict(x_test)
#利用混淆矩阵评估分类的性能
from sklearn.metrics import confusion_matrix
cn=confusion_matrix(y_test, y_pred)
#可视化分类结果(测试集)
from matplotlib.colors import ListedColormap
X_set, y_set = x_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('yellow', 'blue'))(i), label = j)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

Random Forest

原理

采用多个分类器进行预测,再将分类结果进行汇总决出最终的结果,又叫做集成学习(Ensemble Learning),可以减少预测结果的浮动率

算法步骤

美赛python学习d11——决策树,随机森林
通俗来讲就是不断重复从训练集里挑k个数据建立决策树,最后建立多棵决策,对于一个新数据,所有决策树都进行决策,最后综合得出结果

实例

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

dataset = pd.read_csv("Social_Network_Ads.csv")

x = dataset.iloc[:, [2,3]].values

y = dataset.iloc[:, 4].values

from sklearn.model_selection import train_test_split

x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)

from sklearn.preprocessing import StandardScaler

sc_x = StandardScaler()

x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)
#利用决策树进行分类
from sklearn.ensemble import RandomForestClassifier
#n_estimators代表决策树数量
classifier=RandomForestClassifier(n_estimators=10,criterion="entropy",random_state=0)
classifier.fit(x_train,y_train)
y_pred=classifier.predict(x_test)
#利用混淆矩阵评估分类的性能
from sklearn.metrics import confusion_matrix
cn=confusion_matrix(y_test, y_pred)
#可视化分类结果(测试集)
from matplotlib.colors import ListedColormap
X_set, y_set = x_test, y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),
                     np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],
                c = ListedColormap(('yellow', 'blue'))(i), label = j)
plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

上一篇:深度学习--bbox坐标转换(任意格式【list,numpy,tensor】、任意维度【向量、一维矩阵、二维矩阵】)


下一篇:深度学习入门-从朴素感知机到神经网络