无法获得准确的KNN结果

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

我正在研究螃蟹物种数据集。我有7个因素,并且正在努力将物种预测为1或0。我的目标是使准确度达到100%。我已经尝试过从1到60的多个k,但不能使它的准确度超过50%。以下是我的KNN代码和60个测试样本的预测结果。我知道如何使用sklearn函数,但我想从头开始。有人可以帮助我在程序中找到逻辑错误吗?

提前谢谢您

x_train, x_test, y_train, y_test = train_test_split(X,target,test_size=0.3)

k=60

distances = []

targets = []

predictions = []

for i in range(len(x_test)):
    for i in range(len(x_test)):
        distances.append([np.sqrt(np.sum(np.square(x_test[i,:] - x_train[i,:]))),i])
    distances = sorted(distances)
    for i in range(k):
        index = distances[i][1]
        targets.append(y_train[index])
    count = Counter(targets).most_common(1)[0][0]
    predictions.append(count)
predictions = np.array(predictions)
print(predictions)
accuracy = accuracy_score(y_test,predictions)
print(accuracy)

[1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0]0.5

python numpy machine-learning data-science knn
1个回答
0
投票

Oabdel,

关于您的代码的几点观察。

•对于二进制分类,您可能需要尝试逻辑回归而不是KNN。使用KNN会将您(标记的)数据聚类为K个聚类,然后您可以将分类标签附加到其上,而不是简单的“这不是/不是特定的蟹种”。

•如果您确实想使用KNN,对于已有的数据,您知道数据集中存在多少种不同种类的螃蟹吗?我注意到您已将K设置为60。K(在KNN中)应该是您要分类的聚类数目,而不是测试样本的数目。

•除非我误解了您的代码,否则您似乎正在尝试使用x_test而不是整个数据集来设置模型。如前所述,由于KNN每次运行算法时都会使用整个数据集,因此以这种方式拆分数据毫无意义。

总之,如果您尝试进行二进制分类,那么KNN可能不是您的算法!如果您想练习KNN,也许可以重新考虑您要使用数据集实现的目标。

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