python-3.x - 在决策树上制作决策曲面图时出错

标签 python-3.x scikit-learn

我的 python 版本是 3。 我已经改编了this我的数据代码。 并在尝试制作图表时,在线

X = l_atributos[:, pair]

我有错误:

list indices must be integers or slices, not tuple

但我看不出问题出在哪里。你能帮帮我吗?

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(...) 包装器包装的二维数组。

但在您的示例中,您只有二维数组:

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']])

关于python-3.x - 在决策树上制作决策曲面图时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56523270/

相关文章:

python - 在 Python 中有效比较两个文件中的行

python - 防止 RandomizedSearchCV 预测 KNN 分类器的所有一类

python - 如果先运行并行代码会挂起,但如果在运行非并行代码之后运行则可以正常工作

python - 获得猜测的准确性

android - 从单个脚本运行多个 Monkey Runner(Python 脚本)程序

python - 如何使用 cpython 将结构数组传递给 DLL 函数?

python - RandomForestClassifier .fit 在 ec2 上因内存错误而失败,但在本地运行时没有错误

python - 生成 3D 高斯数据

python - 为什么 open(True, 'w' ) 会像 sys.stdout.write 一样打印文本?

python-3.x - 加速Python中的位串/位运算?