簡體   English   中英

python 訓練和測試中的錯誤:如何修復“TypeError: unhashable type: 'list'”

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM