Get in touch
or send us a question?
CONTACT

Using LSTM to train model (2)

import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
import matplotlib.pyplot as plt

Load the dataset

df = pd.read_csv(‘data.csv’) # Replace ‘data.csv’ with your dataset path
data = df[‘CLOSE’].values.reshape(-1, 1)

Normalize the data

scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)

Function to create sequences

def create_dataset(dataset, time_step=60):
X, y = [], []
for i in range(len(dataset) – time_step):
X.append(dataset[i:i + time_step, 0])
y.append(dataset[i + time_step, 0])
return np.array(X), np.array(y)

Split data into training and testing sets

train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size]
test_data = scaled_data[train_size:]

time_step = 60
X_train, y_train = create_dataset(train_data, time_step)
X_test, y_test = create_dataset(test_data, time_step)

Reshape data into [samples, time steps, features]

X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)

Build LSTM model

model = Sequential([
LSTM(50, return_sequences=True, input_shape=(X_train.shape[1], 1)),
Dropout(0.2),
LSTM(50, return_sequences=False),
Dropout(0.2),
Dense(25),
Dense(1)
])

Compile and train the model

model.compile(optimizer=’adam’, loss=’mean_squared_error’)
model.fit(X_train, y_train, batch_size=1, epochs=1)

Make predictions

train_predict = model.predict(X_train)
test_predict = model.predict(X_test)

Inverse transform predictions to original scale

train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict)

Visualize results

plt.figure(figsize=(16, 8))
plt.plot(data, label=’Original Data’)
plt.plot(range(time_step, time_step + len(train_predict)), train_predict, label=’Train Predictions’)
plt.plot(range(time_step + len(train_predict), len(data)), test_predict, label=’Test Predictions’)
plt.legend()
plt.show()

Source: Copilot