Training an Inverse Model and Computing Predictions¶

This tutorial shows how to use ncpi to estimate the excitation-inhibition (E/I) ratio from simulated local field potentials (LFPs). It generates synthetic signals with known E/I ratios, extracts features, trains three inference models, and compares their predictions with the known simulated values.

This tutorial extends the README.md example. While the README.md uses 1,000 simulated samples and trains one regressor, this notebook uses 10,000 samples and compares three regressors.

Requirements¶

To run this notebook, install:

  • ncpi
  • scikit-learn
  • pycatch22
  • matplotlib

1) Set up configuration and simulation helpers¶

This section mirrors the README setup (Gao et al., 2017-inspired synthetic LFP generation).

In [1]:
from pathlib import Path
import shutil

import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import mean_squared_error

import ncpi


RNG = np.random.default_rng(42)
FS = 1000.0  # Hz
DT = 1.0 / FS  # s
DURATION_S = 12.0  # s
N_SAMPLES_SIGNAL = int(FS * DURATION_S)
N_SAMPLES_DATASET = 10000  # number of synthetic LFP samples
ARTIFACT_ROOT = Path("training_predictions_artifacts")
if ARTIFACT_ROOT.exists():
    shutil.rmtree(ARTIFACT_ROOT)
ARTIFACT_ROOT.mkdir(parents=True, exist_ok=True)

# Gao et al. (2017) Table 1 parameters
RATE_E_HZ = 2.0
RATE_I_HZ = 5.0
N_E = 8000
N_I = 2000
V_REST_MV = -65.0
E_AMPA_MV = 0.0
E_GABAA_MV = -80.0
TAU_RISE_AMPA_MS = 0.1
TAU_DECAY_AMPA_MS = 2.0
TAU_RISE_GABAA_MS = 0.5
TAU_DECAY_GABAA_MS = 10.0
EPS = 1e-12


def conductance_kernel(tau_rise_ms, tau_decay_ms, fs_hz, support_ms=200.0):
    t = np.arange(0.0, support_ms / 1000.0, 1.0 / fs_hz)
    tau_r = tau_rise_ms / 1000.0
    tau_d = tau_decay_ms / 1000.0
    k = np.exp(-t / tau_d) - np.exp(-t / tau_r)
    k[k < 0.0] = 0.0
    k = k / (np.sum(k) + EPS)
    return k


K_AMPA = conductance_kernel(TAU_RISE_AMPA_MS, TAU_DECAY_AMPA_MS, FS)
K_GABAA = conductance_kernel(TAU_RISE_GABAA_MS, TAU_DECAY_GABAA_MS, FS)


def poisson_counts_from_isi(rate_hz, duration_s, dt_s, n_samples, rng):
    expected_spikes = max(1, int(rate_hz * duration_s))
    n_draws = max(32, int(expected_spikes + 8.0 * np.sqrt(expected_spikes) + 64))
    isi = rng.exponential(scale=1.0 / rate_hz, size=n_draws)
    spike_times = np.cumsum(isi)

    while spike_times[-1] < duration_s:
        extra = rng.exponential(scale=1.0 / rate_hz, size=n_draws)
        spike_times = np.concatenate([spike_times, spike_times[-1] + np.cumsum(extra)])

    spike_times = spike_times[spike_times < duration_s]
    spike_bins = (spike_times / dt_s).astype(int)
    return np.bincount(spike_bins, minlength=n_samples).astype(float)


def simulate_lfp(target_inh_over_exc):
    spikes_e = poisson_counts_from_isi(
        rate_hz=RATE_E_HZ * N_E,
        duration_s=DURATION_S,
        dt_s=DT,
        n_samples=N_SAMPLES_SIGNAL,
        rng=RNG,
    )
    spikes_i = poisson_counts_from_isi(
        rate_hz=RATE_I_HZ * N_I,
        duration_s=DURATION_S,
        dt_s=DT,
        n_samples=N_SAMPLES_SIGNAL,
        rng=RNG,
    )

    g_e = np.convolve(spikes_e, K_AMPA, mode="same")
    g_i = np.convolve(spikes_i, K_GABAA, mode="same")

    # Set mean gI to 2x-6x mean gE.
    g_i *= (target_inh_over_exc * np.mean(g_e)) / (np.mean(g_i) + EPS)
    ei_ratio = np.mean(g_e) / (np.mean(g_i) + EPS)

    i_e = g_e * (V_REST_MV - E_AMPA_MV)
    i_i = g_i * (V_REST_MV - E_GABAA_MV)
    lfp = i_e + i_i

    total_power = np.sum(np.abs(np.fft.rfft(lfp)) ** 2)
    norm = np.sqrt(total_power + EPS)
    return lfp / norm, i_e / norm, i_i / norm, ei_ratio

2) Generate synthetic data and compute catch22 features¶

This step follows the same procedure as the README example.

In [2]:
print("[1/6] Initializing feature engine...")
lfp_samples = []
ei_ratios = np.zeros(N_SAMPLES_DATASET, dtype=float)
feature_engine = ncpi.Features(method="catch22", params={"normalize": True})
dataset_progress_step = max(1, N_SAMPLES_DATASET // 10)

print("[2/6] Generating synthetic dataset...")
for i in range(N_SAMPLES_DATASET):
    target_inh_over_exc = RNG.uniform(2.0, 6.0)
    lfp, i_e, i_i, ei_ratio = simulate_lfp(target_inh_over_exc)
    lfp_samples.append(lfp)
    ei_ratios[i] = ei_ratio

    if (i + 1) % dataset_progress_step == 0 or (i + 1) == N_SAMPLES_DATASET:
        pct = 100.0 * (i + 1) / N_SAMPLES_DATASET
        print(f"  -> Dataset progress: {i + 1}/{N_SAMPLES_DATASET} ({pct:.1f}%)")

print("  -> Computing catch22 features...")

def feature_progress(completed, total, percent):
    if completed > 0 and (percent % 10 == 0 or completed == total):
        print(f"  -> Feature progress: {completed}/{total} ({percent}%)")

catch22_features = np.asarray(
    feature_engine.compute_features(
        samples=lfp_samples,
        n_jobs=None,
        progress_callback=feature_progress,
    ),
    dtype=float,
)

print("Feature matrix shape:", catch22_features.shape)
[1/6] Initializing feature engine...
[2/6] Generating synthetic dataset...
  -> Dataset progress: 1000/10000 (10.0%)
  -> Dataset progress: 2000/10000 (20.0%)
  -> Dataset progress: 3000/10000 (30.0%)
  -> Dataset progress: 4000/10000 (40.0%)
  -> Dataset progress: 5000/10000 (50.0%)
  -> Dataset progress: 6000/10000 (60.0%)
  -> Dataset progress: 7000/10000 (70.0%)
  -> Dataset progress: 8000/10000 (80.0%)
  -> Dataset progress: 9000/10000 (90.0%)
  -> Dataset progress: 10000/10000 (100.0%)
  -> Computing catch22 features...
Computing catch22 features:   0%|          | 0/10000 [00:00<?, ?it/s]
Computing catch22 features:   0%|          | 1/10000 [00:05<14:40:06,  5.28s/it]
  -> Feature progress: 1/10000 (0%)
Computing catch22 features:   2%|▏         | 157/10000 [00:07<06:37, 24.76it/s] 
Computing catch22 features:   2%|▏         | 235/10000 [00:08<03:58, 40.88it/s]
  -> Feature progress: 1000/10000 (10%)
Computing catch22 features:  11%|█         | 1093/10000 [00:09<00:37, 237.84it/s]
Computing catch22 features:  12%|█▏        | 1249/10000 [00:09<00:33, 262.31it/s]
Computing catch22 features:  13%|█▎        | 1327/10000 [00:12<01:11, 121.17it/s]
Computing catch22 features:  16%|█▋        | 1639/10000 [00:13<00:48, 173.86it/s]
  -> Feature progress: 2000/10000 (20%)
Computing catch22 features:  21%|██        | 2107/10000 [00:13<00:28, 272.51it/s]
Computing catch22 features:  26%|██▌       | 2575/10000 [00:15<00:24, 304.42it/s]
Computing catch22 features:  27%|██▋       | 2653/10000 [00:15<00:25, 283.22it/s]
Computing catch22 features:  27%|██▋       | 2731/10000 [00:17<00:42, 170.32it/s]
Computing catch22 features:  28%|██▊       | 2809/10000 [00:18<00:51, 139.94it/s]
Computing catch22 features:  29%|██▉       | 2887/10000 [00:18<00:44, 160.08it/s]
  -> Feature progress: 3000/10000 (30%)
Computing catch22 features:  33%|███▎      | 3277/10000 [00:19<00:22, 294.50it/s]
Computing catch22 features:  37%|███▋      | 3667/10000 [00:19<00:15, 415.93it/s]
Computing catch22 features:  39%|███▉      | 3901/10000 [00:20<00:14, 423.64it/s]
Computing catch22 features:  40%|███▉      | 3979/10000 [00:20<00:17, 349.51it/s]
  -> Feature progress: 4000/10000 (40%)
Computing catch22 features:  41%|████      | 4057/10000 [00:21<00:22, 269.75it/s]
Computing catch22 features:  41%|████▏     | 4135/10000 [00:24<00:56, 103.36it/s]
Computing catch22 features:  46%|████▌     | 4603/10000 [00:24<00:23, 228.30it/s]
Computing catch22 features:  47%|████▋     | 4681/10000 [00:25<00:25, 206.92it/s]
Computing catch22 features:  50%|████▉     | 4993/10000 [00:26<00:20, 244.21it/s]
  -> Feature progress: 5000/10000 (50%)
Computing catch22 features:  54%|█████▍    | 5383/10000 [00:27<00:15, 295.88it/s]
Computing catch22 features:  55%|█████▍    | 5461/10000 [00:28<00:20, 222.94it/s]
Computing catch22 features:  55%|█████▌    | 5539/10000 [00:29<00:24, 180.68it/s]
Computing catch22 features:  58%|█████▊    | 5773/10000 [00:31<00:26, 161.81it/s]
  -> Feature progress: 6000/10000 (60%)
Computing catch22 features:  63%|██████▎   | 6319/10000 [00:31<00:11, 312.94it/s]
Computing catch22 features:  64%|██████▍   | 6397/10000 [00:32<00:14, 250.02it/s]
Computing catch22 features:  65%|██████▍   | 6475/10000 [00:32<00:15, 231.79it/s]
Computing catch22 features:  66%|██████▌   | 6553/10000 [00:33<00:15, 229.56it/s]
Computing catch22 features:  69%|██████▊   | 6865/10000 [00:33<00:07, 401.43it/s]
Computing catch22 features:  70%|██████▉   | 6973/10000 [00:34<00:14, 207.04it/s]
  -> Feature progress: 7000/10000 (70%)
Computing catch22 features:  72%|███████▏  | 7177/10000 [00:35<00:13, 203.28it/s]
Computing catch22 features:  74%|███████▍  | 7411/10000 [00:36<00:10, 250.74it/s]
Computing catch22 features:  76%|███████▌  | 7567/10000 [00:38<00:14, 166.61it/s]
Computing catch22 features:  77%|███████▋  | 7723/10000 [00:38<00:11, 205.54it/s]
Computing catch22 features:  80%|████████  | 8035/10000 [00:38<00:05, 342.85it/s]
  -> Feature progress: 8000/10000 (80%)
Computing catch22 features:  82%|████████▏ | 8155/10000 [00:39<00:06, 299.75it/s]
Computing catch22 features:  83%|████████▎ | 8347/10000 [00:40<00:06, 238.23it/s]
Computing catch22 features:  84%|████████▍ | 8425/10000 [00:41<00:07, 215.70it/s]
Computing catch22 features:  86%|████████▌ | 8581/10000 [00:41<00:05, 259.52it/s]
Computing catch22 features:  87%|████████▋ | 8737/10000 [00:42<00:06, 205.21it/s]
Computing catch22 features:  90%|████████▉ | 8971/10000 [00:44<00:05, 181.84it/s]
  -> Feature progress: 9000/10000 (90%)
Computing catch22 features:  92%|█████████▏| 9205/10000 [00:44<00:03, 226.45it/s]
Computing catch22 features:  93%|█████████▎| 9283/10000 [00:45<00:03, 212.76it/s]
Computing catch22 features:  96%|█████████▌| 9595/10000 [00:45<00:01, 363.07it/s]
Computing catch22 features:  98%|█████████▊| 9829/10000 [00:45<00:00, 445.65it/s]
Computing catch22 features: 100%|██████████| 10000/10000 [00:45<00:00, 219.81it/s]
  -> Feature progress: 10000/10000 (100%)
Feature matrix shape: (10000, 22)

3) Split train/test data¶

We use the same randomized 80/20 split as in the README example.

In [3]:
print("[3/6] Splitting train/test data...")
idx = np.arange(N_SAMPLES_DATASET)
RNG.shuffle(idx)
split = int(0.8 * len(idx))
tr, te = idx[:split], idx[split:]

X_train, X_test = catch22_features[tr], catch22_features[te]
y_train, y_test = ei_ratios[tr], ei_ratios[te]

print("X_train:", X_train.shape, "X_test:", X_test.shape)
[3/6] Splitting train/test data...
X_train: (8000, 22) X_test: (2000, 22)

4) Train and evaluate multiple ML regressors¶

Here we keep the same ncpi.Inference API from the README, but run several model families.

In [4]:
MODEL_CONFIGS = {
    "RandomForestRegressor": {
        "n_estimators": 300,
        "max_depth": 20,
        "min_samples_leaf": 1,
        "max_features": "sqrt",
        "random_state": 42,
        "n_jobs": 1,
    },
    "Ridge": {
        "alpha": 1.0,
        "random_state": 42,
    },
    "MLPRegressor": {
        "hidden_layer_sizes": (256, 128, 64),
        "activation": "relu",
        "solver": "adam",
        "alpha": 5e-4,
        "learning_rate_init": 1e-3,
        "max_iter": 800,
        "early_stopping": True,
        "random_state": 42,
    },
}

results = {}

print("[4/6] Training and predicting across models...")
for model_name, hyperparams in MODEL_CONFIGS.items():
    print(f"\n--- Model: {model_name}")

    model = ncpi.Inference(model=model_name, hyperparams=hyperparams)
    model.add_simulation_data(X_train, y_train)

    result_dir = ARTIFACT_ROOT / model_name
    model.train(param_grid=None, scaler=True, seed=42, result_dir=str(result_dir))
    y_pred = np.asarray(
        model.predict(X_test, scaler=True, n_jobs=1, result_dir=str(result_dir)),
        dtype=float,
    ).reshape(-1)

    mse = mean_squared_error(y_test, y_pred)
    results[model_name] = {
        "y_pred": y_pred,
        "mse": float(mse),
    }

    print(f"Test MSE ({model_name}): {mse:.5f}")
[4/6] Training and predicting across models...

--- Model: RandomForestRegressor
Training single sklearn model on data...
Scaler saved at 'training_predictions_artifacts/RandomForestRegressor/scaler.pkl'
Model saved at 'training_predictions_artifacts/RandomForestRegressor/model.pkl'
Computing predictions:   0%|          | 0/2000 [00:00<?, ?it/s]
Computing predictions:   0%|          | 1/2000 [00:02<1:15:41,  2.27s/it]
Computing predictions:  13%|█▎        | 251/2000 [00:04<00:26, 65.74it/s]
Computing predictions:  25%|██▌       | 501/2000 [00:06<00:17, 87.19it/s]
Computing predictions:  38%|███▊      | 751/2000 [00:08<00:12, 97.23it/s]
Computing predictions:  50%|█████     | 1001/2000 [00:11<00:09, 103.04it/s]
Computing predictions:  63%|██████▎   | 1251/2000 [00:13<00:07, 104.46it/s]
Computing predictions:  75%|███████▌  | 1501/2000 [00:15<00:04, 105.96it/s]
Computing predictions:  88%|████████▊ | 1751/2000 [00:18<00:02, 107.16it/s]
Computing predictions: 100%|██████████| 2000/2000 [00:18<00:00, 110.89it/s]
Test MSE (RandomForestRegressor): 0.00022

--- Model: Ridge
Training single sklearn model on data...
Scaler saved at 'training_predictions_artifacts/Ridge/scaler.pkl'
Model saved at 'training_predictions_artifacts/Ridge/model.pkl'

Computing predictions:   0%|          | 0/2000 [00:00<?, ?it/s]
Computing predictions:   0%|          | 1/2000 [00:00<31:27,  1.06it/s]
Computing predictions:  50%|█████     | 1001/2000 [00:01<00:00, 1280.68it/s]
Computing predictions: 100%|██████████| 2000/2000 [00:01<00:00, 1738.37it/s]

Test MSE (Ridge): 0.00052

--- Model: MLPRegressor
Training single sklearn model on data...
Scaler saved at 'training_predictions_artifacts/MLPRegressor/scaler.pkl'
Model saved at 'training_predictions_artifacts/MLPRegressor/model.pkl'
Computing predictions:   0%|          | 0/2000 [00:00<?, ?it/s]
Computing predictions:  13%|█▎        | 251/2000 [00:00<00:00, 2042.87it/s]
Computing predictions:  50%|█████     | 1001/2000 [00:00<00:00, 4453.25it/s]
Computing predictions:  88%|████████▊ | 1751/2000 [00:00<00:00, 5227.22it/s]
Computing predictions: 100%|██████████| 2000/2000 [00:00<00:00, 5439.35it/s]
Test MSE (MLPRegressor): 0.00033

5) Compare prediction quality across models¶

We compare the predicted E/I ratios with the known simulated values and summarize the test MSE.

In [5]:
print("[5/6] Plotting model comparison...")
model_names = list(results.keys())

fig, axes = plt.subplots(1, len(model_names), figsize=(6 * len(model_names), 5), squeeze=False)
axes = axes.ravel()

for ax, model_name in zip(axes, model_names):
    y_pred = results[model_name]["y_pred"]
    mse = results[model_name]["mse"]

    ax.scatter(y_test, y_pred, s=16, alpha=0.7, label="Predictions")
    lo = float(min(np.min(y_test), np.min(y_pred)))
    hi = float(max(np.max(y_test), np.max(y_pred)))
    ax.plot([lo, hi], [lo, hi], "k--", linewidth=1.1, label="Ideal fit")

    ax.set_xlabel("Known simulated E/I ratio")
    ax.set_ylabel("Predicted E/I ratio")
    ax.set_title(model_name)
    ax.text(0.03, 0.95, f"MSE = {mse:.5f}", transform=ax.transAxes, va="top", ha="left")
    ax.legend(frameon=False, loc="lower right")

plt.tight_layout()
plt.show()

# Also print a compact ranking
ranking = sorted(((m, results[m]["mse"]) for m in model_names), key=lambda x: x[1])
print("\nMSE ranking (best to worst):")
for name, mse in ranking:
    print(f"- {name}: {mse:.5f}")
[5/6] Plotting model comparison...
No description has been provided for this image
MSE ranking (best to worst):
- RandomForestRegressor: 0.00022
- MLPRegressor: 0.00033
- Ridge: 0.00052