解决PyTorch RuntimeError: Expected 3-dimensional input for 3-dimensional weight, but got 4-dimensional input 错误
在使用PyTorch进行矩阵乘法运算时,经常会遇到RuntimeError: Expected 3-dimensional input for 3-dimensional weight, but got 4-dimensional input of size [100, 1, 10000, 12] instead错误。这个错误通常是因为输入数据的维度与权重矩阵的维度不匹配导致的。
为了解决这个问题,可以将输入数据的第二个维度(通常为1)删除,使其与权重矩阵的维度匹配。
修改后的代码如下:
import torch
weight = torch.randn(5, 3)
input = torch.randn(100, 10000, 12)
output = torch.matmul(input, weight)
这样修改后,weight的形状为[5, 3],input的形状为[100, 10000, 12],可以进行矩阵乘法运算。
注意: 确保修改后的input的维度与weight的维度匹配,否则仍然会引发错误。
原文地址: https://www.cveoy.top/t/topic/c0x9 著作权归作者所有。请勿转载和采集!