报错:UserWarning: Using a target size (torch.Size([15])) that is different to the input size

报错:UserWarning: Using a target size (torch.Size([15])) that is different to the input size (torch.Size([15, 1])).
问题:训练模型时遇到以下报错
报错:UserWarning: Using a target size (torch.Size([15])) that is different to the input size_第1张图片
解决方法:
在forward(self, x)函数体中,在return x之前,加一句
x = x.squeeze(-1)
以达到降低一维的目的;

def forward(self, x):
        H,(h,c) = self.lstm(x.float(),None) #编码
        h=h.squeeze(0)
        c=c.squeeze(0)
        H_pre=torch.empty((h.shape[0],1,128*2)).to(device)
        for i in range(1): #解码
            h_t, c_t = self.lstmcell(h, (h, c))  # 预测
            H=torch.cat((H,h_t.unsqueeze(1)),1)
            h_atten=self.Atten(H) #获取结合了注意力的隐状态
            H_pre[:,i,:]=h_atten  #记录解码器每一步的隐状态
            h, c = h_t, c_t  # 将当前的隐状态与细胞状态记录用于下一个时间步
        out = self.fc2(self.fc1(H_pre)).squeeze(2)
 
        return out.squeeze(-1)

你可能感兴趣的:(Debug,python,机器学习,数据挖掘,jupyter)