Neural ODE weather prediction¶
This example trains a neural ODE: an MLP is the right-hand side of the ODE, and its weights are the parameters of the problem. It fits the Delhi monthly climate data (mean temperature, humidity, wind speed, mean pressure), training on a growing prefix of the series and predicting the rest.
import pathlib
import equinox as eqx
import jax
import jax.numpy as jnp
import jax.random as jr
import matplotlib.pyplot as plt
import numpy as np
import optax
from diffsol_jax import ODEProblem, solve
from tqdm import trange
DATA_PATH = pathlib.Path("data") / "MonthlyDelhiClimate.csv"
PLOT_DIR = pathlib.Path("plots")
DATA_DIM = 4
COLUMNS = ["meantemp", "humidity", "wind_speed", "meanpressure"]
def load_data():
data = np.loadtxt(DATA_PATH, delimiter=",", skiprows=1)
return jnp.asarray(data[:, 0]), jnp.asarray(data[:, 1:])
The network is a small Equinox MLP mapping the state to its time derivative.
class NeuralNetwork(eqx.Module):
layers: list[eqx.nn.Linear]
def __call__(self, x):
x = jax.nn.silu(self.layers[0](x))
x = jax.nn.silu(self.layers[1](x))
return self.layers[2](x)
def make_network(data_dim, key):
key1, key2, key3 = jax.random.split(key, 3)
return NeuralNetwork(
layers=[
eqx.nn.Linear(data_dim, 64, key=key1),
eqx.nn.Linear(64, 32, key=key2),
eqx.nn.Linear(32, data_dim, key=key3),
]
)
The network itself is the params= template: its weight arrays are the
parameters of the problem, and jax.grad of a solve returns a network of
gradients. The dynamics are non-stiff, so the explicit tsit45 solver fits.
ts, ys = load_data()
y0 = ys[0]
net = make_network(DATA_DIM, key=jr.key(0))
problem = ODEProblem(lambda x, net, t: net(x), state=y0, params=net, solver="tsit45")
Each round trains on a prefix of the data, a few months longer each time; fitting the whole series at once from a random initialisation tends to get stuck. The loss solves the ODE over the prefix and compares with the data.
def train_one_round(net, ts_batch, ys_batch, round_idx, steps=250):
opt = optax.adamw(1e-3)
opt_state = opt.init(net)
def loss_fn(p):
ys_pred = solve(problem, y0, p, ts_batch[0], ts_batch[-1], saveat=ts_batch)
return jnp.sum((ys_pred - ys_batch) ** 2)
@jax.jit
def step(p, opt_state):
loss_val, grads = jax.value_and_grad(loss_fn)(p)
updates, opt_state = opt.update(grads, opt_state, p)
return optax.apply_updates(p, updates), opt_state, loss_val
pbar = trange(steps, desc=f"round {round_idx}", leave=False)
for _ in pbar:
net, opt_state, loss_val = step(net, opt_state)
pbar.set_postfix(loss=f"{loss_val:.4f}")
return net
def plot_round(round_idx, batch_len, predict_ys, path):
fig, axes = plt.subplots(DATA_DIM, 1, figsize=(8, 10), sharex=True)
for i, (ax, name) in enumerate(zip(axes, COLUMNS)):
ax.plot(ts, ys[:, i], "o", ms=3, color="black", label=f"{name}_data")
ax.plot(ts[:batch_len], predict_ys[:batch_len, i], "-", label=f"{name}_train")
ax.plot(
ts[batch_len:], predict_ys[batch_len:, i], "--", label=f"{name}_predict"
)
ax.set_ylabel(name)
ax.legend(fontsize="small")
axes[-1].set_xlabel("month")
fig.suptitle(f"round {round_idx}")
fig.tight_layout()
fig.savefig(path)
plt.close(fig)
After each round, solving over the full time range shows the fit on the training prefix and the prediction beyond it.
PLOT_DIR.mkdir(exist_ok=True)
BATCH_STEP = 4
rounds = trange(1, ts.shape[0] // BATCH_STEP, desc="rounds")
for i in rounds:
batch_len = i * BATCH_STEP
rounds.set_postfix(data_points=batch_len)
net = train_one_round(net, ts[:batch_len], ys[:batch_len], i)
predict_ys = solve(problem, y0, net, ts[0], ts[-1], saveat=ts)
plot_round(i, batch_len, predict_ys, PLOT_DIR / f"neural-ode-weather_{i}.png")
The last round, trained on everything but the final months:
