pythorch建立一个LSTM模型,预测14日后的股票价格
时间: 2024-04-10 07:34:30 浏览: 94
Sure! Here's an example of how you can build an LSTM model in PyTorch to predict stock prices 14 days into the future:
```python
import torch
import torch.nn as nn
class LSTMNet(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTMNet, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size, batch_first=True)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
out, _ = self.lstm(x)
out = self.fc(out[:, -1, :])
return out
# Define the hyperparameters
input_size = 1 # Number of features in the input
hidden_size = 64 # Number of hidden units in the LSTM layer
output_size = 1 # Number of output predictions
# Create an instance of the LSTM model
model = LSTMNet(input_size, hidden_size, output_size)
# Define the loss function and optimizer
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Training loop
for epoch in range(num_epochs):
# Forward pass
outputs = model(inputs)
loss = criterion(outputs, targets)
# Backward and optimize
optimizer.zero_grad()
loss.backward()
optimizer.step()
# Print the loss at every epoch
print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}')
# Predict future stock prices
future_inputs = ... # Prepare future inputs (shape: [batch_size, 14, input_size])
predicted_prices = model(future_inputs)
```
Note that you need to prepare your training data (`inputs` and `targets`) and future inputs (`future_inputs`) according to your dataset. Also, make sure to adjust the hyperparameters (e.g., `hidden_size`, `num_epochs`, learning rate) based on your specific task and data.
阅读全文