[英]How can i solve the Input Size Error with Conv2d?
RuntimeError:预期 3D(未批处理)或 4D(批处理)输入到 conv2d,但得到大小输入:[16, 1280] 即使我的 inputs.shape 是 torch.Size([16, 3, 120, 120])
嘿,我是 pytorch 的新用户,所以请不要对我太苛刻。
我正在尝试训练以下 model 将图像分类为 12 个标签:
model = models.efficientnet_b1(weights='DEFAULT').to(device) # put it to GPU
model.classifier = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=32, kernel_size=3, stride=1, padding=1),
nn.ReLU(inplace=True),
nn.MaxPool2d(kernel_size=2, stride=2),
nn.Flatten(),
nn.Linear(32*16*16, 128),
nn.ReLU(inplace=True),
nn.Linear(128, 12)
).to(device)
for param in model.parameters():
param.requires_grad = False
optimizer = torch.optim.AdamW(model.classifier.parameters(), lr=5e-4, weight_decay=0.1)
并像这样训练它:
# Define the loss function and the optimizer
criterion = nn.CrossEntropyLoss()
# Define the number of training epochs
num_epochs = 10
# Training loop
for epoch in range(num_epochs):
# Set the model to train mode
model.train()
# Initialize the running loss for this epoch
running_loss = 0.0
# Iterate over the training data
for i, data in enumerate(train_loader):
inputs, labels = data
inputs, labels = inputs.to(device), labels.to(device)
# Zero the gradients
optimizer.zero_grad()
# Forward pass
print(inputs.shape) // Print: torch.Size([16, 3, 120, 120])
outputs = model(inputs) //Error
loss = criterion(outputs, labels)
# Backward pass and optimization
loss.backward()
optimizer.step()
# Update the running loss
running_loss += loss.item()
我的问题是,我收到错误:RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [16, 1280] 我不明白为什么会收到此错误,因为输入大小是 [16, 3, 120, 120](如印刷)
非常感谢您的帮助!
您正在用自己的模块替换model.classifier
。 问题是原始模块需要一个形式为 = (batch, 1280) 的输入,而您正在用一个需要形式为 (batch, channels, height, width) 输入的模块替换它。 你可以这样做:
net.classifier = nn.Sequential(
nn.Dropout()
nn.Linear(1280, 12)
)
这只是一个工作示例,我不知道您要做什么! 我想你想要 output 等于 12
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.