text_html_output_1.png
from keras.layers import LSTM, Dense

from keras.models import Sequential

from sklearn.preprocessing import MinMaxScaler

from statsmodels.tsa.seasonal import seasonal_decompose

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import numpy as np

import numpy as np

import pandas as pd

import pandas as pd

class Logger:
    RESET = '\x1b[0m'
    RED = '\x1b[31m'
    GREEN = '\x1b[32m'
    def info(self, message: str):
        pass
    def error(self, message: str):
        pass
logger = Logger()

def load_data(file: str) -> pd.DataFrame:
    data = pd.read_csv(file)
    return data
def show_type_1(data: pd.DataFrame) -> None:
    colors = ['#FF7F50', '#DDA0DD', '#66CDAA', '#BC8F8F']
def prepare_data(dataFrame: pd.DataFrame, target: str):
    n_cols = 1
    dataset = dataFrame[target]
    dataset = pd.DataFrame(dataset)
    data = dataset.values
    train_size = int(len(data) * 0.75)
    test_size = len(data) - train_size
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(np.array(data))
    train_data = scaled_data[0:train_size, :]
    x_train = []
    y_train = []
    time_steps = 60
    n_cols = 1
    for i in range(time_steps, len(scaled_data)):
        x_train.append(scaled_data[i - time_steps:i, :n_cols])
        y_train.append(scaled_data[i, :n_cols])
    x_train, y_train = (np.array(x_train), np.array(y_train))
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], n_cols))
    return (x_train, y_train, scaler, train_size, test_size, scaled_data)
def generate_forecast(scaled_data, train_size) -> (np.array, np.array):
    time_steps = 60
    test_data = scaled_data[train_size - time_steps:, :]
    x_test = []
    y_test = []
    n_cols = 1
    for i in range(time_steps, len(test_data)):
        x_test.append(test_data[i - time_steps:i, 0:n_cols])
        y_test.append(test_data[i, 0:n_cols])
    x_test, y_test = (np.array(x_test), np.array(y_test))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], n_cols))
    return (x_test, y_test)
def generate_forecast_v2(dataFrame: pd.DataFrame, target: str) -> (np.array, np.array):
    dataset = dataFrame[target]
    dataset = pd.DataFrame(dataset)
    data = dataset.values
    train_size = int(len(data) * 0.75)
    test_size = len(data) - train_size
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(np.array(dataset))
    train_data = scaled_data[0:train_size, :]
    x_train = []
    y_train = []
    time_steps = 60
    n_cols = 1
    for i in range(time_steps, len(scaled_data)):
        x_train.append(scaled_data[i - time_steps:i, :n_cols])
        y_train.append(scaled_data[i, :n_cols])
    x_train, y_train = (np.array(x_train), np.array(y_train))
    x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], n_cols))
    test_data = scaled_data[train_size - time_steps:, :]
    x_test = []
    y_test = []
    n_cols = 1
    for i in range(time_steps, len(test_data)):
        x_test.append(test_data[i - time_steps:i, 0:n_cols])
        y_test.append(test_data[i, 0:n_cols])
    x_test, y_test = (np.array(x_test), np.array(y_test))
    x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], n_cols))
    return (x_test, y_test, train_size)

train_data = load_data('/kaggle/input/daily-climate-time-series-data/DailyDelhiClimateTrain.csv')
test_data = load_data('/kaggle/input/daily-climate-time-series-data/DailyDelhiClimateTest.csv')

train_data = train_data[(train_data['meanpressure'] > 980) & (train_data['meanpressure'] < 1050)]
data_to_show = train_data.drop('date', axis=1)

ts_decomposition = seasonal_decompose(x=train_data['meantemp'], model='additive', period=365)
trend_estimate = ts_decomposition.trend
seasonal_estimate = ts_decomposition.seasonal
residual_estimate = ts_decomposition.resid

model = Sequential([LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1], 1)), LSTM(units=50, return_sequences=False), Dense(units=25), Dense(units=1)])
model.compile(optimizer='adam', loss='mean_squared_error')
history = model.fit(x_train, y_train, epochs=30, batch_size=32)

x_test, y_test = generate_forecast(scaled_data, train_size)
y_test = scaler.inverse_transform(y_test)
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)

preds_acts = pd.DataFrame(data={'Predictions': predictions.flatten(), 'Actuals': y_test.flatten()})
plt.figure(figsize=(16, 6))
plt.plot(preds_acts['Predictions'])
plt.plot(preds_acts['Actuals'])
plt.legend(['Predictions', 'Actuals'])
plt.show()