![](/img/trans.png)
[英]How to fix 'TypeError: unhashable type: 'list' error?
[英]Error in python train and test : How to fix “TypeError: unhashable type: 'list'”
我正在尝试编写代码,其中数据集分为训练和测试。 主要训练部分将分为训练和交叉验证。 使用 K-fold 值,我想运行代码,以便将主火车集分成我们想要的尽可能多的折叠(或组,取决于我们提到的折叠的值),并将 (folds-1) 组分配给分割的训练集和剩余的交叉验证。 例如,如果有 3 个折叠,则主列车分为三组:g1、g2、g3。 首先,将 g1+g2 作为训练,g3 是交叉验证,然后,g2+g3 是训练,g1 是交叉验证,依此类推,以找到准确率,从而找到最佳 K 值。
我使用的逻辑是根据折叠次数划分主列车并在其上使用随机选择。 因此从“split_list”function 中选择一组并进行交叉验证。 rest 用于训练(主要训练交叉验证)。
从 sklearn.metrics 导入随机数导入 accuracy_score
def split_list(x_train,折叠):
length = len(x_train)
return random.choices([ x_train[i*length // folds: (i+1)*length // folds]
for i in range(folds) ])
def Random_Search(x_train,y_train,classifier, params, folds):
trainscores = []
cvscores = []
for k in tqdm(params['n_neighbors']):
trainscores_folds = []
cvscores_folds = []
for j in range(0, folds):
cv_indices = split_list(list(x_train), folds)
train_indices = list(set(list(range(1, len(x_train)))) -
set(cv_indices))
我得到的错误:
TypeError Traceback (most recent call last)
<ipython-input-114-808deaf8461e> in <module>
8 params = {'n_neighbors':sorted(random.sample(range(1,50),10))}
9 folds = 9
---> 10 trainscores,cvscores = Random_Search(X_train, y_train, neigh, params, folds)
11 plt.plot(params['n_neighbors'],trainscores, label='train cruve')
12 plt.plot(params['n_neighbors'],cvscores, label='cv cruve')
<ipython-input-113-fc0b09f4ad82> in Random_Search(x_train, y_train, classifier, params, folds)
14 for j in range(0, folds):
15 cv_indices = split_list(list(x_train), folds)
---> 16 train_indices = list(set(list(range(1, len(x_train)))) - set(cv_indices))
17 # selecting the data points based on the train_indices and test_indices
18 X_train = x_train[train_indices]
TypeError: unhashable type: 'list'
我不知道你想在那里做什么,但问题可能出在train_indices 列表上,就像 output 这样的列表,但你有一个包含项目列表的列表,所以他不知道如何阅读该列表。 他期望的项目不是项目列表。
所以你有一个包含一个项目列表的主列表,但他希望找到项目而不是另一个项目列表。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.