IndexError:数组索引过多:数组是二维的,但有 3 个索引

问题描述 投票:0回答:3
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd 

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train,Y_train)

# Visualising the Test set results
from matplotlib.colors import ListedColormap
X_set, y_set = X_test, Y_test
X1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 
1, step = 0.01),np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, 
step = 0.01))
plt.sactter(X1, X2, knn.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
         alpha = 0.75, cmap = ListedColormap(('red', 'green')))
plt.xlim(X1.min(), X1.max())
plt.ylim(X2.min(), X2.max())
for i, j in enumerate(np.unique(y_set)):
    plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],c = ListedColormap(('red', 
    'green'))(i), label = j)

plt.title('Classifier (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

错误:

File "C:\Users\shaar\.spyder-py3\MLPractice\KNN.py", line 55, in <module>
plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1])

IndexError: too many indices for array: array is 2-dimensional, but 3 were indexed
python-3.x numpy knn
3个回答
0
投票

当您尝试输入或尝试使用 numpy 数组的其他维度(当它仅为一维时)时,通常会发生这种情况。如果你有一个类似 numpy 数组,那就更清楚了

a = [1,2,3,4]
稍后,如果您尝试使用像
(1,2)
这样的值,如果您尝试查找 2D numpy 数组的第一行和第二列,它将采用它。 因此在访问 numpy 数组时避免使用逗号。希望我很清楚,如果不考虑检查https://www.w3schools.com/python/numpy/numpy_creating_arrays.asp


0
投票

如果 numpy 数组有二维但其中一个只有一个块,那么它们的作用有点令人困惑。 在您的代码片段中,我们看不到您在

y_set
中填写的内容

X_set, y_set = X_test, Y_test
但我认为如果你用 

y_set

 观察 
y_set.shape
 的尺寸,你会得到

(150,1)
(我假设有 150 个数据集)。 Python 将为每个形状生成一个索引。要分离所需的尺寸,您可以将不需要的尺寸设置为零:

y_set_one_dimension = y_set[:,0] print(y_set_one_dimension.shape)
就像

如何访问 NumPy 多维数组的第 i 列?中所描述的那样

输出将是:

(150,)
现在散点图将获得二维所需的 2 个 indizies 并且可以工作。

注释:

如果

y_set

 是一个数据框,你必须首先将其转换为 numpy 数组:

yArray = numpy.array(y_set)
    

-1
投票
X_set, y_set = X_test, Y_test.ravel()
    
© www.soinside.com 2019 - 2024. All rights reserved.