我想制作一个图表,显示错误分类错误与使用KNN的de K邻居。
这是我为此构建的代码:
# creating odd list of K for KNN
myList = list(range(1,50))
# subsetting just the odd ones
neighbors = filter(lambda x: x % 2 != 0, myList)
# empty list that will hold cv scores
cv_scores = []
# perform 10-fold cross validation
for k in neighbors:
knn = KNN(n_neighbors=k, n_jobs = 6, metric = 'minkowski', contamination = 0.05)
scores = cross_val_score(knn, X_test, pred, cv=10, scoring='accuracy')
cv_scores.append(scores.mean())
### Create Plot
import matplotlib.pyplot as plt
plt.style.use('ggplot')
# changing to misclassification error
MSE = [1 - x for x in cv_scores]
# determining best k
optimal_k = neighbors[MSE.index(min(next(iter(MSE))))]
print ("The optimal K neighbors number is %d" % optimal_k)
# plot misclassification error vs k
plt.plot(neighbors, MSE, figsize = (20,12))
plt.xlabel('Number of Neighbors K')
plt.ylabel('Misclassification Error')
plt.show()
问题出在这一行:
optimal_k = neighbors[MSE.index(min(next(iter(MSE))))]
这段代码好像是用python 2编写的。这是原来的一行:
optimal_k = neighbors[MSE.index(min(MSE))]
我添加了next()
和iter()
来解决这个问题,正如一些用户在类似的其他线程中所建议的那样。但是我收到了这个错误:
TypeError: 'numpy.float64' object is not iterable
我知道为什么会发生这种错误,它应该迭代一个列表,但它只取数字。我认为这个问题来自filter()
在这一行使用:
neighbors = filter(lambda x: x % 2 != 0, myList)
我如何修复此代码在python 3上运行并防止这种情况发生?
提前致谢
编辑:
我正在使用的KNN版本不是sklearn中的版本,对于那些想要尝试此代码的人来说。它来自一个名为PYOD的异常检测包。链接here
您也可以使用sklearn中的原始KNN进行尝试,但请注意,您需要删除污染参数以及距离参数
问题是代码将neighbors
定义为生成器并在第一个循环中耗尽它。解决方案:使用列表。
neighbors = list(filter(lambda x: x % 2 != 0, myList))
您获得最佳的原始语法也是正确的(不需要iter
或next
):
optimal_k = neighbors[MSE.index(min(MSE))]