TypeError: Expected sequence or array-like, got estimator KNeighborsClassifier

TypeError: Expected sequence or array-like, got estimator KNeighborsClassifier

我正在尝试使用 scikit-learn 实现 K-NN 算法。 这是我的代码的样子:

X = df.drop(columns=['Purchased'])
y = df['Purchased'].values
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, 
test_size=0.3,stratify=y)
from sklearn.preprocessing import StandardScaler  
scaler = StandardScaler()  
scaler.fit(X_train)
X_train = scaler.transform(X_train)  
X_test = scaler.transform(X_test)  
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors = 3)
knn.fit(X_train,y_train)
knn.predict(X_test)
knn.score(X_test, y_test)
from sklearn.metrics import classification_report, confusion_matrix  
print(confusion_matrix(y_test, knn))  
print(classification_report(y_test, knn)) 

在 运行 最后 2 个输出之后,我收到此消息:

TypeError: Expected sequence or array-like, got estimator KNeighborsClassifier(algorithm='auto', leaf_size=30, metric='minkowski',
           metric_params=None, n_jobs=None, n_neighbors=3, p=2,
           weights='uniform')

有人知道问题出在哪里吗? 谢谢!

print(confusion_matrix(y_test, knn.predict(X_test))
print(classification_report(y_test, knn.predict(X_test))

在这种情况下,knn 是 class 的一个对象,没有实现 str。所以你必须用 knn.predict.

的结果替换它

如错误提示所示,confusion_matrix 函数需要一个序列或类似数组的对象(例如列表),而不是它得到一个 KNeighborsClassifier 对象,在您的情况下是 knn.

您可以通过像这样保存 predict 函数的输出来解决此问题:

my_result = knn.predict(X_test)

然后您可以在下一行中使用此变量:

print(confusion_matrix(y_test, my_result))