def get_lstm_backtest(serialized_model, dataset): df = pd.DataFrame.from_dict(dataset) ts = TimeSeries.from_dataframe(df, time_col='time_interval', value_cols=['count']) scaler = Scaler() ts = scaler.fit_transform(ts) model = pickle.loads(serialized_model) backtest = model.historical_forecasts(series=ts, start=0.8, forecast_horizon=1, stride=1, retrain=False, verbose=False) backtest = scaler.inverse_transform(backtest[1:]) ts = scaler.inverse_transform(ts) backtest.plot(label='LSTM Model', lw=3, c='orange')
def get_lstm_model(dataset=None, plot=False, verbose=False): if (dataset is None): df = pd.read_csv("jeans_day.csv") else: df = pd.DataFrame.from_dict(dataset) ts = TimeSeries.from_dataframe(df, time_col='time_interval', value_cols=['count']) train, val = ts.split_after(0.8) scaler = Scaler() train_transformed = scaler.fit_transform(train) val_transformed = scaler.transform(val) ts_transformed = scaler.transform(ts) params = dict() params['model'] = ["LSTM"] params['hidden_size'] = [50, 75, 100] params['n_rnn_layers'] = [1] params['input_chunk_length'] = [14] params['output_chunk_length'] = [1] params['n_epochs'] = [100] params['dropout'] = [0] params['batch_size'] = [4, 6] params['random_state'] = [0, 1] params['loss_fn'] = [MSELoss()] lstm = RNNModel.gridsearch(parameters=params, series=train_transformed, val_series=val_transformed, verbose=verbose, metric=mse) params = lstm[1] lstm_model = lstm[0] lstm_model.fit(train_transformed, verbose=True) if (plot): backtest = lstm_model.historical_forecasts(series=ts_transformed, start=0.8, forecast_horizon=1, stride=1, retrain=False, verbose=False) print(val) print(backtest[1:]) print("R2: {}".format( r2_score(scaler.inverse_transform(val_transformed), scaler.inverse_transform(backtest[1:]), intersect=False))) print("MAPE: {}".format( mape(scaler.inverse_transform(val_transformed), scaler.inverse_transform(backtest[1:])))) print("MASE: {}".format( mase(scaler.inverse_transform(val_transformed), scaler.inverse_transform(backtest[1:]), train))) print("MAE: {}".format( mae(scaler.inverse_transform(val_transformed), scaler.inverse_transform(backtest[1:])))) scaler.inverse_transform(backtest).plot(label='backtest') scaler.inverse_transform(ts_transformed).plot(label='actual') plt.title("H&M Daily, LSTM Model") plt.xlabel("Date") plt.ylabel("Count") plt.legend() plt.show() else: return [lstm_model, params]