python-3.x - 在决策树上制作决策面图时出错
问题描述
我的 python 版本是 3。我已经为我的数据调整了这段代码。当试图制作图表时,在线
X = l_atributos[:, pair]
我有错误:
列表索引必须是整数或切片,而不是元组
但我没有看到问题出在哪里。你可以帮帮我吗?
for pairidx, pair in enumerate([[0, 1],[0, 2],[0, 3],[1, 2],[1, 3],[2, 3]]):
# We only take the two corresponding features
X = l_atributos[:, pair]
y = etiquetas
# Train
clf = DecisionTreeClassifier().fit(X, y)
# Plot the decision boundary
plt.subplot(2, 3, pairidx + 1)
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, plot_step),
np.arange(y_min, y_max, plot_step))
plt.tight_layout(h_pad=0.5, w_pad=0.5, pad=2.5)
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.RdYlBu)
plt.xlabel(['so2', 'no2', 'temp', 'viento', 'precipitacion'][pair[0]])
plt.ylabel(['so2', 'no2', 'temp', 'viento', 'precipitacion'][pair[1]])
# Plot the training points
for i, color in zip(range(n_classes), plot_colors):
idx = np.where(y == i)
plt.scatter(X[idx, 0], X[idx, 1], c=color, label=['nivel 0', 'nivel 1', 'nivel 2', 'nivel 3'][i], cmap=plt.cm.RdYlBu, edgecolor='black', s=15)
plt.suptitle("Decision surface of a decision tree using paired features")
plt.legend(loc='lower right', borderpad=0, handletextpad=0)
plt.axis("tight")
plt.figure()
clf = DecisionTreeClassifier().fit(l_atributos, etiquetas)
plot_tree(clf, filled=True)
plt.show()
解决方案
用于表示示例和您的代码中的数据的数据结构中的常见问题。
如果您打印iris
示例的内容,您可能会看到以下数据:
from sklearn.datasets import load_iris
iris = load_iris()
print(iris.data)
输出
array([[5.1, 3.5, 1.4, 0.2],
[4.9, 3. , 1.4, 0.2],
[4.7, 3.2, 1.3, 0.2],
...
如您所见,这是用numpy.array(...)
包装器包装的 2D 数组。
但是在您的示例中,您只有二维数组:
print(l_atributos[:3])
结果
[['66', '26.0', '12.1', '16.0', '0.0'], ['75', '16.0', '10.0', '26.0', '5.9'], ['61', '25.0', '8.0', '23.0', '29.4']]
如果您想使用 scikit 的示例进行最少的更改,只需使用以下命令包装您的数据numpy.array
:
import numpy as np
l_atributos = np.array([['66', '26.0', '12.1', '16.0', '0.0'], ['75', '16.0', '10.0', '26.0', '5.9'], ['61', '25.0', '8.0', '23.0', '29.4']])
推荐阅读
- angular - 当存储中的数据未更改时,订阅正在触发
- python - 更改函数中位置参数的数量
- python-3.x - 摆脱空间直方图 matplotlib
- html - 如何在 django 的新视图中显示单击的项目/图像?
- excel - 使用 vba 将数据粘贴到下一个空列中
- highcharts - Highcharts - 具有数千个项目的树形图中的异步向下钻取
- python - 如何在这种 python 正则表达式情况下指定非贪婪模式?
- python - Python-BeautifulSoup:如何将 html 保存到数据库中?
- java - 如何在 AWS 上托管 nanohttpd java 应用程序?
- opengl - SSAO 和阴影映射 | 阴影不适用于 SSAO