|
| 1 | +""" |
| 2 | +=========================== |
| 3 | +Multi-step-ahead NARX model |
| 4 | +=========================== |
| 5 | +
|
| 6 | +.. currentmodule:: fastcan |
| 7 | +
|
| 8 | +In this example, we will compare one-step-ahead NARX and multi-step-ahead NARX. |
| 9 | +""" |
| 10 | + |
| 11 | +# Authors: Sikai Zhang |
| 12 | +# SPDX-License-Identifier: MIT |
| 13 | + |
| 14 | +# %% |
| 15 | +# Nonlinear system |
| 16 | +# ---------------- |
| 17 | +# |
| 18 | +# `Duffing equation <https://en.wikipedia.org/wiki/Duffing_equation>` is used to |
| 19 | +# generate simulated data. The mathematical model is given by |
| 20 | +# |
| 21 | +# .. math:: |
| 22 | +# \ddot{y} + 0.1\dot{y} - y + 0.25y^3 = u |
| 23 | +# |
| 24 | +# where :math:`y` is the output signal and :math:`u` is the input signal, which is |
| 25 | +# :math:`u(t) = 2.5\cos(2\pi t)`. |
| 26 | +# |
| 27 | +# The phase portraits of the Duffing equation are shown below. |
| 28 | + |
| 29 | +import matplotlib.pyplot as plt |
| 30 | +import numpy as np |
| 31 | +from scipy.integrate import odeint |
| 32 | + |
| 33 | + |
| 34 | +def duffing_equation(y, t): |
| 35 | + """Non-autonomous system""" |
| 36 | + y1, y2 = y |
| 37 | + u = 2.5 * np.cos(2 * np.pi * t) |
| 38 | + dydt = [y2, -0.1 * y2 + y1 - 0.25 * y1**3 + u] |
| 39 | + return dydt |
| 40 | + |
| 41 | + |
| 42 | +def auto_duffing_equation(y, t): |
| 43 | + """Autonomous system""" |
| 44 | + y1, y2 = y |
| 45 | + dydt = [y2, -0.1 * y2 + y1 - 0.25 * y1**3] |
| 46 | + return dydt |
| 47 | + |
| 48 | + |
| 49 | +dur = 10 |
| 50 | +n_samples = 1000 |
| 51 | + |
| 52 | +y0 = None |
| 53 | +if y0 is None: |
| 54 | + n_init = 10 |
| 55 | + x0 = np.linspace(0, 2, n_init) |
| 56 | + y0_y = np.cos(np.pi * x0) |
| 57 | + y0_x = np.sin(np.pi * x0) |
| 58 | + y0 = np.c_[y0_x, y0_y] |
| 59 | +else: |
| 60 | + n_init = len(y0) |
| 61 | + |
| 62 | +t = np.linspace(0, dur, n_samples) |
| 63 | +sol = np.zeros((n_init, n_samples, 2)) |
| 64 | +for i in range(n_init): |
| 65 | + sol[i] = odeint(auto_duffing_equation, y0[i], t) |
| 66 | + |
| 67 | +for i in range(n_init): |
| 68 | + plt.plot(sol[i, :, 0], sol[i, :, 1], c="tab:blue") |
| 69 | + |
| 70 | +plt.title("Phase portraits of Duffing equation") |
| 71 | +plt.xlabel("y(t)") |
| 72 | +plt.ylabel("dy/dt(t)") |
| 73 | +plt.show() |
| 74 | + |
| 75 | +# %% |
| 76 | +# Generate training-test data |
| 77 | +# --------------------------- |
| 78 | +# |
| 79 | +# In the phase portraits, it is shown that the system has two stable equilibria. |
| 80 | +# We use one to generate training data and the other to generate test data. |
| 81 | + |
| 82 | +dur = 10 |
| 83 | +n_samples = 1000 |
| 84 | + |
| 85 | +t = np.linspace(0, dur, n_samples) |
| 86 | + |
| 87 | +sol = odeint(duffing_equation, [0.6, 0.8], t) |
| 88 | +u_train = 2.5 * np.cos(2 * np.pi * t).reshape(-1, 1) |
| 89 | +y_train = sol[:, 0] |
| 90 | + |
| 91 | +sol = odeint(auto_duffing_equation, [0.6, -0.8], t) |
| 92 | +u_test = 2.5 * np.cos(2 * np.pi * t).reshape(-1, 1) |
| 93 | +y_test = sol[:, 0] |
| 94 | + |
| 95 | +# %% |
| 96 | +# One-step-head VS. multi-step-ahead NARX |
| 97 | +# --------------------------------------- |
| 98 | +# |
| 99 | +# First, we use :meth:`make_narx` to obtain the reduced NARX model. |
| 100 | +# Then, the NARX model will be fitted with one-step-ahead predictor and |
| 101 | +# multi-step-ahead predictor, respectively. Generally, the training of one-step-ahead |
| 102 | +# (OSA) NARX is faster, while the multi-step-ahead (MSA) NARX is more accurate. |
| 103 | + |
| 104 | +from sklearn.metrics import r2_score |
| 105 | + |
| 106 | +from fastcan.narx import make_narx |
| 107 | + |
| 108 | +max_delay = 2 |
| 109 | + |
| 110 | +narx_model = make_narx( |
| 111 | + X=u_train, |
| 112 | + y=y_train, |
| 113 | + n_features_to_select=10, |
| 114 | + max_delay=max_delay, |
| 115 | + poly_degree=3, |
| 116 | + verbose=0, |
| 117 | +) |
| 118 | + |
| 119 | + |
| 120 | +def plot_prediction(ax, t, y_true, y_pred, title): |
| 121 | + ax.plot(t, y_true, label="true") |
| 122 | + ax.plot(t, y_pred, label="predicted") |
| 123 | + ax.legend() |
| 124 | + ax.set_title(f"{title} (R2: {r2_score(y_true, y_pred):.5f})") |
| 125 | + ax.set_xlabel("t (s)") |
| 126 | + ax.set_ylabel("y(t)") |
| 127 | + |
| 128 | + |
| 129 | +narx_model.fit(u_train, y_train) |
| 130 | +y_train_osa_pred = narx_model.predict(u_train, y_init=y_train[:max_delay]) |
| 131 | +y_test_osa_pred = narx_model.predict(u_test, y_init=y_test[:max_delay]) |
| 132 | + |
| 133 | +narx_model.fit(u_train, y_train, coef_init="one_step_ahead") |
| 134 | +y_train_msa_pred = narx_model.predict(u_train, y_init=y_train[:max_delay]) |
| 135 | +y_test_msa_pred = narx_model.predict(u_test, y_init=y_test[:max_delay]) |
| 136 | + |
| 137 | +fig, ax = plt.subplots(2, 2, figsize=(8, 6)) |
| 138 | +plot_prediction(ax[0, 0], t, y_train, y_train_osa_pred, "OSA NARX on Train") |
| 139 | +plot_prediction(ax[0, 1], t, y_train, y_train_msa_pred, "MSA NARX on Train") |
| 140 | +plot_prediction(ax[1, 0], t, y_test, y_test_osa_pred, "OSA NARX on Test") |
| 141 | +plot_prediction(ax[1, 1], t, y_test, y_test_msa_pred, "MSA NARX on Test") |
| 142 | +fig.tight_layout() |
| 143 | +plt.show() |
| 144 | + |
| 145 | + |
| 146 | +# %% |
| 147 | +# Multiple measurement sessions |
| 148 | +# ----------------------------- |
| 149 | +# |
| 150 | +# The plot above shows that the NARX model cannot capture the dynamics at |
| 151 | +# the left equilibrium shown in the phase portraits. To improve the performance, let us |
| 152 | +# combine the training and test data for model training to include the dynamics of both |
| 153 | +# equilibria. Here, we need to insert `np.nan` to indicate the model that training data |
| 154 | +# and test data are from different measurement sessions. The plot shows that the |
| 155 | +# prediction performance of the NARX on test data has been largely improved. |
| 156 | + |
| 157 | +u_all = np.r_[u_train, [[np.nan]], u_test] |
| 158 | +y_all = np.r_[y_train, [np.nan], y_test] |
| 159 | +narx_model = make_narx( |
| 160 | + X=u_all, |
| 161 | + y=y_all, |
| 162 | + n_features_to_select=10, |
| 163 | + max_delay=max_delay, |
| 164 | + poly_degree=3, |
| 165 | + verbose=0, |
| 166 | +) |
| 167 | + |
| 168 | +narx_model.fit(u_all, y_all) |
| 169 | +y_train_osa_pred = narx_model.predict(u_train, y_init=y_train[:max_delay]) |
| 170 | +y_test_osa_pred = narx_model.predict(u_test, y_init=y_test[:max_delay]) |
| 171 | + |
| 172 | +narx_model.fit(u_all, y_all, coef_init="one_step_ahead") |
| 173 | +y_train_msa_pred = narx_model.predict(u_train, y_init=y_train[:max_delay]) |
| 174 | +y_test_msa_pred = narx_model.predict(u_test, y_init=y_test[:max_delay]) |
| 175 | + |
| 176 | +fig, ax = plt.subplots(2, 2, figsize=(8, 6)) |
| 177 | +plot_prediction(ax[0, 0], t, y_train, y_train_osa_pred, "OSA NARX on Train") |
| 178 | +plot_prediction(ax[0, 1], t, y_train, y_train_msa_pred, "MSA NARX on Train") |
| 179 | +plot_prediction(ax[1, 0], t, y_test, y_test_osa_pred, "OSA NARX on Test") |
| 180 | +plot_prediction(ax[1, 1], t, y_test, y_test_msa_pred, "MSA NARX on Test") |
| 181 | +fig.tight_layout() |
| 182 | +plt.show() |
0 commit comments