python - 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 进行尝试,但请注意,您需要删除污染参数,可能还有距离参数
解决方案
问题是代码被定义neighbors
为生成器并在第一个循环中耗尽它。解决方案:使用列表。
neighbors = list(filter(lambda x: x % 2 != 0, myList))
此外,您获得最佳效果的原始语法是正确的(不需要iter
or next
):
optimal_k = neighbors[MSE.index(min(MSE))]
推荐阅读
- javascript - AngularJS:将相同的组件添加到多个模块
- python-2.7 - 将从 Pandas 数据帧获得的字符串转换为每行的单独列表
- python - 在字典中附加值列表
- python - 将python连接到sqlite3并一次填充多行
- ios - 如何在 Swift 中将字典数组存储到领域数据库
- masm - 使用汇编语言将命令行参数传递给 WInAPI 函数
- android - 解释 Mobile First 应用真实性机制?
- google-apps-script - 使用 Apps 脚本转置并复制到另一张工作表
- lua - 如何确定 sysdig 字段是否存在或如果不存在则处理错误
- python - 获取 IOError:[Errno 121] 尝试通过 I2C 从 Arduino 获取数据时,python(覆盆子)上的 smbus 出现远程 I/O 错误