Last Updated on 2021-07-24 by Clay
問題描述
今天,當我在嘗試著自己使用 nn.Embedding() 拼接並計算句向量的時候,我在自己預先準備的 DataLoader 上得到了這樣的一個報錯:
TypeError: expected Tensor as element 0 in argument 0, but got list
仔細研究了一下,發現問題發生在我製作 DataLoader 時,我的資料並不是 Tensor 資料型態,故沒辦法使用 DataLoader 自行決定 Batch Size,並餵給我的模型當作訓練資料。
同樣的錯誤會發生在:
torch.cat((tensor1, tensor2), 0)
或
torch.stack((tensor1, tensor2), 0)
以上的案例,只要 tensor1 或 tensor2 其中某項並不是 Tensor 的資料型態,就會出現文章最上頭的報錯。
至於為什麼 DataLoader 會出現這個報錯?我目前查看了一下,多半是因為 DataLoader 會使用 torch.stack() 去幫我們拼接資料的緣故。
解決方法
解決方法說穿了非常單純,在一般自行拼接資料報錯的時候,把 Tensor 印出來看看,確認究竟是哪裡的資料並不是 Tensor 的型態。
至於我的案例,由於我資料的格式沒法妥協,故決定捨棄 DataLoader,自行決定好 Batch Size 再放入模型中。雖然麻煩了一點,但這確實可行。
References
Read More
- [已解決][PyTorch] RuntimeError: Attempting to deserialize object on CUDA device 3 but torch.cuda.device_count() is 1.
- [已解決][PyTorch] RuntimeError: CUDA out of memory. Tried to allocate 2.0 GiB
- [已解決][PyTorch] IndexError: Dimension out of range (expected to be in range of [-1, 0], but got 1)
- [已解決][PyTorch] TypeError: not a sequence
- [已解決][PyTorch] RuntimeError: bool value of Tensor with more than one value is ambiguous