Multivariate time series forecasting using Vector Auto-Regressive Model. :param df: pandas.DataFrame, index: time, columns: sensor id, content: data. :param n_forwards: a tuple of horizons. :param n_lags: the order of the VAR model. :param test_ratio: :return: [list of
(df, n_forwards=(1, 3), n_lags=4, test_ratio=0.2)
| 51 | |
| 52 | |
| 53 | def var_predict(df, n_forwards=(1, 3), n_lags=4, test_ratio=0.2): |
| 54 | """ |
| 55 | Multivariate time series forecasting using Vector Auto-Regressive Model. |
| 56 | :param df: pandas.DataFrame, index: time, columns: sensor id, content: data. |
| 57 | :param n_forwards: a tuple of horizons. |
| 58 | :param n_lags: the order of the VAR model. |
| 59 | :param test_ratio: |
| 60 | :return: [list of prediction in different horizon], dt_test |
| 61 | """ |
| 62 | n_sample, n_output = df.shape |
| 63 | n_test = int(round(n_sample * test_ratio)) |
| 64 | n_train = n_sample - n_test |
| 65 | df_train, df_test = df[:n_train], df[n_train:] |
| 66 | |
| 67 | scaler = StandardScaler(mean=df_train.values.mean(), std=df_train.values.std()) |
| 68 | data = scaler.transform(df_train.values) |
| 69 | var_model = VAR(data) |
| 70 | var_result = var_model.fit(n_lags) |
| 71 | max_n_forwards = np.max(n_forwards) |
| 72 | # Do forecasting. |
| 73 | result = np.zeros(shape=(len(n_forwards), n_test, n_output)) |
| 74 | start = n_train - n_lags - max_n_forwards + 1 |
| 75 | for input_ind in range(start, n_sample - n_lags): |
| 76 | prediction = var_result.forecast(scaler.transform(df.values[input_ind: input_ind + n_lags]), max_n_forwards) |
| 77 | for i, n_forward in enumerate(n_forwards): |
| 78 | result_ind = input_ind - n_train + n_lags + n_forward - 1 |
| 79 | if 0 <= result_ind < n_test: |
| 80 | result[i, result_ind, :] = prediction[n_forward - 1, :] |
| 81 | |
| 82 | df_predicts = [] |
| 83 | for i, n_forward in enumerate(n_forwards): |
| 84 | df_predict = pd.DataFrame(scaler.inverse_transform(result[i]), index=df_test.index, columns=df_test.columns) |
| 85 | df_predicts.append(df_predict) |
| 86 | return df_predicts, df_test |
| 87 | |
| 88 | |
| 89 | def eval_static(traffic_reading_df): |
no test coverage detected