Apologies for the confusion. Since the code I provided assumes you have a separate transformer_models.py file where you define the transformer model architecture, let's modify the code to define the transformer model directly in the main script. Here's the modified code:
import pandas as pd
import yahoo_fin.stock_info as si
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
import torch
import torch.nn as nn
import torch.optim as optim
import numpy as np
import matplotlib.pyplot as plt
# Define the Transformer model
class TransAm(nn.Module):
def __init__(self, input_dim, output_dim):
super(TransAm, self).__init__()
self.encoder = nn.TransformerEncoderLayer(d_model=input_dim, nhead=4)
self.fc = nn.Linear(input_dim, output_dim)
def forward(self, x):
x = self.encoder(x)
x = x[:, -1, :] # Only take the last sequence element
x = self.fc(x)
return x
# Get Apple stock data from Yahoo Finance
df = si.get_data('AAPL')
# Preprocess the data
scaler = MinMaxScaler()
scaled_data = scaler.fit_transform(df['adjclose'].values.reshape(-1, 1))
# Split the data into train and test sets
train_size = int(len(scaled_data) * 0.8)
test_size = len(scaled_data) - train_size
train_data, test_data = scaled_data[:train_size], scaled_data[train_size:]
# Split train and test data into input and output
def create_dataset(data, look_back=1):
X, Y = [], []
for i in range(len(data)-look_back-1):
X.append(data[i:(i+look_back), 0])
Y.append(data[(i+look_back), 0])
return np.array(X), np.array(Y)
look_back = 20
trainX, trainY = create_dataset(train_data, look_back)
testX, testY = create_dataset(test_data, look_back)
# Convert the data to PyTorch tensors
trainX = torch.from_numpy(trainX).float()
trainY = torch.from_numpy(trainY).float()
testX = torch.from_numpy(testX).float()
testY = torch.from_numpy(testY).float()
# Define the transformer model
model = TransAm(input_dim=look_back, output_dim=1)
# Set the loss function and optimizer
criterion = nn.MSELoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# Train the model
num_epochs = 100
for epoch in range(num_epochs):
model.train()
optimizer.zero_grad()
output = model(trainX.unsqueeze(2))
loss = criterion(output.squeeze(), trainY)
loss.backward()
optimizer.step()
if (epoch+1) % 10 == 0:
print(f'Epoch: {epoch+1}/{num_epochs}, Loss: {loss.item()}')
# Evaluate the model
model.eval()
with torch.no_grad():
train_prediction = model(trainX.unsqueeze(2)).squeeze().detach().numpy()
test_prediction = model(testX.unsqueeze(2)).squeeze().detach().numpy()
train_mse = mean_squared_error(trainY, train_prediction)
test_mse = mean_squared_error(testY, test_prediction)
print(f'Train MSE: {train_mse}, Test MSE: {test_mse}')
# Invert the scaling of the predictions
train_prediction = scaler.inverse_transform(train_prediction.reshape(-1, 1))
test_prediction = scaler.inverse_transform(test_prediction.reshape(-1, 1))
# Plot the predictions
plt.plot(df.index[look_back+1:train_size+look_back+1], train_data[look_back+1:], label='Actual Train')
plt.plot(df.index[train_size+look_back+1:], test_data[look_back+1:], label='Actual Test')
plt.plot(df.index[look_back+1:train_size+look_back+1], train_prediction, label='Train Predict')
plt.plot(df.index[train_size+look_back+1:], test_prediction, label='Test Predict')
plt.xlabel('Date')
plt.ylabel('Stock Price')
plt.title('Apple Stock Price Prediction')
plt.legend()
plt.show()
In this modified code, the TransAm class is defined within the main script, removing the dependency on a separate transformer_models.py file. The rest of the code remains mostly the same, with some modifications to handle the input and output dimensions and squeeze the dimensions before inverting the scaling and plotting the predictions.
Please make sure you have the necessary libraries installed (yahoo_fin, torch, sklearn, pandas, numpy, matplotlib). Let me know if you encounter any further issues!