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
df = pd.read_csv(‘data.csv’) # Replace ‘data.csv’ with your dataset path
data = df[‘CLOSE’].values.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
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)
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)
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)
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)
])
model.compile(optimizer=’adam’, loss=’mean_squared_error’)
model.fit(X_train, y_train, batch_size=1, epochs=1)
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
train_predict = scaler.inverse_transform(train_predict)
test_predict = scaler.inverse_transform(test_predict)
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
You need to login in order to like this post: click here
YOU MIGHT ALSO LIKE