Error when making a decision surface graph on a decision tree

Viewed 41

My version of python is 3. I have adapted this code for my data. And when trying to make the graph, on the line

X = l_atributos[:, pair]

I have the error:

list indices must be integers or slices, not tuple

But I'm not seeing where the problem is. Could you help me?

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()
1 Answers

The common problem in data structures used to represent the data in the example and your code.

If you print the content of iris example you may see next data:

from sklearn.datasets import load_iris
iris = load_iris()
print(iris.data)

output

array([[5.1, 3.5, 1.4, 0.2],
       [4.9, 3. , 1.4, 0.2],
       [4.7, 3.2, 1.3, 0.2],
...

As you can see this is the 2D array was wrapped with numpy.array(...) wrapper.

But in your example you have just 2D array:

print(l_atributos[:3])

result

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

If you want to use scikit's example with minimum changes just wrap your data with 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']])
Related