簡體   English   中英

ValueError: 目標尺寸 (torch.Size([32])) 必須與輸入尺寸相同 (torch.Size([32, 3]))

[英]ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 3]))

我看過一些解釋。

這里

但我明白我想出了什么問題,但我的錯誤發生並不不知所措。 例如,發生錯誤的代碼段是 output outputs = model(**inputs)

 # INPUTS
        # Pulling out the inputs in the form of dictionary
        inputs = {'input_ids':      batch[0],
                  'attention_mask': batch[1],
                  'labels':         batch[2],
                  }
        # OUTPUTS
        # '**' Unpacking the dictionary stright into the input
        outputs = model(**inputs)

        loss = outputs[0]
        loss_train_total += loss.item()
        loss.backward()           # backpropagation

我得到的錯誤:

 File "c:\Users\#####\BERT.py", line 193, in <module>
    outputs = model(**inputs)
ValueError: Target size (torch.Size([32])) must be the same as input size (torch.Size([32, 3]))

現在我知道 32 是批量大小,但不確定這個目標在哪里。 我知道這是標簽,但我該如何解決它才能運行?

謝謝。

編輯

我嘗試了一種熱編碼標簽,如下所示:

enc = OneHotEncoder(handle_unknown='ignore')
enc.fit(train_y.reshape(-1, 1))
train_y = enc.transform(train_y.reshape(-1, 1)).toarray()

enc.fit(test_y.reshape(-1, 1))
test_y = enc.transform(test_y.reshape(-1, 1)).toarray()

輸出

[[1. 0. 0.]
 [0. 0. 1.]
 [0. 0. 1.]
 ...
 [0. 1. 0.]
 [1. 0. 0.]
 [0. 0. 1.]]

但我仍然收到相同的錯誤消息

我有一個類似的問題,我能找到的解決方案是擴大“標簽”的尺寸。 我使用以下代碼完成了此操作:

labels = torch.nn.functional.one_hot(labels)

這會將您的標簽列表轉換為單熱編碼。 這應該與標簽和輸入的維度相匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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