1. sklearn中的决策树
2. sklearn基本建模流程
3.决策树的基本流程
4.代码实现
4.1 数据集 —— 红酒
- 特征值(前13列)
- 目标值(3类)
4.2 代码及结果
4.2.1 预测部分
# 获取数据集
wine = load_wine()
# 划分数据集
x_train, x_test, y_train, y_test = train_test_split(wine.data, wine.target, test_size=0.3)
# 建模
clf = tree.DecisionTreeClassifier(criterion='entropy',random_state=30)
clf = clf.fit(x_train, y_train)
score = clf.score(x_test, y_test) # 分类的精确度
print(score)
结果:
4.2.2 绘制分类树
# 绘制树
feature_name = ['酒精','苹果酸','灰','灰的碱性','镁','总酚','类黄酮','非黄烷类酚类','花青素','颜色强度','色调','od280/od315稀释葡萄酒','脯氨酸']
class_name = ["琴酒","雪莉","贝尔摩德"]
dot_data = tree.export_graphviz(clf
,feature_names = feature_name
,class_names = class_name
,filled = True
,rounded = True)
graph = graphviz.Source(dot_data)
graph
结果:
4.2.3 特征重要性
# 特征重要性
clf.feature_importances_
[*zip(feature_name, clf.feature_importances_)]
结果
5.参数选择
5.1 max_depth 选择
%matplotlib inline
import matplotlib.pyplot as plt
test = []
for i in range(10):
clf = tree.DecisionTreeClassifier(max_depth = i+1
,criterion='entropy'
,random_state=30)
clf = clf.fit(x_train, y_train)
score = clf.score(x_test, y_test)
test.append(score)
plt.plot(range(1,11), test, color='red', label='max_depth')
plt.legend()
plt.show()
结果:
参考: sklearn菜菜的b站视频以及文档。
更多推荐