首页 > 解决方案 > python训练和测试中的错误:如何修复“TypeError:unhashable type:'list'”

问题描述

我正在尝试编写代码,其中数据集分为训练和测试。主要训练部分将分为训练和交叉验证。使用 K-fold 值,我想运行代码,以便将主火车集划分为我们想要的尽可能多的折叠(或组,取决于我们提到的折叠的值),并将 (folds-1) 组分配给分割的训练集和剩余的交叉验证。例如,如果有 3 个折叠,则主列车分为三组:g1、g2、g3。首先,将 g1+g2 作为训练,g3 是交叉验证,然后,g2+g3 是训练,g1 是交叉验证,依此类推,以找到准确度,从而找到最佳 K 值。

我使用的逻辑是根据折叠次数划分主列车并在其上使用随机选择。因此从“split_list”函数中选择一组并进行交叉验证。其余的用于训练(主要训练交叉验证)。

从 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'

标签: pythonpython-3.xlisttypeerror

解决方案


我不知道你想在那里做什么,但问题可能出在train_indices 列表上,就像输出一样显示一个列表,但你有一个包含项目列表的列表,所以他不知道如何阅读该列表。他期望的项目不是项目列表。

所以你有一个包含一个项目列表的主列表,但他希望找到项目而不是另一个项目列表。


推荐阅读