python用scikit-learn来训练决策树模型(分类)
决策树可以通过将特征空间划分成不同的矩形来构建复杂的决策边界。 然而,必须小心,决策树越深,决策边界就越复杂,越容易导致过拟合。
import matplotlib.pyplot as plt
import numpy as np
from sklearn.tree import DecisionTreeClassifier
from matplotlib.colors import ListedColormap
from sklearn import datasets
from sklearn.model_selection import train_test_split
# 把.dot数据文件转换成决策树的图像
import graphviz
from pydotplus import graph_from_dot_data
from sklearn.tree import export_graphviz
# 三种不同的杂质标准
# 基尼杂质
def gini(p):
return p * (1 - p) + (1 - p) * (1 - (1 - p))
# 熵
def entropy(p):
return - p * np.log2(p) - (1 - p) * np.log2((1 - p))
# 分类错误
def error(p):
return 1 - np.max([p, 1 - p])
x = np.arange(0.0, 1.0, 0.01)
ent = [entropy(p) if p != 0 else None for p in x]
sc_ent = [e * 0.5 if e else None for e in ent]
err = [error(i) for i in x]
fig = plt.figure()
ax = plt.subplot(111)
for i, lab, ls, c, in zip([ent, sc_ent, gini(x), err],
['Entropy', 'Entropy (scaled)',
'Gini Impurity', 'Misclassification Error'],
['-', '-', '--', '-.'],
['black', 'lightgray', 'red', 'green', 'cyan']):
line = ax.plot(x, i, label=lab, linestyle=ls, lw=2, color=c)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.15),
ncol=4, fancybox=False, shadow=True)
ax.axhline(y=0.5, linewidth=1, color='k', linestyle='--')
ax.axhline(y=1.0, linewidth=1, color='k', linestyle='--')
plt.ylim([0, 1.1])
plt.xlabel('p(i=1)')
plt.ylabel('Impurity Index')
#plt.savefig('images/03_19.png', dpi=300, bbox_inches='tight')
plt.show()
# =================================================================
iris = datasets.load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
print('Class labels:', np.unique(y))
# Splitting data into 70% training and 30% test data:
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=1, stratify=y)
def plot_decision_regions(X, y, classifier, test_idx=None, resolution=0.02):
# setup marker generator and color map
markers = ('s', 'x', 'o', '^', 'v')
colors = ('red', 'blue', 'lightgreen', 'gray', 'cyan')
cmap = ListedColormap(colors[:len(np.unique(y))])
# plot the decision surface
x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1
x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1
xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, resolution),
np.arange(x2_min, x2_max, resolution))
print("xx1, xx2:\n", xx1, "\n", xx2)
Z = classifier.predict(np.array([xx1.ravel(), xx2.ravel()]).T)
Z = Z.reshape(xx1.shape)
plt.contourf(xx1, xx2, Z, alpha=0.3, cmap=cmap)
plt.xlim(xx1.min(), xx1.max())
plt.ylim(xx2.min(), xx2.max())
for idx, cl in enumerate(np.unique(y)):
plt.scatter(x=X[y == cl, 0],
y=X[y == cl, 1],
alpha=0.8,
c=colors[idx],
marker=markers[idx],
label=cl,
edgecolor='black')
# highlight test samples
if test_idx:
# plot all samples
X_test, y_test = X[test_idx, :], y[test_idx]
plt.scatter(X_test[:, 0],
X_test[:, 1],
c='y',
edgecolor='black',
alpha=1.0,
linewidth=1,
marker='o',
s=100,
label='test set')
tree = DecisionTreeClassifier(criterion='gini',
max_depth=4,
random_state=1)
tree.fit(X_train, y_train)
X_combined = np.vstack((X_train, X_test))
y_combined = np.hstack((y_train, y_test))
plot_decision_regions(X_combined, y_combined,
classifier=tree, test_idx=range(105, 150))
plt.xlabel('petal length [cm]')
plt.ylabel('petal width [cm]')
plt.legend(loc='upper left')
plt.tight_layout()
#plt.savefig('images/03_20.png', dpi=300)
plt.show()
dot_data = export_graphviz(tree,
filled=True, # 添加颜色
rounded=True, # 框的边缘圆角
class_names=['Setosa',
'Versicolor',
'Virginica'], # 显示大多数分类标签
feature_names=['petal length',
'petal width'], # 显示分裂标准的特征
out_file=None)
graph = graph_from_dot_data(dot_data)
graph.write_png('xxx\\chap03tree.png')
运行结果:
Class labels: [0 1 2]
xx1, xx2:
[[0. 0.02 0.04 … 7.84 7.86 7.88]
[0. 0.02 0.04 … 7.84 7.86 7.88]
[0. 0.02 0.04 … 7.84 7.86 7.88]
…
[0. 0.02 0.04 … 7.84 7.86 7.88]
[0. 0.02 0.04 … 7.84 7.86 7.88]
[0. 0.02 0.04 … 7.84 7.86 7.88]]
[[-0.9 -0.9 -0.9 … -0.9 -0.9 -0.9 ]
[-0.88 -0.88 -0.88 … -0.88 -0.88 -0.88]
[-0.86 -0.86 -0.86 … -0.86 -0.86 -0.86]
…
[ 3.44 3.44 3.44 … 3.44 3.44 3.44]
[ 3.46 3.46 3.46 … 3.46 3.46 3.46]
[ 3.48 3.48 3.48 … 3.48 3.48 3.48]]
运行结果图: