繁体   English   中英

Pytorch RuntimeError: mat1 和 mat2 形状不能相乘(32x246016 和 3136x1000)

[英]Pytorch RuntimeError: mat1 and mat2 shapes cannot be multiplied (32x246016 and 3136x1000)

我正在 Pytorch 上构建一个 CNN。 我对输入有点困惑。 我收到以下错误:

RuntimeError:mat1 和 mat2 形状不能相乘(32x246016 和 3136x1000)

图像为 250 x 250 灰度。

谁能看看我的构造函数并告诉我哪里出错了? 如果您能向我解释为什么我错了以及为什么您的答案是正确的,则可以加分; ;)

class CNN(nn.Module):

# Contructor
def __init__(self):
    super(CNN, self).__init__()
    self.cnn1 = nn.Conv2d(1, 32, kernel_size=5, stride=1, padding=2)
    self.conv1_bn = nn.BatchNorm2d(32)

    self.maxpool1=nn.MaxPool2d(kernel_size=2, stride=2)
    
    self.cnn2 = nn.Conv2d(32, 64, kernel_size=5,stride=1, padding=2)
    self.conv2_bn = nn.BatchNorm2d(64)
    self.maxpool2=nn.MaxPool2d(kernel_size=2, stride=2)  
    
    self.drop_out1 = nn.Dropout()
    self.fc1 = nn.Linear(7 * 7 * 64, 1000)
    self.bn_fc1 = nn.BatchNorm2d(1000)
    
    self.fc2 = nn.Linear(1000, 1)
    

    

# Prediction
def forward(self, x):
    x = self.cnn1(x)
    x = self.conv1_bn(x)
    x = torch.relu(x)
    x = self.maxpool1(x)
    x = self.cnn2(x)
    x = self.conv2_bn(x)
    x = torch.relu(x)
    x = self.maxpool2(x)
    x = x.view(x.size(0), -1)
    x = self.drop_out1(x)
    x = self.fc1(x)
    x = self.bn_fc1(x)
    x = torch.relu(x)
    x = self.fc2(x)
    x = torch.sigmoid(x)
   
    return x

您的 fc1 层需要一个形状为(-1, 7*7*64)的张量,但您传递给它的是一个形状为[-1, 246016]的张量( -1是批量大小)。

要计算卷积网络的 output 大小,请参阅这篇文章或任何神经网络教科书。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM