Input type (torch.cuda.DoubleTensor) and weight type (torch.cuda.FloatTensor) should be the same 要如何修正? 並且哪一種格式比較節省資源?
你遇到的錯誤是:
Input type (torch.cuda.DoubleTensor) and weight type (torch.cuda.FloatTensor) should be the same
這代表你的模型的參數(weight
)是 FloatTensor
(也就是 float32
),但你傳入的 input 是 DoubleTensor
(也就是 float64
),這兩種精度不同,PyTorch 無法自動轉換,因此出錯。
✅ 修正方法
只要在 input 資料進模型之前,把它轉成 float32
即可:
x = x.float() # or .to(torch.float32)
或如果你是使用 GPU:
如果你用的是 numpy
資料轉為 tensor,也建議從 numpy 就強制轉成 float32
:
✅ 哪種格式比較節省資源?
格式 | PyTorch 名稱 | 精度 | 每個元素所需記憶體 | 建議用途 |
---|---|---|---|---|
float32 |
torch.float |
單精度 | 4 bytes | ✅ 99% 情況下推薦,速度快、精度夠 |
float64 |
torch.double |
雙精度 | 8 bytes | ❌ 除非你做物理模擬、科研數值分析才需要 |
float16 |
torch.float16 |
半精度 | 2 bytes | ⚠️ 訓練有難度,適用於加速推論或使用 AMP(自動混合精度) |
小建議:
-
你的模型參數預設就是
float32
(除非你有手動設定double()
) -
一律使用
float32
最省資源且效能最好 -
遇到這錯誤,99% 是你轉換資料時忘了指定 dtype,補上
.float()
就好了
如果你需要自動轉換所有資料為 float32
,也可以統一包裝在你的 Dataset
或 collate_fn
裡
留言板
歡迎留下建議與分享!希望一起交流!感恩!