TensorFlowClass / pages /19_RNN.py
eaglelandsonce's picture
Create 19_RNN.py
5c4e96f verified
raw
history blame
2.34 kB
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers, models
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
# Load the dataset
data_url = 'https://raw.githubusercontent.com/selva86/datasets/master/aapl.csv'
df = pd.read_csv(data_url)
df = df[['Date', 'Close']]
df['Date'] = pd.to_datetime(df['Date'])
df.set_index('Date', inplace=True)
# Normalize the data
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df)
# Create sequences
def create_sequences(data, seq_length):
xs = []
ys = []
for i in range(len(data) - seq_length):
x = data[i:i + seq_length]
y = data[i + seq_length]
xs.append(x)
ys.append(y)
return np.array(xs), np.array(ys)
seq_length = 60
X, y = create_sequences(scaled_data, seq_length)
# Split the data into training and testing sets
split = int(0.8 * len(X))
X_train, X_test = X[:split], X[split:]
y_train, y_test = y[:split], y[split:]
# Reshape data for the model
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))
# Build the RNN model
model = models.Sequential()
model.add(layers.LSTM(50, return_sequences=True, input_shape=(seq_length, 1)))
model.add(layers.LSTM(50, return_sequences=False))
model.add(layers.Dense(25))
model.add(layers.Dense(1))
model.summary()
# Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
# Train the model
history = model.fit(X_train, y_train, batch_size=32, epochs=20, validation_split=0.1)
# Make predictions
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# Inverse transform the predictions
train_predict = scaler.inverse_transform(train_predict)
y_train = scaler.inverse_transform(y_train.reshape(-1, 1))
test_predict = scaler.inverse_transform(test_predict)
y_test = scaler.inverse_transform(y_test.reshape(-1, 1))
# Plot the results
plt.figure(figsize=(14, 5))
plt.plot(df.index, df['Close'], label='True Price')
plt.plot(df.index[seq_length:seq_length + len(train_predict)], train_predict, label='Train Predict')
plt.plot(df.index[seq_length + len(train_predict):], test_predict, label='Test Predict')
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.legend()
plt.show()