簡體   English   中英

RuntimeError: mat1 和 mat2 形狀不能相乘(4x73034 和 200x120)

[英]RuntimeError: mat1 and mat2 shapes cannot be multiplied (4x73034 and 200x120)

為皮膚檢測數據集構建神經網絡層,這里出錯了。 我知道我犯了一些錯誤,但無法弄清楚。 獲取圖像尺寸 224*224 和通道 3 后出現錯誤: RuntimeError: mat1 and mat2 形狀不能相乘(4x73034 和 200x120)

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
  def __init__(self):
    super(Net, self).__init__()
    self.conv1 = nn.Conv2d(3, 16, 5)
    self.pool = nn.MaxPool2d(2, 2)
    self.conv2 = nn.Conv2d(16, 26, 5)
    self.fc1 = nn.Linear(8 * 5 * 5, 120)
    self.fc2 = nn.Linear(120, 86)
    self.fc3 = nn.Linear(86, 2)

  def forward(self, x):
    x = self.pool(F.relu(self.conv1(x)))
    x = self.pool(F.relu(self.conv2(x)))
    x = torch.flatten(x,1)
    x = F.relu(self.fc1(x))
    x = F.relu(self.fc2(x))
    x = self.fc3(x)
    return x

net = Net().to(device)
print(net)

這些是層和網絡模塊

<ipython-input-41-8c9bafb31c44> in forward(self, x)
     16     x = self.pool(F.relu(self.conv2(x)))
     17     x = torch.flatten(x,1)
---> 18     x = F.relu(self.fc1(x))
     19     x = F.relu(self.fc2(x))
     20     x = self.fc3(x)

誰能幫我解決這個問題。

您在 torch.flatten 的 output 和 self.fc1 的輸入之間存在不匹配

打印torch.flatten的torch.flatten的形狀

x = torch.flatten(x,1)
print(x.size())

並隨后更新self.fc1的定義

self.fc1 = nn.Linear(8 * 5 * 5, 120)

正如Anant所說,您需要將展平的 conv2 維度(73034)匹配為 fc1 層的輸入維度。

self.fc1 = nn.Linear(73034, 120)

每個conv層的output計算公式:

[(height or width) - kernel size + 2*padding] / stride + 1

對於以下內容,我將使用尺寸(通道、高度、寬度)輸入 (3,224,224) -> conv1 -> (16,220,220) -> pool -> (16,110,110) -> conv2 -> (26,106,106) -> pool -> (26 ,53,53) -> 展平 -> (73034)

看來您的批量大小是 4。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM