【问题标题】:Pytorch LSTM Prediction not learningPytorch LSTM 预测不学习
【发布时间】:2021-07-19 17:06:26
【问题描述】:

我正在使用 LSTM 模型使用以下数据集预测 BABA 股票价格:“/kaggle/input/price-volume-data-for-all-us-stocks-etfs/Data/Stocks/baba.us.txt ”。

我不确定为什么我的模型没有学习并且 y_test_prediction 与实际的 y_test 如此不同。在我开始学习机器学习时,我非常感谢您的帮助。谢谢!

在拆分数据之前,我已经使用 minMaxScaler 对数据进行了缩放。这就是我拆分数据的方式:

x_train, y_train, x_test, y_test = [], [], [], []
lags = 3

for t in range(len(train_data)-lags-1):
    x_train.append(train_data[t:(t+lags),:])
    y_train.append(train_data[(t+lags),:])

for t in range(len(test_data)-lags-1):
    x_test.append(test_data[t:(t+lags),:])
    y_test.append(test_data[(t+lags),:])    
    
x_train = torch.FloatTensor(np.array(x_train))
y_train = torch.FloatTensor(np.array(y_train))
x_test = torch.FloatTensor(np.array(x_test))
y_test = torch.FloatTensor(np.array(y_test))

x_train = np.reshape(x_train,(x_train.shape[0],x_train.shape[1],1))
x_test = np.reshape(x_test,(x_test.shape[0],x_test.shape[1],1))

print(x_train.shape)
print(y_train.shape)
print(x_test.shape)
print(y_test.shape)

这是我的 LSTM 模型:

input_dim = 1
hidden_layer_dim = 32
num_layers = 1
output_dim = 1


class LSTM(nn.Module):
    def __init__(self, input_dim,hidden_layer_dim, num_layers, output_dim ):
        super(LSTM, self).__init__()
        
        self.input_dim = input_dim
        self.hidden_layer_dim = hidden_layer_dim
        self.num_layers = num_layers
        self.output_dim = output_dim
        
        self.lstm = nn.LSTM(input_dim, hidden_layer_dim,num_layers,batch_first = True)
        self.fc = nn.Linear(hidden_layer_dim, output_dim)
        
    def forward(self, x):
        # initial hidden state & cell state as zeros
        h0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_layer_dim))
        c0 = Variable(torch.zeros(self.num_layers, x.size(0), self.hidden_layer_dim))

        # lstm output with hidden and cell state
        output, (hn, cn) = self.lstm(x, (h0,c0))
        # get hidden state to be passed to dense layer
        hn = hn.view(-1, self.hidden_layer_dim)
        output = self.fc(hn)

        return output

这是我的训练:

num_epochs = 100
learning_rate = 0.01

model = LSTM(input_dim,hidden_layer_dim, num_layers, output_dim)

loss = torch.nn.MSELoss()    # mean-squared error for regression
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)
hist = np.zeros(num_epochs)

# train model
for epoch in range(num_epochs):
    outputs = model(x_train)
    optimizer.zero_grad()
    
    #get loss function
 
    loss_fn = loss(outputs, y_train.view(1,-1))
    hist[epoch] = loss_fn.item()
    
    loss_fn.backward()
    optimizer.step()
    
    if epoch %10==0:
        print("Epoch: %d, loss: %1.5f" % (epoch, hist[epoch]))
        

这是训练损失和预测与实际的对比

training loss

prediction vs actual

【问题讨论】:

  • 您的训练损失如何?
  • 对于初学者来说,分享这些步骤的损失曲线。您正在检查超过 10 个时期的损失,这对于调试来说肯定太多了。在调试时,您应该在步骤上的曲线,甚至不是时代。
  • 我已经添加了训练损失和预测与实际的图表。感谢您的帮助!
  • 你输入的数据形状是否正确?...因为如果batch_first=False,那么形状应该是(seq_length, batch_size, hidden_​​size)形式

标签: machine-learning pytorch lstm prediction


【解决方案1】:

每次调用 forward 时都在初始化隐藏层,这可能会导致反向传播错误。您甚至不必初始化它们。 PyTorch 会为您解决这个问题。您可以查看this 实现以了解详细信息。另外,作为旁注,您可能想看看 PyTorch 数据加载器(只是一种更简单的拆分方法)。

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 1970-01-01
    • 2020-09-28
    • 2021-04-15
    • 2023-04-08
    相关资源
    最近更新 更多