PyTorch LSTM 模型参数定义与常见错误解决
定义模型参数
input_size = X_new.shape[1]
hidden_size = len(X_new)
num_layers = 2
output_size = 1
batch_size = 1
# 定义LSTM模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, num_layers, output_size, batch_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.num_layers = num_layers
self.batch_size = batch_size
self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
batch_size = self.batch_size # 获取输入数据的batch_size
h0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).cuda()
c0 = torch.zeros(self.num_layers, batch_size, self.hidden_size).cuda()
x = x.unsqueeze(0)
out, _ = self.lstm(x, (h0, c0))
out = out.squeeze(0)
out = self.fc(out[:, -1, :])
return out
常见错误解决
UserWarning: Using a target size (torch.Size([3090])) that is different to the input size (torch.Size([1])). This will likely lead to incorrect results due to broadcasting. Please ensure they have the same size.
这个警告提示我们,在输入数据和目标数据的大小上存在不匹配。具体来说,在模型的输出层中,我们将hidden state作为输入,然后将其压缩到output size维度。因此,我们需要确保目标数据的大小与output size相同。在这里,我们可以将目标数据调整为一个1维张量,大小为[batch_size],其中batch_size为1。可以使用以下代码解决这个问题:
target = torch.tensor(y_new).view(-1) # 将target调整为1维张量
原文地址: https://www.cveoy.top/t/topic/lDgL 著作权归作者所有。请勿转载和采集!