這可能是一個愚蠢的問題,但我想在我的深度強化學習專案中使用卷積神經網路,但遇到了一個我不明白的問題。在我的專案中,我想插入6x7應該相當于 6x7 大小(42 像素)的黑白圖片的網路矩陣,對嗎?
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.model = torch.nn.Sequential()
self.model.add_module("conv_1", torch.nn.Conv2d(in_channels=1, out_channels=16, kernel_size=4, stride = 1))
self.model.add_module("relu_1", torch.nn.ReLU())
self.model.add_module("max_pool", torch.nn.MaxPool2d(2))
self.model.add_module("conv_2", torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=4, stride = 1))
self.model.add_module("relu_2", torch.nn.ReLU())
self.model.add_module("flatten", torch.nn.Flatten())
self.model.add_module("linear", torch.nn.Linear(in_features=16*16*16, out_features=7))
def forward(self, x):
x = self.model(x)
return x
因為conv1 in_channels=1我只有 1 個矩陣(如果是影像識別,則意味著 1 種顏色)。其他in_channels和out_channels是隨機的,直到linear。我不知道應該在哪里插入矩陣的大小,但最終輸出應該是7我輸入的大小linear。
我得到的錯誤是:
RuntimeError: Expected 3D (unbatched) or 4D (batched) input to conv2d, but got input of size: [6, 7]
uj5u.com熱心網友回復:
您的代碼存在一些問題。首先,您收到該錯誤訊息的原因是因為 CNN 需要一個帶有 shape 的張量(N, Cin, Hin, Win),其中:
N是批量大小Cin是輸入通道數Hin是輸入影像像素高度Win是輸入影像像素寬度
您只提供width和height尺寸。您需要顯式添加一個channels和batch維度,即使這些維度的值僅為1:
model = CNN()
example_input = torch.randn(size=(6, 7)) # this is your input image
print(example_input.shape) # should be (6, 7)
output = model(example_input) # you original error
example_input = example_input.unsqueeze(0).unsqueeze(0) # adds batch and channels dimension
print(example_input.shape) # should now be (1, 1, 6, 7)
output = model(example_input) # no more error!
但是,您會注意到,您現在得到了一個不同的錯誤:
RuntimeError: Calculated padded input size per channel: (1 x 2). Kernel size: (4 x 4). Kernel size can't be greater than actual input size
這是因為在第一個 conv 層之后,您的資料是 shape 1x2,但您的第二層的內核大小是4,這使得操作無法進行。大小的輸入影像6x7非常小,要么將內核大小減小到可行的程度,要么使用更大的影像。
這是一個作業示例:
import torch
from torch import nn
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.model = torch.nn.Sequential()
self.model.add_module(
"conv_1",
torch.nn.Conv2d(in_channels=1, out_channels=16, kernel_size=2, stride=1),
)
self.model.add_module("relu_1", torch.nn.ReLU())
self.model.add_module("max_pool", torch.nn.MaxPool2d(2))
self.model.add_module(
"conv_2",
torch.nn.Conv2d(in_channels=16, out_channels=16, kernel_size=2, stride=1),
)
self.model.add_module("relu_2", torch.nn.ReLU())
self.model.add_module("flatten", torch.nn.Flatten())
self.model.add_module("linear", torch.nn.Linear(in_features=32, out_features=7))
def forward(self, x):
x = self.model(x)
return x
model = CNN()
x = torch.randn(size=(6, 7))
x = x.unsqueeze(0).unsqueeze(0)
output = model(x)
print(output.shape) # has shape (1, 7)
請注意,我將 更改kernel_size為 2,最終線性層的輸入大小為32. 此外,輸出具有 shape (1, 7),1 是 batch_size,在我們的例子中只有 1。如果您只想要 7 個輸出特征,只需使用x = torch.squeeze(x)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/479920.html
