我正在尝试构建 CNN,但出现此错误:
---> 52 x = x.view(x.size(0), 5 * 5 * 16)
RuntimeError: shape '[16, 400]' is invalid for input of size 9600
我不清楚“x.view”行的输入应该是什么。另外,我真的不明白我的代码中应该有多少次这个“x.view”函数。是不是只有一次,在 3 个卷积层和 2 个线性层之后?还是5次,每层一次?
这是我的 CNN 代码:
import torch.nn.functional as F
# Convolutional neural network
class ConvNet(nn.Module):
def __init__(self, num_classes=10):
super(ConvNet, self).__init__()
self.conv1 = nn.Conv2d(
in_channels=3,
out_channels=16,
kernel_size=3)
self.conv2 = nn.Conv2d(
in_channels=16,
out_channels=24,
kernel_size=4)
self.conv3 = nn.Conv2d(
in_channels=24,
out_channels=32,
kernel_size=4)
self.dropout = nn.Dropout2d(p=0.3)
self.pool = nn.MaxPool2d(2)
self.fc1 = nn.Linear(16 * 5 * 5, 120)
self.fc2 = nn.Linear(512, 10)
self.final = nn.Softmax(dim=1)
def forward(self, x):
print('shape 0 ' + str(x.shape))
x = F.max_pool2d(F.relu(self.conv1(x)), 2)
x = self.dropout(x)
print('shape 1 ' + str(x.shape))
x = F.max_pool2d(F.relu(self.conv2(x)), 2)
x = self.dropout(x)
print('shape 2 ' + str(x.shape))
# x = F.max_pool2d(F.relu(self.conv3(x)), 2)
# x = self.dropout(x)
x = F.interpolate(x, size=(5, 5))
x = x.view(x.size(0), 5 * 5 * 16)
x = self.fc1(x)
return x
net = ConvNet()
有人可以帮助我理解这个问题吗?
x.shape
的输出为:
形状 0 火炬.Size([16, 3, 256, 256])
形状 1 火炬.Size([16, 16, 127, 127])
形状 2 火炬.Size([16, 24, 62, 62])
谢谢。
这意味着通道和空间维度的乘积不是
5*5*16
。要展平张量,请将 x = x.view(x.size(0), 5 * 5 * 16)
替换为:
x = x.view(x.size(0), -1)
我在下面遇到了同样的错误:
运行时错误:形状“[3, 3]”对于大小 6 的输入无效
当我尝试使用
view()与
2x3(6)
重塑 3x3(9)
的张量时,如下所示:
import torch
my_tensor = torch.tensor([[0, 1, 2], [3, 4, 5]])
my_tensor.view(3, 3) # Error
所以,我用
2x3(6)
、1x6(6)
、2x3(6)
或3x2(6)
用6x1(6)
重塑view()
的张量,然后我可以得到如下所示的结果。 *重塑张量的元素总数必须与原始张量匹配:
import torch
my_tensor = torch.tensor([[0, 1, 2], [3, 4, 5]])
my_tensor.view(1, 6) # tensor([[0, 1, 2, 3, 4, 5]])
my_tensor.view(2, 3) # tensor([[0, 1, 2], [3, 4, 5]])
my_tensor.view(3, 2) # tensor([[0, 1], [2, 3], [4, 5]])
my_tensor.view(6, 1) # tensor([[0], [1], [2], [3], [4], [5]])