问题描述
我正在尝试使用批量标准化实现 Conv1d
层,但我不断收到以下错误:
RuntimeError Traceback (most recent call last)
<ipython-input-32-ef6e122ea50c> in <module>()
----> 1 test()
2 for epoch in range(1,n_epochs + 1):
3 train(epoch)
4 test()
7 frames
/usr/local/lib/python3.7/dist-packages/torch/nn/modules/conv.py in _conv_forward(self,input,weight,bias)
258 _single(0),self.dilation,self.groups)
259 return F.conv1d(input,bias,self.stride,--> 260 self.padding,self.groups)
261
262 def forward(self,input: Tensor) -> Tensor:
RuntimeError: Expected 3-dimensional input for 3-dimensional weight [25,40,5],but got 2-dimensional input of size [32,40] instead
使用 DataLoader 类以 32 个批次传递数据,它有 40 个特征和 10 个标签。这是我的模型:
class MyModel(nn.Module):
def __init__(self):
super(MyModel,self).__init__()
#self.flatten=nn.Flatten()
self.net_stack=nn.Sequential(
nn.Conv1d(in_channels=40,out_channels=25,kernel_size=5,stride=2),#applying batch norm
nn.ReLU(),nn.Batchnorm1d(25,affine=True),nn.Conv1d(in_channels=25,out_channels=20,nn.Batchnorm1d(20,nn.Linear(20,10),nn.softmax(dim=1))
def forward(self,x):
#x=torch.reshape(x,(1,-1))
result=self.net_stack(x)
return result
我已经尝试在其他答案中给出,例如解压输入张量,但是这些问题中的模型都没有使用带有 batchnorm1d 的 Conv1d,因此我无法将问题缩小到必须导致错误的层。我刚刚开始使用 Pytorch,并且能够实现一个简单的线性 NN 模型,但是在对相同数据使用卷积 NN 时遇到了这个错误。
解决方法
您需要为输入添加批处理维度(并更改输入通道的数量)。
conv1d
层接受形状为 [B,C,L]
的输入,其中 B
是批量大小,C
是通道数,L
是宽度/输入的长度。此外,您的 conv1d
层需要 40 个输入通道:
nn.Conv1d(in_channels=40,out_channels=25,kernel_size=5,stride=2)
因此,您的输入张量 x
必须具有 [B,40,L]
形状,而现在它具有 [32,40]
形状。
试试:
def forward(self,x):
result=self.net_stack(x[None])
return result
您将收到另一个错误,抱怨维度不匹配,建议您将输入通道数更改为 40。