Load the data
data = pd.read_csv('data.csv', usecols=[1])
Convert the data to a numpy array
dataset = data.values
Scale the data
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
Define the number of time steps and features
time_steps = 60
features = 1
Create the input data
x_train = []
y_train = []
for i in range(time_steps, len(dataset)):
x_train.append(scaled_data[i-time_steps:i, 0])
y_train.append(scaled_data[i, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
Reshape the input data
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], features))
Define the model
model = Sequential([
LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], features)),
Dropout(0.2),
LSTM(units=50, return_sequences=True),
Dropout(0.2),
LSTM(units=50, return_sequences=True),
Dropout(0.2),
LSTM(units=50),
Dropout(0.2),
Dense(units=1)
])
Compile the model
model.compile(optimizer='adam', loss='mean_squared_error')
Train the model
model.fit(x_train, y_train, epochs=50, batch_size=32)
Create the test data
test_data = scaled_data[len(scaled_data)-time_steps:]
x_test = []
for i in range(time_steps, len(test_data)):
x_test.append(test_data[i-time_steps:i, 0])
x_test = np.array(x_test)
Reshape the test data
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], features))
Use the model to make predictions
predictions = model.predict(x_test)
Unscale the data
predictions = scaler.inverse_transform(predictions)
Plot the predictions
plt.figure(figsize=(10,6))
plt.plot(data[len(data)-len(predictions):].index, predictions, color='red', label='Predicted Price')
plt.plot(data[len(data)-len(predictions):].index, data[len(data)-len(predictions):], color='blue', label='Actual Price')
plt.title('Price Prediction')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()
plt.show()