怎么对决策树的分类预测的结果画散点图,请给出具体代码
时间: 2023-06-08 09:09:18 浏览: 48
这是一个python的例子代码,供参考:
首先,我们需要用决策树模型拟合数据,并得到预测结果:
```python
from sklearn.tree import DecisionTreeClassifier
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data[:, 2:] # petal length and width
y = iris.target
tree_clf = DecisionTreeClassifier(max_depth=2)
tree_clf.fit(X, y)
# predict
y_pred = tree_clf.predict(X)
```
接着,我们可以用matplotlib库来绘制散点图:
```python
import matplotlib.pyplot as plt
# visualize
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs", label="Iris setosa")
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^", label="Iris versicolor")
plt.plot(X[:, 0][y==2], X[:, 1][y==2], "yo", label="Iris virginica")
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
plt.legend(loc="upper left", fontsize=14)
# add decision boundaries
from matplotlib.colors import ListedColormap
import numpy as np
def plot_decision_boundary(clf, X, y, axes=[0, 7.5, 0, 3], iris=True, legend=False, plot_training=True):
x1s = np.linspace(axes[0], axes[1], 100)
x2s = np.linspace(axes[2], axes[3], 100)
x1, x2 = np.meshgrid(x1s, x2s)
X_new = np.c_[x1.ravel(), x2.ravel()]
y_pred = clf.predict(X_new).reshape(x1.shape)
custom_cmap = ListedColormap(['#9898ff','#fafab0','#a0faa0'])
plt.contourf(x1, x2, y_pred, alpha=0.3, cmap=custom_cmap)
if not iris:
custom_cmap2 = ListedColormap(['#000000','#ffffff','#ff0000'])
plt.contour(x1, x2, y_pred, cmap=custom_cmap2, alpha=0.8)
if plot_training:
plt.plot(X[:, 0][y==0], X[:, 1][y==0], "bs")
plt.plot(X[:, 0][y==1], X[:, 1][y==1], "g^")
plt.plot(X[:, 0][y==2], X[:, 1][y==2], "yo")
plt.axis(axes)
if iris:
plt.xlabel("Petal length", fontsize=14)
plt.ylabel("Petal width", fontsize=14)
else:
plt.xlabel(r"$x_1$", fontsize=18)
plt.ylabel(r"$x_2$", fontsize=18, rotation=0)
if legend:
plt.legend(loc="lower right", fontsize=14)
plt.figure(figsize=(8, 4))
plot_decision_boundary(tree_clf, X, y)
plt.show()
```
此时我们得到的图像将是决策树分类结果与散点图的叠加。