为了账号安全,请及时绑定邮箱和手机立即绑定

Python3 - TypeError:'numpy.float64' 对象不可迭代

Python3 - TypeError:'numpy.float64' 对象不可迭代

心有法竹 2021-11-09 20:10:57
我想绘制一个图,显示使用 KNN 的误分类错误与 de K 个邻居的关系。这是我为此构建的代码:# creating odd list of K for KNNmyList = list(range(1,50))# subsetting just the odd onesneighbors = filter(lambda x: x % 2 != 0, myList)# empty list that will hold cv scorescv_scores = []# perform 10-fold cross validationfor 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 Plotimport matplotlib.pyplot as pltplt.style.use('ggplot')# changing to misclassification errorMSE = [1 - x for x in cv_scores]# determining best koptimal_k = neighbors[MSE.index(min(next(iter(MSE))))]print ("The optimal K neighbors number is %d" % optimal_k)# plot misclassification error vs kplt.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 上运行并防止这种情况发生?
查看完整描述

1 回答

?
倚天杖

TA贡献1828条经验 获得超3个赞

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

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

此外,您获得最佳值的原始语法是正确的(不需要iternext):

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


查看完整回答
反对 回复 2021-11-09
  • 1 回答
  • 0 关注
  • 535 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信