首页 > 解决方案 > Python3 - TypeError:'numpy.float64'对象不可迭代

问题描述

我想绘制一个图,显示错误分类错误与使用 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 的异常检测包。链接在这里

您也可以使用 sklearn 中的原始 KNN 进行尝试,但请注意,您需要删除污染参数,可能还有距离参数

标签: pythonpython-3.xnumpyplotknn

解决方案


问题是代码被定义neighbors为生成器并在第一个循环中耗尽它。解决方案:使用列表。

neighbors = list(filter(lambda x: x % 2 != 0, myList))

此外,您获得最佳效果的原始语法是正确的(不需要iteror next):

optimal_k = neighbors[MSE.index(min(MSE))]

推荐阅读