【发布时间】:2020-11-24 00:40:08
【问题描述】:
我正在尝试创建一个用于批量图像的简单线性回归神经网络。输入维度为[BatchSize, 3, Width, Height],第二个维度表示输入图像的RGB通道。
这是我对该回归模型的(失败的)尝试:
class LinearNet(torch.nn.Module):
def __init__(self, Chn, W,H, nHidden):
"""
Input: A [BatchSize x Channels x Width x Height] set of images
Output: A fitted regression model with weights dimension : [Width x Height]
"""
super(LinearNet, self).__init__()
self.Chn = Chn
self.W = W
self.H = H
self.hidden = torch.nn.Linear(Chn*W*H,nHidden) # hidden layer
self.predict = torch.nn.Linear(nHidden, Chn*W*H) # output layer
def forward(self, x):
torch.reshape(x, (-1,self.Chn*self.W*self.H)) # FAILS here
# x = x.resize(-1,self.Chn*self.W*self.H)
x = F.relu(self.hidden(x)) # activation function for hidden layer
x = self.predict(x) # linear output
x = x.resize(-1,self.Chn, self.W,self.H)
return x
当发送一批尺寸为[128 x 3 x 96 x 128] 的图像时,在指示的行上失败:
RuntimeError: mat1 and mat2 shapes cannot be multiplied (36864x128 and 36864x256)
如何正确操作矩阵维度以使用这些 pytorch 函数?
更新基于(已删除)评论,我已更新代码以使用torch.reshape。
【问题讨论】:
-
错误是说您的 x 的大小为
128x3x96x128并且它具有4718592元素,但是,您试图将其仅转换为36864元素。你错过了*128。