image_output_1.png
from dateutil.relativedelta import relativedelta

from keras.layers.core import Dense

from keras.layers.recurrent import LSTM

from keras.models import Sequential

from sklearn.preprocessing import MinMaxScaler

import datetime

import matplotlib.pyplot as plt

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

data = pd.read_csv('/kaggle/input/hourly-energy-consumption/AEP_hourly.csv')

from sklearn.preprocessing import MinMaxScaler
from dateutil.relativedelta import relativedelta
import datetime
data = data.sort_values(by=['Datetime'])
data['Datetime'] = data['Datetime'].astype('datetime64')
data = data.loc[data['Datetime'] >= data['Datetime'][len(data['Datetime']) - 1] - relativedelta(years=3)]
data.reset_index(inplace=True)
scaler = MinMaxScaler()
consumption = scaler.fit_transform(np.reshape(data['AEP_MW'].values, (-1, 1)))[:, 0]

ratio = 0.8
split = int(np.floor(ratio * len(data)))
input_length = 20
x_train = [consumption[i - input_length:i] for i in range(input_length, split)]
x_test = [consumption[i - input_length:i] for i in range(input_length + split, len(consumption))]
y_train = consumption[input_length:split]
y_test = consumption[input_length + split:]
x_train_lstm = np.reshape(x_train, (np.shape(x_train)[0], np.shape(x_train)[1], 1))
x_test_lstm = np.reshape(x_test, (np.shape(x_test)[0], np.shape(x_test)[1], 1))

from keras.models import Sequential
from keras.layers.recurrent import LSTM
from keras.layers.core import Dense
lstm = Sequential()
layers = [LSTM(units=128, input_shape=(input_length, 1), activation='sigmoid', return_sequences=True), LSTM(units=128, activation='sigmoid'), Dense(1)]
for layer in layers:
    lstm.add(layer)
lstm.compile(loss='mean_squared_error', optimizer='adam', metrics=['accuracy'])
history_lstm = lstm.fit(x_train_lstm, y_train, validation_data=(x_test_lstm, y_test), epochs=3, batch_size=32)

import matplotlib.pyplot as plt

predictions = lstm.predict(x_test_lstm)
first_date = data['Datetime'][len(data) - len(y_test)]
predicted_dates = [first_date + datetime.timedelta(hours=i) for i in range(len(x_test))]
plt.figure()
plt.plot(data['Datetime'], scaler.inverse_transform(np.reshape(consumption, (-1, 1))), color='b', alpha=0.7)
plt.plot(predicted_dates, scaler.inverse_transform(np.reshape(predictions, (-1, 1))), color='r', alpha=0.4)
plt.xlabel('Datetime')
plt.ylabel('Energy consumption in MegaWatt')
plt.title('American energy consumption evolution over time')
plt.legend(['true data', 'prediction'])
plt.show()