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

from sklearn.tree import DecisionTreeClassifier

读取Excel数据集

df = pd.read_excel('data.xlsx') X = df.iloc[:, [0, 1]].values y = df.iloc[:, 2].values

训练模型,限制树的最大深度4

clf = DecisionTreeClassifier(max_depth=4)

拟合模型

clf.fit(X, y)

画图

x_min, x_max = X[:, 0].min() - 1, X[:, 0].max() + 1 y_min, y_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx, yy = np.meshgrid(np.arange(x_min, x_max, 0.1), np.arange(y_min, y_max, 0.1))

Z = clf.predict(np.c_[xx.ravel(), yy.ravel()]) Z = Z.reshape(xx.shape)

plt.contourf(xx, yy, Z, alpha=0.4) plt.scatter(X[:, 0], X[:, 1], c=y, alpha=0.8) plt.show()

使用 Python 和 scikit-learn 创建决策树模型并可视化 - 基于 Excel 数据集

原文地址: https://www.cveoy.top/t/topic/hM3K 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录