【发布时间】:2018-12-13 20:56:08
【问题描述】:
This code 我发现有一个神经网络可以拍摄黑白图像。 (这是一个连体网络,但那部分不相关)。当我将其更改为拍摄我的图像而不是将它们转换为黑白时,我收到如下所示的错误。
我尝试将第一个 Conv2d,第六行从 1 更改为 3
class SiameseNetwork(nn.Module):
def __init__(self):
super(SiameseNetwork, self).__init__()
self.cnn1 = nn.Sequential(
nn.ReflectionPad2d(1),
# was nn.Conv2d(1, 4, kernel_size=3),
nn.Conv2d(3, 4, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(4),
nn.ReflectionPad2d(1),
nn.Conv2d(4, 8, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(8),
nn.ReflectionPad2d(1),
nn.Conv2d(8, 8, kernel_size=3),
nn.ReLU(inplace=True),
nn.BatchNorm2d(8))
self.fc1 = nn.Sequential(
nn.Linear(8*300*300, 500),
nn.ReLU(inplace=True),
nn.Linear(500, 500),
nn.ReLU(inplace=True),
nn.Linear(500, 5))
def forward_once(self, x):
output = self.cnn1(x)
output = output.view(output.size()[0], -1)
output = self.fc1(output)
return output
def forward(self, input1, input2):
output1 = self.forward_once(input1)
output2 = self.forward_once(input2)
return output1, output2
当图像未转换为黑白并保持彩色时,我的错误。
RuntimeError: invalid argument 0: Sizes of tensors must match
except in dimension 0. Got 3 and 1 in dimension 1 at
/opt/conda/conda-bld/pytorch-nightly_1542963753679/work/aten/src/TH/generic/THTensorMoreMath.cpp:1319
我将图像的形状作为数组(在它们进入模型之前)检查为黑白与彩色......
黑白
torch.Size([1, 1, 300, 300])
彩色
torch.Size([1, 3, 300, 300])
这是我正在使用的整个原始代码的 Jupyter Notebook 的链接...https://github.com/harveyslash/Facial-Similarity-with-Siamese-Networks-in-Pytorch/blob/master/Siamese-networks-medium.ipynb
编辑:更新:我似乎已经通过在代码的 SiameseNetworkDataset 部分将图像转换为 RBG 来解决它
img0 = img0.convert("L")
改为
img0 = img0.convert("RGB")
我之前刚刚注释掉了该行,并认为这会将其留在 RGB 中,但这是模型无法理解的其他内容。 此外,还需要对 OP 进行更改。
nn.Conv2d(1, 4, kernel_size=3),
改为
nn.Conv2d(3, 4, kernel_size=3),
如果您想通过解释模型正在做什么来明确回答,我会给您绿色检查。不是很懂nn.Conv2d
【问题讨论】:
标签: python image conv-neural-network pytorch