图k-NN错误:IndexError:索引1超出尺寸1的轴1的范围

问题描述 投票:1回答:1

我是机器学习的新手,并希望绘制一个k-NN分类器图。

我遇到此错误“ indexError:索引1超出了尺寸1的轴1的范围”,但我不明白问题出在哪里?

我的数据对于ML而言确实很小,但我目前仅进行跟踪。数据是4列的结构。(图像链接在代码下方)第1个是索引列,第2个和第3个是两个变量,第4个是目标分类器。只有21个样本。

import pandas as pd
from pylab import rcParams
import matplotlib.pyplot as plt
from sklearn import neighbors
from matplotlib.colors import ListedColormap
from sklearn.neighbors import KNeighborsClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, classification_report

n_neighbors = 5

# import some data to play with
Test_Cu_48hrs = pd.read_csv('Test_Cu_48hrs.csv' , index_col = 0)

# prepare data
X = Test_Cu_48hrs.iloc[:,1:2].values 
y = Test_Cu_48hrs.iloc[:,2].values
h = .02

# Create color maps
cmap_light = ListedColormap(['#FFAAAA', '#AAFFAA', '#AAAAFF','#AFAFAF','#FFFF00','#800080','#00CED1'])
cmap_bold  = ListedColormap(['#FF0000', '#00FF00', '#0000FF','#AFAFAF','#FFFF00','#800080','#00CED1'])

# we create an instance of Neighbours Classifier and fit the data.
clf = neighbors.KNeighborsClassifier(n_neighbors, weights='distance')
clf.fit(X, y)

# calculate min, max and limits
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, h),
np.arange(y_min, y_max, h))

# predict class using data and kNN classifier
Z = clf.predict(np.c_[xx.ravel(), yy.ravel()])

# Put the result into a color plot
Z = Z.reshape(xx.shape)
plt.figure()
plt.pcolormesh(xx, yy, Z, cmap=cmap_light)

# Plot also the training points
plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap_bold)
plt.xlim(xx.min(), xx.max())
plt.ylim(yy.min(), yy.max())
plt.title("7-Class classification (k = %i)" % (n_neighbors))
plt.show() 


  [1]: https://i.stack.imgur.com/J0y3i.png
python pandas numpy scikit-learn knn
1个回答
0
投票

您的错误是由于您对熊猫df的切片方式引起的。这样一来,您将获得X作为一维。因此,您的错误超出范围索引。


0
投票

您的错误是由于您对熊猫进行切片的方式引起的。这样一来,您将获得X作为一维。因此,您的错误超出范围索引。

© www.soinside.com 2019 - 2024. All rights reserved.