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
import numpy as np
import matplotlib.pyplot as plt
import mne
from mne.decoding import ReceptiveField, TimeDelayingRidge
from scipy.stats import multivariate_normal
from scipy.io import loadmat
from sklearn.preprocessing import scale
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 = [.1, 500]
means_low = [.2, 2500]
cov = [[.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()
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)
plt.autoscale(tight=True)
mne.viz.tight_layout()
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 = .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)
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.)')
mne.viz.tight_layout()
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)
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)
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)
plt.autoscale(tight=True)
mne.viz.tight_layout()
# 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=.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'])
plt.autoscale(tight=True)
mne.viz.tight_layout()
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
0%| | Sample : 1/3450 [00:07<7:28:29, 7.80s/it]
10%|9 | Sample : 331/3450 [00:07<01:10, 44.55it/s]
16%|#5 | Sample : 546/3450 [00:07<00:38, 74.85it/s]
22%|##2 | Sample : 762/3450 [00:07<00:25, 106.74it/s]
29%|##8 | Sample : 995/3450 [00:07<00:17, 142.80it/s]
36%|###5 | Sample : 1230/3450 [00:07<00:12, 180.89it/s]
44%|####3 | Sample : 1505/3450 [00:07<00:08, 227.64it/s]
51%|#####1 | Sample : 1764/3450 [00:07<00:06, 273.69it/s]
61%|###### | Sample : 2100/3450 [00:07<00:04, 336.45it/s]
71%|####### | Sample : 2434/3450 [00:07<00:02, 401.70it/s]
80%|######## | Sample : 2760/3450 [00:07<00:01, 468.27it/s]
90%|########9 | Sample : 3096/3450 [00:07<00:00, 540.06it/s]
100%|#########9| Sample : 3441/3450 [00:07<00:00, 617.15it/s]
100%|##########| Sample : 3450/3450 [00:07<00:00, 431.50it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
9%|8 | Sample : 306/3450 [00:00<00:00, 19122.97it/s]
17%|#6 | Sample : 573/3450 [00:00<00:00, 17856.73it/s]
24%|##4 | Sample : 832/3450 [00:00<00:00, 17260.84it/s]
31%|### | Sample : 1068/3450 [00:00<00:00, 16565.27it/s]
37%|###7 | Sample : 1281/3450 [00:00<00:00, 15832.00it/s]
43%|####3 | Sample : 1490/3450 [00:00<00:00, 15304.32it/s]
49%|####9 | Sample : 1703/3450 [00:00<00:00, 14971.78it/s]
55%|#####5 | Sample : 1914/3450 [00:00<00:00, 14704.70it/s]
62%|######1 | Sample : 2122/3450 [00:00<00:00, 14467.80it/s]
68%|######7 | Sample : 2334/3450 [00:00<00:00, 14311.29it/s]
74%|#######3 | Sample : 2542/3450 [00:00<00:00, 14155.73it/s]
80%|#######9 | Sample : 2749/3450 [00:00<00:00, 14021.92it/s]
86%|########5 | Sample : 2961/3450 [00:00<00:00, 13936.08it/s]
92%|#########1| Sample : 3163/3450 [00:00<00:00, 13808.41it/s]
98%|#########7| Sample : 3378/3450 [00:00<00:00, 13772.32it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 14134.66it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
9%|9 | Sample : 324/3450 [00:00<00:00, 20226.15it/s]
16%|#5 | Sample : 537/3450 [00:00<00:00, 16644.19it/s]
22%|##1 | Sample : 744/3450 [00:00<00:00, 15330.53it/s]
27%|##7 | Sample : 938/3450 [00:00<00:00, 14454.03it/s]
33%|###3 | Sample : 1147/3450 [00:00<00:00, 14138.76it/s]
39%|###9 | Sample : 1357/3450 [00:00<00:00, 13947.58it/s]
45%|####5 | Sample : 1562/3450 [00:00<00:00, 13754.81it/s]
51%|#####1 | Sample : 1760/3450 [00:00<00:00, 13545.62it/s]
57%|#####7 | Sample : 1971/3450 [00:00<00:00, 13497.29it/s]
63%|######3 | Sample : 2184/3450 [00:00<00:00, 13468.61it/s]
70%|######9 | Sample : 2399/3450 [00:00<00:00, 13460.46it/s]
76%|#######5 | Sample : 2611/3450 [00:00<00:00, 13436.52it/s]
82%|########1 | Sample : 2820/3450 [00:00<00:00, 13395.36it/s]
88%|########7 | Sample : 3020/3450 [00:00<00:00, 13305.60it/s]
93%|#########3| Sample : 3220/3450 [00:00<00:00, 13228.24it/s]
99%|#########9| Sample : 3432/3450 [00:00<00:00, 13226.66it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 13354.92it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|5 | Sample : 198/3450 [00:00<00:00, 12372.39it/s]
12%|#1 | Sample : 405/3450 [00:00<00:00, 12649.68it/s]
18%|#7 | Sample : 615/3450 [00:00<00:00, 12815.45it/s]
27%|##7 | Sample : 948/3450 [00:00<00:00, 14964.20it/s]
37%|###7 | Sample : 1285/3450 [00:00<00:00, 16310.39it/s]
47%|####7 | Sample : 1630/3450 [00:00<00:00, 17294.80it/s]
57%|#####7 | Sample : 1967/3450 [00:00<00:00, 17917.22it/s]
65%|######5 | Sample : 2252/3450 [00:00<00:00, 17897.59it/s]
73%|#######3 | Sample : 2530/3450 [00:00<00:00, 17825.18it/s]
82%|########2 | Sample : 2837/3450 [00:00<00:00, 17989.48it/s]
92%|#########1| Sample : 3159/3450 [00:00<00:00, 18236.19it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18002.22it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
8%|8 | Sample : 292/3450 [00:00<00:00, 18236.38it/s]
16%|#6 | Sample : 557/3450 [00:00<00:00, 17371.37it/s]
24%|##4 | Sample : 834/3450 [00:00<00:00, 17336.70it/s]
32%|###2 | Sample : 1118/3450 [00:00<00:00, 17446.66it/s]
41%|#### | Sample : 1404/3450 [00:00<00:00, 17529.25it/s]
49%|####8 | Sample : 1685/3450 [00:00<00:00, 17529.16it/s]
58%|#####7 | Sample : 1994/3450 [00:00<00:00, 17822.20it/s]
67%|######7 | Sample : 2328/3450 [00:00<00:00, 18265.09it/s]
76%|#######6 | Sample : 2622/3450 [00:00<00:00, 18278.20it/s]
85%|########5 | Sample : 2934/3450 [00:00<00:00, 18428.37it/s]
95%|#########4| Sample : 3277/3450 [00:00<00:00, 18773.68it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18708.38it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
9%|8 | Sample : 301/3450 [00:00<00:00, 18780.56it/s]
16%|#6 | Sample : 559/3450 [00:00<00:00, 17398.32it/s]
25%|##4 | Sample : 849/3450 [00:00<00:00, 17638.36it/s]
33%|###3 | Sample : 1151/3450 [00:00<00:00, 17914.48it/s]
41%|####1 | Sample : 1425/3450 [00:00<00:00, 17722.65it/s]
48%|####7 | Sample : 1650/3450 [00:00<00:00, 17028.24it/s]
57%|#####7 | Sample : 1969/3450 [00:00<00:00, 17494.46it/s]
65%|######4 | Sample : 2231/3450 [00:00<00:00, 17325.44it/s]
72%|#######2 | Sample : 2500/3450 [00:00<00:00, 17252.11it/s]
80%|######## | Sample : 2769/3450 [00:00<00:00, 17195.50it/s]
88%|########8 | Sample : 3039/3450 [00:00<00:00, 17151.73it/s]
95%|#########4| Sample : 3269/3450 [00:00<00:00, 16850.03it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 17001.38it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
8%|7 | Sample : 264/3450 [00:00<00:00, 16494.80it/s]
17%|#6 | Sample : 572/3450 [00:00<00:00, 17901.75it/s]
25%|##5 | Sample : 865/3450 [00:00<00:00, 18015.58it/s]
34%|###3 | Sample : 1165/3450 [00:00<00:00, 18211.86it/s]
43%|####3 | Sample : 1493/3450 [00:00<00:00, 18705.42it/s]
52%|#####1 | Sample : 1778/3450 [00:00<00:00, 18532.70it/s]
60%|#####9 | Sample : 2060/3450 [00:00<00:00, 18377.07it/s]
68%|######7 | Sample : 2336/3450 [00:00<00:00, 18207.86it/s]
76%|#######6 | Sample : 2634/3450 [00:00<00:00, 18263.23it/s]
84%|########4 | Sample : 2906/3450 [00:00<00:00, 18104.71it/s]
94%|#########3| Sample : 3230/3450 [00:00<00:00, 18346.02it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18470.41it/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))
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] - .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=[-.4, len(alphas) - .6])
mne.viz.tight_layout()
# 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([], [])
plt.autoscale(tight=True)
fig.suptitle('Model coefficients / scores for many ridge parameters', y=1)
mne.viz.tight_layout()
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)
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]
8%|8 | Sample : 287/3450 [00:00<00:00, 17898.26it/s]
14%|#4 | Sample : 498/3450 [00:00<00:00, 15484.93it/s]
24%|##4 | Sample : 844/3450 [00:00<00:00, 17631.88it/s]
34%|###4 | Sample : 1176/3450 [00:00<00:00, 18468.53it/s]
43%|####2 | Sample : 1467/3450 [00:00<00:00, 18403.24it/s]
49%|####8 | Sample : 1679/3450 [00:00<00:00, 17426.55it/s]
56%|#####5 | Sample : 1926/3450 [00:00<00:00, 17095.35it/s]
64%|######4 | Sample : 2218/3450 [00:00<00:00, 17253.84it/s]
72%|#######1 | Sample : 2471/3450 [00:00<00:00, 17054.11it/s]
81%|######## | Sample : 2784/3450 [00:00<00:00, 17365.74it/s]
91%|#########1| Sample : 3147/3450 [00:00<00:00, 17979.28it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18187.26it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
11%|# | Sample : 367/3450 [00:00<00:00, 22936.77it/s]
21%|## | Sample : 719/3450 [00:00<00:00, 22431.16it/s]
31%|###1 | Sample : 1080/3450 [00:00<00:00, 22456.76it/s]
41%|####1 | Sample : 1419/3450 [00:00<00:00, 22105.81it/s]
52%|#####1 | Sample : 1777/3450 [00:00<00:00, 22158.37it/s]
60%|###### | Sample : 2079/3450 [00:00<00:00, 21535.62it/s]
71%|####### | Sample : 2442/3450 [00:00<00:00, 21722.98it/s]
81%|######## | Sample : 2789/3450 [00:00<00:00, 21714.69it/s]
90%|######### | Sample : 3118/3450 [00:00<00:00, 21545.69it/s]
99%|#########8| Sample : 3399/3450 [00:00<00:00, 21049.84it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 21132.53it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
10%|# | Sample : 348/3450 [00:00<00:00, 21724.38it/s]
21%|## | Sample : 711/3450 [00:00<00:00, 22215.44it/s]
31%|###1 | Sample : 1072/3450 [00:00<00:00, 22333.07it/s]
41%|####1 | Sample : 1418/3450 [00:00<00:00, 22117.33it/s]
51%|##### | Sample : 1753/3450 [00:00<00:00, 21855.87it/s]
61%|###### | Sample : 2100/3450 [00:00<00:00, 21814.92it/s]
71%|#######1 | Sample : 2460/3450 [00:00<00:00, 21920.00it/s]
82%|########1 | Sample : 2828/3450 [00:00<00:00, 22076.11it/s]
92%|#########2| Sample : 3191/3450 [00:00<00:00, 22151.40it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 22023.48it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|5 | Sample : 193/3450 [00:00<00:00, 12026.10it/s]
11%|#1 | Sample : 394/3450 [00:00<00:00, 12278.65it/s]
17%|#7 | Sample : 588/3450 [00:00<00:00, 12223.04it/s]
23%|##2 | Sample : 785/3450 [00:00<00:00, 12238.52it/s]
29%|##9 | Sample : 1002/3450 [00:00<00:00, 12529.25it/s]
40%|###9 | Sample : 1373/3450 [00:00<00:00, 14535.83it/s]
50%|####9 | Sample : 1709/3450 [00:00<00:00, 15600.44it/s]
57%|#####6 | Sample : 1959/3450 [00:00<00:00, 15597.25it/s]
64%|######3 | Sample : 2196/3450 [00:00<00:00, 15488.63it/s]
71%|####### | Sample : 2441/3450 [00:00<00:00, 15460.61it/s]
78%|#######8 | Sample : 2707/3450 [00:00<00:00, 15592.26it/s]
86%|########6 | Sample : 2981/3450 [00:00<00:00, 15757.91it/s]
94%|#########4| Sample : 3258/3450 [00:00<00:00, 15912.04it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 15766.55it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|5 | Sample : 196/3450 [00:00<00:00, 12203.42it/s]
12%|#1 | Sample : 404/3450 [00:00<00:00, 12590.03it/s]
18%|#7 | Sample : 606/3450 [00:00<00:00, 12585.92it/s]
24%|##3 | Sample : 813/3450 [00:00<00:00, 12665.77it/s]
30%|### | Sample : 1036/3450 [00:00<00:00, 12939.09it/s]
40%|#### | Sample : 1397/3450 [00:00<00:00, 14748.38it/s]
51%|#####1 | Sample : 1766/3450 [00:00<00:00, 16119.45it/s]
62%|######1 | Sample : 2126/3450 [00:00<00:00, 17058.57it/s]
72%|#######2 | Sample : 2500/3450 [00:00<00:00, 17909.84it/s]
83%|########3 | Sample : 2864/3450 [00:00<00:00, 18508.96it/s]
93%|#########3| Sample : 3215/3450 [00:00<00:00, 18903.68it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18456.98it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|5 | Sample : 206/3450 [00:00<00:00, 12859.26it/s]
12%|#1 | Sample : 411/3450 [00:00<00:00, 12806.63it/s]
18%|#7 | Sample : 617/3450 [00:00<00:00, 12816.24it/s]
24%|##3 | Sample : 823/3450 [00:00<00:00, 12831.22it/s]
30%|### | Sample : 1048/3450 [00:00<00:00, 13099.09it/s]
41%|####1 | Sample : 1424/3450 [00:00<00:00, 15056.74it/s]
52%|#####1 | Sample : 1793/3450 [00:00<00:00, 16378.95it/s]
62%|######1 | Sample : 2137/3450 [00:00<00:00, 17129.64it/s]
72%|#######2 | Sample : 2488/3450 [00:00<00:00, 17778.34it/s]
82%|########1 | Sample : 2815/3450 [00:00<00:00, 18108.59it/s]
92%|#########2| Sample : 3177/3450 [00:00<00:00, 18630.52it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18028.53it/s]
Fitting 15 epochs, 20 channels
0%| | Sample : 0/3450 [00:00<?, ?it/s]
6%|5 | Sample : 197/3450 [00:00<00:00, 12251.86it/s]
11%|#1 | Sample : 389/3450 [00:00<00:00, 12099.30it/s]
17%|#6 | Sample : 581/3450 [00:00<00:00, 12045.81it/s]
22%|##2 | Sample : 773/3450 [00:00<00:00, 12026.32it/s]
28%|##8 | Sample : 970/3450 [00:00<00:00, 12086.33it/s]
39%|###8 | Sample : 1340/3450 [00:00<00:00, 14163.86it/s]
50%|####9 | Sample : 1708/3450 [00:00<00:00, 15622.42it/s]
60%|###### | Sample : 2081/3450 [00:00<00:00, 16761.03it/s]
71%|#######1 | Sample : 2450/3450 [00:00<00:00, 17607.02it/s]
82%|########1 | Sample : 2816/3450 [00:00<00:00, 18259.90it/s]
92%|#########2| Sample : 3191/3450 [00:00<00:00, 18856.33it/s]
100%|##########| Sample : 3450/3450 [00:00<00:00, 18368.61it/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))
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] - .1),
arrowprops={'arrowstyle': '->'})
ax.annotate('Best Ridge', (ix_best_alpha, scores[ix_best_alpha]),
(ix_best_alpha, scores[ix_best_alpha] - .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=[-.4, len(alphas) - .6])
mne.viz.tight_layout()
# 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)
mne.viz.tight_layout()
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)
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)
plt.autoscale(tight=True)
mne.viz.tight_layout()
References#
Total running time of the script: ( 0 minutes 26.129 seconds)
Estimated memory usage: 9 MB