Spectro-temporal receptive field (STRF) estimation on continuous data#

This demonstrates how an encoding model can be fit with multiple continuous inputs. In this case, we simulate the model behind a spectro-temporal receptive field (or STRF). First, we create a linear filter that maps patterns in spectro-temporal space onto an output, representing neural activity. We fit a receptive field model that attempts to recover the original linear filter that was used to create this data.

# Authors: Chris Holdgraf <choldgraf@gmail.com>
#          Eric Larson <larson.eric.d@gmail.com>
#
# License: BSD-3-Clause
# Copyright the MNE-Python contributors.
import matplotlib.pyplot as plt
import numpy as np
from scipy.io import loadmat
from scipy.stats import multivariate_normal
from sklearn.preprocessing import scale

import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge

rng = np.random.RandomState(1337)  # To make this example reproducible

Load audio data#

We’ll read in the audio data from [1] in order to simulate a response.

In addition, we’ll downsample the data along the time dimension in order to speed up computation. Note that depending on the input values, this may not be desired. For example if your input stimulus varies more quickly than 1/2 the sampling rate to which we are downsampling.

# Read in audio that's been recorded in epochs.
path_audio = mne.datasets.mtrf.data_path()
data = loadmat(str(path_audio / "speech_data.mat"))
audio = data["spectrogram"].T
sfreq = float(data["Fs"][0, 0])
n_decim = 2
audio = mne.filter.resample(audio, down=n_decim, npad="auto")
sfreq /= n_decim

Create a receptive field#

We’ll simulate a linear receptive field for a theoretical neural signal. This defines how the signal will respond to power in this receptive field space.

n_freqs = 20
tmin, tmax = -0.1, 0.4

# To simulate the data we'll create explicit delays here
delays_samp = np.arange(np.round(tmin * sfreq), np.round(tmax * sfreq) + 1).astype(int)
delays_sec = delays_samp / sfreq
freqs = np.linspace(50, 5000, n_freqs)
grid = np.array(np.meshgrid(delays_sec, freqs))

# We need data to be shaped as n_epochs, n_features, n_times, so swap axes here
grid = grid.swapaxes(0, -1).swapaxes(0, 1)

# Simulate a temporal receptive field with a Gabor filter
means_high = [0.1, 500]
means_low = [0.2, 2500]
cov = [[0.001, 0], [0, 500000]]
gauss_high = multivariate_normal.pdf(grid, means_high, cov)
gauss_low = -1 * multivariate_normal.pdf(grid, means_low, cov)
weights = gauss_high + gauss_low  # Combine to create the "true" STRF
kwargs = dict(
    vmax=np.abs(weights).max(),
    vmin=-np.abs(weights).max(),
    cmap="RdBu_r",
    shading="gouraud",
)

fig, ax = plt.subplots(layout="constrained")
ax.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax.set(title="Simulated STRF", xlabel="Time Lags (s)", ylabel="Frequency (Hz)")
plt.setp(ax.get_xticklabels(), rotation=45)
Simulated STRF

Simulate a neural response#

Using this receptive field, we’ll create an artificial neural response to a stimulus.

To do this, we’ll create a time-delayed version of the receptive field, and then calculate the dot product between this and the stimulus. Note that this is effectively doing a convolution between the stimulus and the receptive field. See here for more information.

# Reshape audio to split into epochs, then make epochs the first dimension.
n_epochs, n_seconds = 16, 5
audio = audio[:, : int(n_seconds * sfreq * n_epochs)]
X = audio.reshape([n_freqs, n_epochs, -1]).swapaxes(0, 1)
n_times = X.shape[-1]

# Delay the spectrogram according to delays so it can be combined w/ the STRF
# Lags will now be in axis 1, then we reshape to vectorize
delays = np.arange(np.round(tmin * sfreq), np.round(tmax * sfreq) + 1).astype(int)

# Iterate through indices and append
X_del = np.zeros((len(delays),) + X.shape)
for ii, ix_delay in enumerate(delays):
    # These arrays will take/put particular indices in the data
    take = [slice(None)] * X.ndim
    put = [slice(None)] * X.ndim
    if ix_delay > 0:
        take[-1] = slice(None, -ix_delay)
        put[-1] = slice(ix_delay, None)
    elif ix_delay < 0:
        take[-1] = slice(-ix_delay, None)
        put[-1] = slice(None, ix_delay)
    X_del[ii][tuple(put)] = X[tuple(take)]

# Now set the delayed axis to the 2nd dimension
X_del = np.rollaxis(X_del, 0, 3)
X_del = X_del.reshape([n_epochs, -1, n_times])
n_features = X_del.shape[1]
weights_sim = weights.ravel()

# Simulate a neural response to the sound, given this STRF
y = np.zeros((n_epochs, n_times))
for ii, iep in enumerate(X_del):
    # Simulate this epoch and add random noise
    noise_amp = 0.002
    y[ii] = np.dot(weights_sim, iep) + noise_amp * rng.randn(n_times)

# Plot the first 2 trials of audio and the simulated electrode activity
X_plt = scale(np.hstack(X[:2]).T).T
y_plt = scale(np.hstack(y[:2]))
time = np.arange(X_plt.shape[-1]) / sfreq
_, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6), sharex=True, layout="constrained")
ax1.pcolormesh(time, freqs, X_plt, vmin=0, vmax=4, cmap="Reds", shading="gouraud")
ax1.set_title("Input auditory features")
ax1.set(ylim=[freqs.min(), freqs.max()], ylabel="Frequency (Hz)")
ax2.plot(time, y_plt)
ax2.set(
    xlim=[time.min(), time.max()],
    title="Simulated response",
    xlabel="Time (s)",
    ylabel="Activity (a.u.)",
)
Input auditory features, Simulated response

Fit a model to recover this receptive field#

Finally, we’ll use the mne.decoding.ReceptiveField class to recover the linear receptive field of this signal. Note that properties of the receptive field (e.g. smoothness) will depend on the autocorrelation in the inputs and outputs.

# Create training and testing data
train, test = np.arange(n_epochs - 1), n_epochs - 1
X_train, X_test, y_train, y_test = X[train], X[test], y[train], y[test]
X_train, X_test, y_train, y_test = (
    np.rollaxis(ii, -1, 0) for ii in (X_train, X_test, y_train, y_test)
)
# Model the simulated data as a function of the spectrogram input
alphas = np.logspace(-3, 3, 7)
scores = np.zeros_like(alphas)
models = []
for ii, alpha in enumerate(alphas):
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=alpha)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores[ii] = rf.score(X_test, y_test).item()
    models.append(rf)

times = rf.delays_ / float(rf.sfreq)

# Choose the model that performed best on the held out data
ix_best_alpha = np.argmax(scores)
best_mod = models[ix_best_alpha]
coefs = best_mod.coef_[0]
best_pred = best_mod.predict(X_test)[:, 0]

# Plot the original STRF, and the one that we recovered with modeling.
_, (ax1, ax2) = plt.subplots(
    1,
    2,
    figsize=(6, 3),
    sharey=True,
    sharex=True,
    layout="constrained",
)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, coefs, **kwargs)
ax1.set_title("Original STRF")
ax2.set_title("Best Reconstructed STRF")
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2]], rotation=45)

# Plot the actual response and the predicted response on a held out stimulus
time_pred = np.arange(best_pred.shape[0]) / sfreq
fig, ax = plt.subplots()
ax.plot(time_pred, y_test, color="k", alpha=0.2, lw=4)
ax.plot(time_pred, best_pred, color="r", lw=1)
ax.set(title="Original and predicted activity", xlabel="Time (s)")
ax.legend(["Original", "Predicted"])
  • Original STRF, Best Reconstructed STRF
  • Original and predicted activity
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
  0%|          | Sample : 1/3450 [00:07<6:48:44,    7.11s/it]
 10%|█         | Sample : 345/3450 [00:07<01:00,   50.94it/s]
 20%|██        | Sample : 698/3450 [00:07<00:26,  105.56it/s]
 30%|███       | Sample : 1042/3450 [00:07<00:14,  161.29it/s]
 40%|████      | Sample : 1395/3450 [00:07<00:09,  221.17it/s]
 51%|█████     | Sample : 1747/3450 [00:07<00:06,  283.68it/s]
 61%|██████    | Sample : 2099/3450 [00:07<00:03,  349.09it/s]
 71%|███████   | Sample : 2440/3450 [00:07<00:02,  415.35it/s]
 81%|████████  | Sample : 2786/3450 [00:07<00:01,  485.67it/s]
 91%|█████████ | Sample : 3135/3450 [00:07<00:00,  559.85it/s]
100%|██████████| Sample : 3450/3450 [00:07<00:00,  474.60it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 351/3450 [00:00<00:00, 21915.25it/s]
 20%|██        | Sample : 699/3450 [00:00<00:00, 21822.02it/s]
 30%|███       | Sample : 1050/3450 [00:00<00:00, 21845.36it/s]
 41%|████      | Sample : 1399/3450 [00:00<00:00, 21832.73it/s]
 51%|█████     | Sample : 1752/3450 [00:00<00:00, 21873.24it/s]
 61%|██████    | Sample : 2104/3450 [00:00<00:00, 21896.76it/s]
 71%|███████   | Sample : 2455/3450 [00:00<00:00, 21894.37it/s]
 81%|████████  | Sample : 2800/3450 [00:00<00:00, 21843.33it/s]
 91%|█████████▏| Sample : 3149/3450 [00:00<00:00, 21831.21it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21867.98it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 350/3450 [00:00<00:00, 21840.46it/s]
 20%|██        | Sample : 703/3450 [00:00<00:00, 21945.84it/s]
 31%|███       | Sample : 1058/3450 [00:00<00:00, 22021.17it/s]
 41%|████      | Sample : 1412/3450 [00:00<00:00, 22035.59it/s]
 51%|█████     | Sample : 1765/3450 [00:00<00:00, 22041.30it/s]
 61%|██████    | Sample : 2090/3450 [00:00<00:00, 21713.41it/s]
 71%|███████   | Sample : 2440/3450 [00:00<00:00, 21737.32it/s]
 81%|████████  | Sample : 2793/3450 [00:00<00:00, 21780.04it/s]
 91%|█████████ | Sample : 3146/3450 [00:00<00:00, 21812.13it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21848.47it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 348/3450 [00:00<00:00, 21735.06it/s]
 20%|██        | Sample : 701/3450 [00:00<00:00, 21888.69it/s]
 30%|██▉       | Sample : 1029/3450 [00:00<00:00, 21391.32it/s]
 40%|████      | Sample : 1381/3450 [00:00<00:00, 21542.88it/s]
 50%|█████     | Sample : 1735/3450 [00:00<00:00, 21667.61it/s]
 61%|██████    | Sample : 2090/3450 [00:00<00:00, 21755.36it/s]
 71%|███████   | Sample : 2443/3450 [00:00<00:00, 21797.00it/s]
 81%|████████  | Sample : 2798/3450 [00:00<00:00, 21848.21it/s]
 91%|█████████▏| Sample : 3153/3450 [00:00<00:00, 21887.32it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21827.93it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 350/3450 [00:00<00:00, 21824.87it/s]
 20%|██        | Sample : 700/3450 [00:00<00:00, 21826.54it/s]
 31%|███       | Sample : 1053/3450 [00:00<00:00, 21888.69it/s]
 41%|████      | Sample : 1407/3450 [00:00<00:00, 21941.18it/s]
 50%|█████     | Sample : 1733/3450 [00:00<00:00, 21585.46it/s]
 60%|██████    | Sample : 2084/3450 [00:00<00:00, 21641.21it/s]
 71%|███████   | Sample : 2435/3450 [00:00<00:00, 21681.50it/s]
 81%|████████  | Sample : 2787/3450 [00:00<00:00, 21722.53it/s]
 91%|█████████ | Sample : 3136/3450 [00:00<00:00, 21732.26it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21746.97it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|▉         | Sample : 338/3450 [00:00<00:00, 21082.86it/s]
 20%|█▉        | Sample : 681/3450 [00:00<00:00, 21248.95it/s]
 30%|██▉       | Sample : 1028/3450 [00:00<00:00, 21387.67it/s]
 40%|████      | Sample : 1383/3450 [00:00<00:00, 21593.35it/s]
 50%|█████     | Sample : 1737/3450 [00:00<00:00, 21710.12it/s]
 60%|██████    | Sample : 2082/3450 [00:00<00:00, 21680.15it/s]
 71%|███████   | Sample : 2435/3450 [00:00<00:00, 21738.67it/s]
 81%|████████  | Sample : 2782/3450 [00:00<00:00, 21726.17it/s]
 91%|█████████ | Sample : 3130/3450 [00:00<00:00, 21728.51it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21707.08it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 349/3450 [00:00<00:00, 21773.85it/s]
 20%|██        | Sample : 702/3450 [00:00<00:00, 21894.81it/s]
 29%|██▊       | Sample : 991/3450 [00:00<00:00, 20542.84it/s]
 39%|███▉      | Sample : 1339/3450 [00:00<00:00, 20865.27it/s]
 49%|████▉     | Sample : 1685/3450 [00:00<00:00, 21022.61it/s]
 59%|█████▊    | Sample : 2024/3450 [00:00<00:00, 21046.71it/s]
 69%|██████▊   | Sample : 2371/3450 [00:00<00:00, 21141.86it/s]
 77%|███████▋  | Sample : 2669/3450 [00:00<00:00, 20763.53it/s]
 88%|████████▊ | Sample : 3021/3450 [00:00<00:00, 20929.78it/s]
 98%|█████████▊| Sample : 3375/3450 [00:00<00:00, 21073.14it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21042.15it/s]

Visualize the effects of regularization#

Above we fit a mne.decoding.ReceptiveField model for one of many values for the ridge regularization parameter. Here we will plot the model score as well as the model coefficients for each value, in order to visualize how coefficients change with different levels of regularization. These issues as well as the STRF pipeline are described in detail in [2][3][4].

# Plot model score for each ridge parameter
fig = plt.figure(figsize=(10, 4), layout="constrained")
ax = plt.subplot2grid([2, len(alphas)], [1, 0], 1, len(alphas))
ax.plot(np.arange(len(alphas)), scores, marker="o", color="r")
ax.annotate(
    "Best parameter",
    (ix_best_alpha, scores[ix_best_alpha]),
    (ix_best_alpha, scores[ix_best_alpha] - 0.1),
    arrowprops={"arrowstyle": "->"},
)
plt.xticks(np.arange(len(alphas)), ["%.0e" % ii for ii in alphas])
ax.set(
    xlabel="Ridge regularization value",
    ylabel="Score ($R^2$)",
    xlim=[-0.4, len(alphas) - 0.6],
)

# Plot the STRF of each ridge parameter
for ii, (rf, i_alpha) in enumerate(zip(models, alphas)):
    ax = plt.subplot2grid([2, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    plt.xticks([], [])
    plt.yticks([], [])
fig.suptitle("Model coefficients / scores for many ridge parameters", y=1)
Model coefficients / scores for many ridge parameters

Using different regularization types#

In addition to the standard ridge regularization, the mne.decoding.TimeDelayingRidge class also exposes Laplacian regularization term as:

\[\begin{split}\left[\begin{matrix} 1 & -1 & & & & \\ -1 & 2 & -1 & & & \\ & -1 & 2 & -1 & & \\ & & \ddots & \ddots & \ddots & \\ & & & -1 & 2 & -1 \\ & & & & -1 & 1\end{matrix}\right]\end{split}\]

This imposes a smoothness constraint of nearby time samples and/or features. Quoting [1] :

Tikhonov [identity] regularization (Equation 5) reduces overfitting by smoothing the TRF estimate in a way that is insensitive to the amplitude of the signal of interest. However, the Laplacian approach (Equation 6) reduces off-sample error whilst preserving signal amplitude (Lalor et al., 2006). As a result, this approach usually leads to an improved estimate of the system’s response (as indexed by MSE) compared to Tikhonov regularization.

scores_lap = np.zeros_like(alphas)
models_lap = []
for ii, alpha in enumerate(alphas):
    estimator = TimeDelayingRidge(tmin, tmax, sfreq, reg_type="laplacian", alpha=alpha)
    rf = ReceptiveField(tmin, tmax, sfreq, freqs, estimator=estimator)
    rf.fit(X_train, y_train)

    # Now make predictions about the model output, given input stimuli.
    scores_lap[ii] = rf.score(X_test, y_test).item()
    models_lap.append(rf)

ix_best_alpha_lap = np.argmax(scores_lap)
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
  5%|▌         | Sample : 177/3450 [00:00<00:00, 11057.21it/s]
 11%|█         | Sample : 371/3450 [00:00<00:00, 11570.62it/s]
 20%|█▉        | Sample : 682/3450 [00:00<00:00, 14307.08it/s]
 29%|██▉       | Sample : 1001/3450 [00:00<00:00, 15820.69it/s]
 38%|███▊      | Sample : 1325/3450 [00:00<00:00, 16787.67it/s]
 48%|████▊     | Sample : 1648/3450 [00:00<00:00, 17423.16it/s]
 57%|█████▋    | Sample : 1976/3450 [00:00<00:00, 17930.80it/s]
 68%|██████▊   | Sample : 2331/3450 [00:00<00:00, 18556.22it/s]
 78%|███████▊  | Sample : 2688/3450 [00:00<00:00, 19060.45it/s]
 87%|████████▋ | Sample : 3018/3450 [00:00<00:00, 19251.01it/s]
 97%|█████████▋| Sample : 3346/3450 [00:00<00:00, 19393.99it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 19040.46it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|▉         | Sample : 332/3450 [00:00<00:00, 20717.54it/s]
 20%|██        | Sample : 691/3450 [00:00<00:00, 21559.86it/s]
 30%|███       | Sample : 1048/3450 [00:00<00:00, 21801.20it/s]
 41%|████      | Sample : 1409/3450 [00:00<00:00, 21994.09it/s]
 51%|█████▏    | Sample : 1773/3450 [00:00<00:00, 22159.37it/s]
 62%|██████▏   | Sample : 2138/3450 [00:00<00:00, 22273.62it/s]
 73%|███████▎  | Sample : 2509/3450 [00:00<00:00, 22422.51it/s]
 83%|████████▎ | Sample : 2877/3450 [00:00<00:00, 22503.58it/s]
 94%|█████████▍| Sample : 3248/3450 [00:00<00:00, 22588.69it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 22536.47it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 361/3450 [00:00<00:00, 22503.77it/s]
 21%|██        | Sample : 727/3450 [00:00<00:00, 22662.06it/s]
 32%|███▏      | Sample : 1097/3450 [00:00<00:00, 22813.11it/s]
 42%|████▏     | Sample : 1460/3450 [00:00<00:00, 22767.24it/s]
 53%|█████▎    | Sample : 1829/3450 [00:00<00:00, 22822.48it/s]
 64%|██████▎   | Sample : 2194/3450 [00:00<00:00, 22811.36it/s]
 74%|███████▍  | Sample : 2561/3450 [00:00<00:00, 22828.01it/s]
 85%|████████▍ | Sample : 2929/3450 [00:00<00:00, 22846.54it/s]
 96%|█████████▌| Sample : 3296/3450 [00:00<00:00, 22857.57it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 22822.27it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 361/3450 [00:00<00:00, 22517.16it/s]
 21%|██        | Sample : 725/3450 [00:00<00:00, 22634.00it/s]
 32%|███▏      | Sample : 1089/3450 [00:00<00:00, 22658.89it/s]
 42%|████▏     | Sample : 1454/3450 [00:00<00:00, 22696.33it/s]
 53%|█████▎    | Sample : 1821/3450 [00:00<00:00, 22744.18it/s]
 63%|██████▎   | Sample : 2180/3450 [00:00<00:00, 22680.99it/s]
 74%|███████▎  | Sample : 2544/3450 [00:00<00:00, 22684.02it/s]
 84%|████████▍ | Sample : 2907/3450 [00:00<00:00, 22677.81it/s]
 95%|█████████▍| Sample : 3272/3450 [00:00<00:00, 22687.82it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 22669.36it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 358/3450 [00:00<00:00, 22330.03it/s]
 21%|██        | Sample : 718/3450 [00:00<00:00, 22398.45it/s]
 31%|███▏      | Sample : 1079/3450 [00:00<00:00, 22454.12it/s]
 42%|████▏     | Sample : 1441/3450 [00:00<00:00, 22488.57it/s]
 52%|█████▏    | Sample : 1800/3450 [00:00<00:00, 22468.05it/s]
 63%|██████▎   | Sample : 2161/3450 [00:00<00:00, 22484.14it/s]
 73%|███████▎  | Sample : 2520/3450 [00:00<00:00, 22473.08it/s]
 83%|████████▎ | Sample : 2880/3450 [00:00<00:00, 22468.82it/s]
 94%|█████████▍| Sample : 3246/3450 [00:00<00:00, 22517.38it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 22505.83it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 359/3450 [00:00<00:00, 22375.11it/s]
 21%|██        | Sample : 717/3450 [00:00<00:00, 22368.88it/s]
 31%|███       | Sample : 1075/3450 [00:00<00:00, 22362.02it/s]
 42%|████▏     | Sample : 1435/3450 [00:00<00:00, 22390.72it/s]
 52%|█████▏    | Sample : 1799/3450 [00:00<00:00, 22461.75it/s]
 63%|██████▎   | Sample : 2161/3450 [00:00<00:00, 22482.35it/s]
 73%|███████▎  | Sample : 2525/3450 [00:00<00:00, 22524.81it/s]
 83%|████████▎ | Sample : 2873/3450 [00:00<00:00, 22402.22it/s]
 92%|█████████▏| Sample : 3178/3450 [00:00<00:00, 21949.19it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 22057.75it/s]
Fitting 15 epochs, 20 channels

  0%|          | Sample : 0/3450 [00:00<?,       ?it/s]
 10%|█         | Sample : 352/3450 [00:00<00:00, 21954.16it/s]
 20%|██        | Sample : 704/3450 [00:00<00:00, 21952.65it/s]
 30%|███       | Sample : 1052/3450 [00:00<00:00, 21874.73it/s]
 41%|████      | Sample : 1402/3450 [00:00<00:00, 21870.93it/s]
 51%|█████     | Sample : 1753/3450 [00:00<00:00, 21882.88it/s]
 61%|██████    | Sample : 2101/3450 [00:00<00:00, 21848.12it/s]
 71%|███████   | Sample : 2451/3450 [00:00<00:00, 21851.86it/s]
 81%|████████▏ | Sample : 2807/3450 [00:00<00:00, 21902.46it/s]
 92%|█████████▏| Sample : 3158/3450 [00:00<00:00, 21905.20it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21978.32it/s]

Compare model performance#

Below we visualize the model performance of each regularization method (ridge vs. Laplacian) for different levels of alpha. As you can see, the Laplacian method performs better in general, because it imposes a smoothness constraint along the time and feature dimensions of the coefficients. This matches the “true” receptive field structure and results in a better model fit.

fig = plt.figure(figsize=(10, 6), layout="constrained")
ax = plt.subplot2grid([3, len(alphas)], [2, 0], 1, len(alphas))
ax.plot(np.arange(len(alphas)), scores_lap, marker="o", color="r")
ax.plot(np.arange(len(alphas)), scores, marker="o", color="0.5", ls=":")
ax.annotate(
    "Best Laplacian",
    (ix_best_alpha_lap, scores_lap[ix_best_alpha_lap]),
    (ix_best_alpha_lap, scores_lap[ix_best_alpha_lap] - 0.1),
    arrowprops={"arrowstyle": "->"},
)
ax.annotate(
    "Best Ridge",
    (ix_best_alpha, scores[ix_best_alpha]),
    (ix_best_alpha, scores[ix_best_alpha] - 0.1),
    arrowprops={"arrowstyle": "->"},
)
plt.xticks(np.arange(len(alphas)), ["%.0e" % ii for ii in alphas])
ax.set(
    xlabel="Laplacian regularization value",
    ylabel="Score ($R^2$)",
    xlim=[-0.4, len(alphas) - 0.6],
)

# Plot the STRF of each ridge parameter
xlim = times[[0, -1]]
for ii, (rf_lap, rf, i_alpha) in enumerate(zip(models_lap, models, alphas)):
    ax = plt.subplot2grid([3, len(alphas)], [0, ii], 1, 1)
    ax.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel="Laplacian")
    ax = plt.subplot2grid([3, len(alphas)], [1, ii], 1, 1)
    ax.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
    ax.set(xticks=[], yticks=[], xlim=xlim)
    if ii == 0:
        ax.set(ylabel="Ridge")
fig.suptitle("Model coefficients / scores for laplacian regularization", y=1)
Model coefficients / scores for laplacian regularization

Plot the original STRF, and the one that we recovered with modeling.

rf = models[ix_best_alpha]
rf_lap = models_lap[ix_best_alpha_lap]
_, (ax1, ax2, ax3) = plt.subplots(
    1,
    3,
    figsize=(9, 3),
    sharey=True,
    sharex=True,
    layout="constrained",
)
ax1.pcolormesh(delays_sec, freqs, weights, **kwargs)
ax2.pcolormesh(times, rf.feature_names, rf.coef_[0], **kwargs)
ax3.pcolormesh(times, rf_lap.feature_names, rf_lap.coef_[0], **kwargs)
ax1.set_title("Original STRF")
ax2.set_title("Best Ridge STRF")
ax3.set_title("Best Laplacian STRF")
plt.setp([iax.get_xticklabels() for iax in [ax1, ax2, ax3]], rotation=45)
Original STRF, Best Ridge STRF, Best Laplacian STRF

References#

Total running time of the script: (0 minutes 25.922 seconds)

Estimated memory usage: 9 MB

Gallery generated by Sphinx-Gallery