【问题标题】:RuntimeError: mat1 and mat2 shapes cannot be multiplied (28x28 and 784x64)RuntimeError:mat1 和 mat2 形状不能相乘(28x28 和 784x64)
【发布时间】:2021-07-27 09:46:02
【问题描述】:
import torch
import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):

    def __init__(self):
        super().__init__()
        self.fc1=nn.Linear(28*28,64)
        self.fc2=nn.Linear(64,64)
        self.fc3=nn.Linear(64,64)
        self.fc4=nn.Linear(64,10)

    def forward(self,x):
        x=F.relu(self.fc1(x))
        x=F.relu(self.fc2(x))
        x=F.relu(self.fc3(x))
        x=self.fc4(x)
        return F.log_softmax(x,dim=1)

net=Net()
print(net)

X=torch.rand((28,28))
X=X.unsqueeze(0)
output=net(X)
print(output)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (28x28 and 784x64)

当我使用 X=X.view(-1,28*28) 代替 X=X.unsqueeze(0) 时,它给了我想要的结果。我无法完全理解这里使用 unsqueeze() 和 view() 的区别。

【问题讨论】:

    标签: deep-learning pytorch


    【解决方案1】:

    您目前只使用两个维度axis=0 是您的批次,axis=1 是您的特征。

    使用X.view(-1, 28*28) 进行整形将使所有轴变平,但最后一个轴会留下(batch_size, feature_size) 形式的形状。

    虽然X.unsqueeze(0) 只会添加一个额外的轴,不会影响张量X 的整体形式,但它不是重塑。我的意思是如果X 的形状为(batch_size, channel, height, width),这很可能是输入图像。那么X.unsqueeze(0) 将被塑造成(1, batch_size, channel, height, width)

    由于您使用的是全连接网络,因此您现在并且应该使用前者,即将 X 重塑为二维张量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-20
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2022-11-24
      • 2021-09-17
      • 2022-01-19
      • 1970-01-01
      相关资源
      最近更新 更多