我想绘制一个图,显示使用 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 上运行并防止这种情况发生?
倚天杖
相关分类