Note
Go to the end to download the full example code
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)
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.)",
)
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"])
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
0%| | Sample : 1/3450 [00:08<8:08:04, 8.49s/it]
11%|█ | Sample : 371/3450 [00:08<01:07, 45.90it/s]
22%|██▏ | Sample : 749/3450 [00:08<00:28, 94.93it/s]
29%|██▉ | Sample : 1014/3450 [00:08<00:18, 130.90it/s]
37%|███▋ | Sample : 1279/3450 [00:08<00:12, 168.59it/s]
48%|████▊ | Sample : 1648/3450 [00:08<00:08, 223.73it/s]
58%|█████▊ | Sample : 2004/3450 [00:08<00:05, 279.44it/s]
69%|██████▉ | Sample : 2380/3450 [00:08<00:03, 341.09it/s]
80%|████████ | Sample : 2761/3450 [00:08<00:01, 406.49it/s]
89%|████████▊ | Sample : 3057/3450 [00:08<00:00, 459.42it/s]
95%|█████████▌| Sample : 3287/3450 [00:08<00:00, 502.13it/s]
100%|██████████| Sample : 3450/3450 [00:08<00:00, 398.46it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|█ | Sample : 371/3450 [00:00<00:00, 23187.11it/s]
22%|██▏ | Sample : 746/3450 [00:00<00:00, 23301.60it/s]
31%|███ | Sample : 1063/3450 [00:00<00:00, 22066.56it/s]
37%|███▋ | Sample : 1288/3450 [00:00<00:00, 19909.51it/s]
47%|████▋ | Sample : 1613/3450 [00:00<00:00, 19993.98it/s]
58%|█████▊ | Sample : 1988/3450 [00:00<00:00, 20641.29it/s]
68%|██████▊ | Sample : 2354/3450 [00:00<00:00, 21007.34it/s]
79%|███████▉ | Sample : 2729/3450 [00:00<00:00, 21361.42it/s]
89%|████████▉ | Sample : 3074/3450 [00:00<00:00, 21385.40it/s]
96%|█████████▌| Sample : 3305/3450 [00:00<00:00, 20516.80it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 20691.38it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|█ | Sample : 373/3450 [00:00<00:00, 23267.03it/s]
21%|██▏ | Sample : 740/3450 [00:00<00:00, 23072.81it/s]
32%|███▏ | Sample : 1120/3450 [00:00<00:00, 23303.32it/s]
42%|████▏ | Sample : 1441/3450 [00:00<00:00, 22412.70it/s]
49%|████▊ | Sample : 1680/3450 [00:00<00:00, 20759.90it/s]
59%|█████▉ | Sample : 2044/3450 [00:00<00:00, 21109.44it/s]
70%|███████ | Sample : 2415/3450 [00:00<00:00, 21450.96it/s]
81%|████████ | Sample : 2781/3450 [00:00<00:00, 21657.74it/s]
91%|█████████▏| Sample : 3156/3450 [00:00<00:00, 21896.59it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21839.14it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
10%|▉ | Sample : 328/3450 [00:00<00:00, 20494.46it/s]
18%|█▊ | Sample : 613/3450 [00:00<00:00, 19116.92it/s]
28%|██▊ | Sample : 966/3450 [00:00<00:00, 20147.79it/s]
39%|███▉ | Sample : 1341/3450 [00:00<00:00, 21021.78it/s]
48%|████▊ | Sample : 1668/3450 [00:00<00:00, 20875.81it/s]
56%|█████▌ | Sample : 1915/3450 [00:00<00:00, 19846.62it/s]
66%|██████▋ | Sample : 2288/3450 [00:00<00:00, 20412.93it/s]
77%|███████▋ | Sample : 2652/3450 [00:00<00:00, 20754.57it/s]
87%|████████▋ | Sample : 3009/3450 [00:00<00:00, 20964.96it/s]
97%|█████████▋| Sample : 3341/3450 [00:00<00:00, 20932.30it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 20865.29it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
7%|▋ | Sample : 232/3450 [00:00<00:00, 14498.03it/s]
16%|█▌ | Sample : 548/3450 [00:00<00:00, 16978.64it/s]
22%|██▏ | Sample : 750/3450 [00:00<00:00, 15454.02it/s]
28%|██▊ | Sample : 981/3450 [00:00<00:00, 15174.57it/s]
35%|███▌ | Sample : 1209/3450 [00:00<00:00, 14966.41it/s]
42%|████▏ | Sample : 1433/3450 [00:00<00:00, 14780.62it/s]
48%|████▊ | Sample : 1655/3450 [00:00<00:00, 14629.12it/s]
55%|█████▍ | Sample : 1887/3450 [00:00<00:00, 14608.32it/s]
61%|██████▏ | Sample : 2115/3450 [00:00<00:00, 14559.15it/s]
68%|██████▊ | Sample : 2343/3450 [00:00<00:00, 14511.22it/s]
75%|███████▍ | Sample : 2574/3450 [00:00<00:00, 14500.67it/s]
81%|████████▏ | Sample : 2805/3450 [00:00<00:00, 14493.00it/s]
88%|████████▊ | Sample : 3034/3450 [00:00<00:00, 14467.85it/s]
95%|█████████▍| Sample : 3264/3450 [00:00<00:00, 14455.77it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 14530.88it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
8%|▊ | Sample : 288/3450 [00:00<00:00, 17992.19it/s]
19%|█▉ | Sample : 667/3450 [00:00<00:00, 20897.05it/s]
26%|██▋ | Sample : 910/3450 [00:00<00:00, 18892.32it/s]
36%|███▌ | Sample : 1238/3450 [00:00<00:00, 19312.68it/s]
47%|████▋ | Sample : 1613/3450 [00:00<00:00, 20216.94it/s]
58%|█████▊ | Sample : 1990/3450 [00:00<00:00, 20841.22it/s]
69%|██████▊ | Sample : 2370/3450 [00:00<00:00, 21314.16it/s]
80%|███████▉ | Sample : 2750/3450 [00:00<00:00, 21671.64it/s]
88%|████████▊ | Sample : 3027/3450 [00:00<00:00, 21080.56it/s]
96%|█████████▋| Sample : 3321/3450 [00:00<00:00, 20743.11it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 20799.97it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|█ | Sample : 371/3450 [00:00<00:00, 23146.06it/s]
22%|██▏ | Sample : 747/3450 [00:00<00:00, 23296.44it/s]
33%|███▎ | Sample : 1127/3450 [00:00<00:00, 23444.32it/s]
40%|████ | Sample : 1391/3450 [00:00<00:00, 21559.39it/s]
49%|████▉ | Sample : 1694/3450 [00:00<00:00, 20980.70it/s]
60%|█████▉ | Sample : 2065/3450 [00:00<00:00, 21394.19it/s]
70%|███████ | Sample : 2431/3450 [00:00<00:00, 21631.85it/s]
81%|████████▏ | Sample : 2806/3450 [00:00<00:00, 21892.95it/s]
92%|█████████▏| Sample : 3173/3450 [00:00<00:00, 22031.07it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21740.80it/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)
Using different regularization types#
In addition to the standard ridge regularization, the
mne.decoding.TimeDelayingRidge
class also exposes
Laplacian regularization
term as:
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]
10%|█ | Sample : 355/3450 [00:00<00:00, 22158.73it/s]
21%|██ | Sample : 723/3450 [00:00<00:00, 22571.07it/s]
28%|██▊ | Sample : 960/3450 [00:00<00:00, 19849.06it/s]
38%|███▊ | Sample : 1301/3450 [00:00<00:00, 20240.34it/s]
49%|████▊ | Sample : 1676/3450 [00:00<00:00, 20935.06it/s]
59%|█████▉ | Sample : 2041/3450 [00:00<00:00, 21288.43it/s]
70%|██████▉ | Sample : 2410/3450 [00:00<00:00, 21579.05it/s]
80%|████████ | Sample : 2776/3450 [00:00<00:00, 21765.04it/s]
88%|████████▊ | Sample : 3043/3450 [00:00<00:00, 21074.16it/s]
97%|█████████▋| Sample : 3339/3450 [00:00<00:00, 20753.34it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 20885.92it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|█ | Sample : 373/3450 [00:00<00:00, 23309.33it/s]
22%|██▏ | Sample : 743/3450 [00:00<00:00, 23186.97it/s]
30%|███ | Sample : 1038/3450 [00:00<00:00, 21511.74it/s]
38%|███▊ | Sample : 1321/3450 [00:00<00:00, 20480.77it/s]
49%|████▉ | Sample : 1691/3450 [00:00<00:00, 21056.69it/s]
60%|█████▉ | Sample : 2066/3450 [00:00<00:00, 21498.84it/s]
71%|███████ | Sample : 2437/3450 [00:00<00:00, 21777.30it/s]
82%|████████▏ | Sample : 2814/3450 [00:00<00:00, 22036.58it/s]
90%|█████████ | Sample : 3118/3450 [00:00<00:00, 21617.03it/s]
99%|█████████▊| Sample : 3399/3450 [00:00<00:00, 21108.85it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21221.97it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|▌ | Sample : 193/3450 [00:00<00:00, 12015.57it/s]
11%|█ | Sample : 385/3450 [00:00<00:00, 11986.74it/s]
17%|█▋ | Sample : 578/3450 [00:00<00:00, 11999.97it/s]
23%|██▎ | Sample : 796/3450 [00:00<00:00, 12429.01it/s]
33%|███▎ | Sample : 1122/3450 [00:00<00:00, 14175.95it/s]
43%|████▎ | Sample : 1498/3450 [00:00<00:00, 15929.33it/s]
54%|█████▍ | Sample : 1877/3450 [00:00<00:00, 17209.00it/s]
65%|██████▌ | Sample : 2255/3450 [00:00<00:00, 18157.08it/s]
76%|███████▋ | Sample : 2633/3450 [00:00<00:00, 18889.94it/s]
85%|████████▍ | Sample : 2926/3450 [00:00<00:00, 18815.91it/s]
93%|█████████▎| Sample : 3220/3450 [00:00<00:00, 18762.57it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 18523.21it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|█ | Sample : 367/3450 [00:00<00:00, 22887.32it/s]
22%|██▏ | Sample : 744/3450 [00:00<00:00, 23210.49it/s]
32%|███▏ | Sample : 1109/3450 [00:00<00:00, 23069.81it/s]
39%|███▉ | Sample : 1350/3450 [00:00<00:00, 20893.82it/s]
49%|████▉ | Sample : 1706/3450 [00:00<00:00, 21185.58it/s]
60%|██████ | Sample : 2083/3450 [00:00<00:00, 21626.84it/s]
71%|███████▏ | Sample : 2461/3450 [00:00<00:00, 21949.45it/s]
82%|████████▏ | Sample : 2838/3450 [00:00<00:00, 22184.17it/s]
93%|█████████▎| Sample : 3221/3450 [00:00<00:00, 22385.89it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 21737.24it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|▌ | Sample : 193/3450 [00:00<00:00, 12059.42it/s]
11%|█ | Sample : 376/3450 [00:00<00:00, 11731.46it/s]
16%|█▋ | Sample : 568/3450 [00:00<00:00, 11823.81it/s]
22%|██▏ | Sample : 763/3450 [00:00<00:00, 11916.95it/s]
29%|██▉ | Sample : 996/3450 [00:00<00:00, 12500.10it/s]
39%|███▉ | Sample : 1346/3450 [00:00<00:00, 14267.49it/s]
50%|████▉ | Sample : 1717/3450 [00:00<00:00, 15739.08it/s]
61%|██████ | Sample : 2091/3450 [00:00<00:00, 16868.76it/s]
71%|███████▏ | Sample : 2463/3450 [00:00<00:00, 17729.66it/s]
82%|████████▏ | Sample : 2831/3450 [00:00<00:00, 18381.00it/s]
89%|████████▉ | Sample : 3080/3450 [00:00<00:00, 18050.89it/s]
96%|█████████▌| Sample : 3303/3450 [00:00<00:00, 17595.73it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 16965.94it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|▋ | Sample : 224/3450 [00:00<00:00, 13938.49it/s]
13%|█▎ | Sample : 445/3450 [00:00<00:00, 13861.32it/s]
19%|█▉ | Sample : 657/3450 [00:00<00:00, 13636.41it/s]
26%|██▌ | Sample : 896/3450 [00:00<00:00, 13980.34it/s]
35%|███▌ | Sample : 1213/3450 [00:00<00:00, 15259.43it/s]
45%|████▍ | Sample : 1540/3450 [00:00<00:00, 16233.56it/s]
54%|█████▍ | Sample : 1866/3450 [00:00<00:00, 16916.65it/s]
64%|██████▎ | Sample : 2194/3450 [00:00<00:00, 17439.85it/s]
72%|███████▏ | Sample : 2489/3450 [00:00<00:00, 17569.56it/s]
80%|███████▉ | Sample : 2750/3450 [00:00<00:00, 17412.30it/s]
90%|█████████ | Sample : 3118/3450 [00:00<00:00, 18057.20it/s]
99%|█████████▉| Sample : 3424/3450 [00:00<00:00, 18168.88it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 17786.17it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
10%|█ | Sample : 351/3450 [00:00<00:00, 21906.44it/s]
19%|█▊ | Sample : 640/3450 [00:00<00:00, 19930.29it/s]
25%|██▌ | Sample : 863/3450 [00:00<00:00, 17805.85it/s]
35%|███▌ | Sample : 1217/3450 [00:00<00:00, 18960.72it/s]
46%|████▋ | Sample : 1599/3450 [00:00<00:00, 20043.57it/s]
57%|█████▋ | Sample : 1967/3450 [00:00<00:00, 20592.01it/s]
68%|██████▊ | Sample : 2345/3450 [00:00<00:00, 21090.15it/s]
79%|███████▊ | Sample : 2710/3450 [00:00<00:00, 21337.17it/s]
85%|████████▌ | Sample : 2944/3450 [00:00<00:00, 20418.23it/s]
95%|█████████▍| Sample : 3267/3450 [00:00<00:00, 20385.45it/s]
100%|██████████| Sample : 3450/3450 [00:00<00:00, 20461.78it/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)
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)
References#
Total running time of the script: (0 minutes 28.510 seconds)
Estimated memory usage: 10 MB