在python 3中通过其他方式交换.has_khey

时间:2018-07-07 14:16:00

标签: python-3.x pandas numpy matplotlib

我知道在python3中,“。has_khey”被替换为“ in”

但是以我为例,我没有设法使其正常工作。

整个执行报价

from sklearn import model_selection
import pandas as pd
import numpy as np
from sklearn import neighbors, metrics
from matplotlib import pyplot as plt

data = pd.read_csv('your_path/winequality-red.csv', sep=";")
X = data.as_matrix([data.columns[:-1]])

y = data.as_matrix([data.columns[-1]])
y.flatten()
X_train, X_test, y_train, y_test  = \
model_selection.train_test_split(X,y, test_size=0.3)
knn= neighbors.KNeighborsRegressor(n_neighbors = 12)
knn.fit(X_train, y_train)
y_pred = knn.predict(X_test)

返回我错误的部分:

sizes = {} 
for (yt, yp) in zip(list(y_test), list(y_pred)):
   if sizes.has_key((yt, yp)):
      sizes[(yt, yp)] += 1
   else:
      sizes[(yt, yp)] = 1

keys = sizes.keys()
plt.scatter([k[0] for k in keys], [k[1] for k in keys], s=[sizes[k] for k in keys], color='coral')

当我尝试在if sizes.has_key((yt, yp)):中交换if (yt, yp) in sizes:

我收到错误消息:TypeError: unhashable type: 'numpy.ndarray'

download the wine database

提前感谢您的帮助

我正在寻找的结果: plot scatter size

here the .ipynb or .py file

1 个答案:

答案 0 :(得分:0)

我认为您显示的代码实际上不会产生您报告的错误。可能您已在该代码之外的笔记本中重新定义了一些变量?

在任何情况下,关于该问题,您都希望将if sizes.has_key((yt, yp)):替换为

if (yt, yp) in sizes.keys():

这应该给你想要的情节

enter image description here