【发布时间】:2020-09-08 21:01:21
【问题描述】:
我已经编写了以下代码来实现KNN
from sklearn.neighbors import KNeighborsClassifier
classifier = KNeighborsClassifier(n_neighbors=5)
classifier.fit(x,y)
classifier.score(x,y)
y_predict_classifier=classifier.predict(x_test)
问题是,当我尝试使用准确度分数找出准确度时,它给了我以下错误:
ValueError Traceback (most recent call last)
<ipython-input-128-358130e4f0a2> in <module>
----> 1 print("Accuracy:",metrics.accuracy_score(y_test, y_predict_classifier))
~\Anaconda3\lib\site-packages\sklearn\metrics\_classification.py in accuracy_score(y_true, y_pred, normalize, sample_weight)
183
184 # Compute accuracy for each possible representation
--> 185 y_type, y_true, y_pred = _check_targets(y_true, y_pred)
186 check_consistent_length(y_true, y_pred, sample_weight)
187 if y_type.startswith('multilabel'):
~\Anaconda3\lib\site-packages\sklearn\metrics\_classification.py in _check_targets(y_true, y_pred)
78 y_pred : array or indicator matrix
79 """
---> 80 check_consistent_length(y_true, y_pred)
81 type_true = type_of_target(y_true)
82 type_pred = type_of_target(y_pred)
~\Anaconda3\lib\site-packages\sklearn\utils\validation.py in check_consistent_length(*arrays)
210 if len(uniques) > 1:
211 raise ValueError("Found input variables with inconsistent numbers of"
--> 212 " samples: %r" % [int(l) for l in lengths])
213
214
ValueError: Found input variables with inconsistent numbers of samples: [176701, 1]
我打印了 y 和 y_predict_classifier 的形状,分别得到 (176701,) 和 (1,)。
谁能告诉我如何解决这个错误?
【问题讨论】:
-
你的 x_test 变量是什么?我们可以看看它是如何分配的吗?
-
可以和x、y、x_test的形状相关。它们的形状是什么? x 应该是 (m, n) ,y 应该是 (m,) 和 x_test (p, n)。看起来 m 是 176701; p 是 1,n 是多少?
标签: python machine-learning knn