Skip to content

Commit b176e20

Browse files
authored
Merge pull request #274 from rsagroup/demo_boot
Demo updates
2 parents c869390 + 89a3faa commit b176e20

File tree

7 files changed

+422
-138
lines changed

7 files changed

+422
-138
lines changed

demos/demo_bootstrap.ipynb

Lines changed: 293 additions & 57 deletions
Large diffs are not rendered by default.

demos/demo_dissimilarities.ipynb

Lines changed: 35 additions & 41 deletions
Large diffs are not rendered by default.

rsatoolbox/inference/evaluate.py

Lines changed: 13 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -144,17 +144,19 @@ def eval_dual_bootstrap(
144144
if use_correction and n_cv > 1:
145145
# we essentially project from the two points for 1 repetition and
146146
# for n_cv repetitions to infinitely many cv repetitions
147-
evals_mean = np.mean(np.mean(evaluations[eval_ok], -1), -1)
148-
evals_1 = np.mean(evaluations[eval_ok], -2)
149-
noise_ceil_mean = np.mean(noise_ceil[:, eval_ok], -1)
150-
noise_ceil_1 = noise_ceil[:, eval_ok]
151-
var_mean = np.cov(
152-
np.concatenate([evals_mean.T, noise_ceil_mean]))
153-
var_1 = []
154-
for i in range(n_cv):
155-
var_1.append(np.cov(np.concatenate([
156-
evals_1[:, :, i].T, noise_ceil_1[:, :, i]])))
157-
var_1 = np.mean(np.array(var_1), axis=0)
147+
evals_nonan = np.mean(np.mean(evaluations[eval_ok], -2), -2)
148+
evals_1 = np.mean(evaluations[eval_ok], -3)
149+
noise_ceil_nonan = np.mean(
150+
noise_ceil[:, eval_ok], -2).transpose([1, 0, 2])
151+
noise_ceil_1 = noise_ceil[:, eval_ok].transpose([1, 0, 2, 3])
152+
matrix = np.concatenate([evals_nonan, noise_ceil_nonan], 1)
153+
matrix -= np.mean(matrix, 0, keepdims=True)
154+
var_mean = np.einsum('ijk,ilk->kjl', matrix, matrix) \
155+
/ (matrix.shape[0] - 1)
156+
matrix_1 = np.concatenate([evals_1, noise_ceil_1], 1)
157+
matrix_1 -= np.mean(matrix_1, 0, keepdims=True)
158+
var_1 = np.einsum('ijmk,ilmk->kjl', matrix_1, matrix_1) \
159+
/ (matrix_1.shape[0] - 1) / matrix_1.shape[2]
158160
# this is the main formula for the correction:
159161
variances = (n_cv * var_mean - var_1) / (n_cv - 1)
160162
else:

rsatoolbox/inference/result.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -102,14 +102,14 @@ def summary(self, test_type='t-test'):
102102
p_noise = self.test_noise(test_type=test_type)
103103
# header of the results table
104104
summary += 'Model' + (' ' * (name_length - 5))
105-
summary += '| Eval \u00B1 SEM |'
105+
summary += '| Eval \u00B1 SEM |'
106106
summary += ' p (against 0) |'
107107
summary += ' p (against NC) |\n'
108-
summary += '-' * (name_length + 50)
108+
summary += '-' * (name_length + 51)
109109
summary += '\n'
110110
for i, m in enumerate(self.models):
111111
summary += m.name + (' ' * (name_length - len(m.name)))
112-
summary += f'| {means[i]:5.3f} \u00B1 {sems[i]:4.3f} |'
112+
summary += f'| {means[i]: 5.3f} \u00B1 {sems[i]:4.3f} |'
113113
if p_zero[i] < 0.001:
114114
summary += ' < 0.001 |'
115115
else:

rsatoolbox/vis/rdm_plot.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -296,7 +296,9 @@ def show_rdm_panel(
296296
rdmat = rdm.get_matrices()[0, :, :]
297297
if np.any(nanmask):
298298
rdmat[nanmask] = np.nan
299-
image = ax.imshow(rdmat, cmap=cmap, vmin=vmin, vmax=vmax)
299+
image = ax.imshow(
300+
rdmat, cmap=cmap, vmin=vmin, vmax=vmax,
301+
interpolation='none')
300302
ax.set_xlim(-0.5, rdm.n_cond - 0.5)
301303
ax.set_ylim(rdm.n_cond - 0.5, -0.5)
302304
ax.xaxis.set_ticks(gridlines)

tests/test_demo.py

Lines changed: 71 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ class TestDemos(unittest.TestCase):
1212
def test_example_dataset(self):
1313
import numpy as np
1414
import matplotlib.pyplot as plt
15-
import rsatoolbox
1615
import rsatoolbox.data as rsd # abbreviation to deal with dataset
1716

1817
# import the measurements for the dataset
@@ -101,8 +100,6 @@ def test_example_dataset(self):
101100
def test_example_dissimilarities(self):
102101
# relevant imports
103102
import numpy as np
104-
from scipy import io
105-
import rsatoolbox
106103
import rsatoolbox.data as rsd # abbreviation to deal with dataset
107104
import rsatoolbox.rdm as rsr
108105
# create a dataset object
@@ -122,11 +119,12 @@ def test_example_dissimilarities(self):
122119
channel_descriptors=chn_des)
123120
# calculate an RDM
124121
RDM_euc = rsr.calc_rdm(data)
125-
RDM_corr = rsr.calc_rdm(data,
126-
method='correlation', descriptor='conds')
122+
_ = rsr.calc_rdm(
123+
data,
124+
method='correlation', descriptor='conds')
127125
# create an RDM object
128126
rdm_des = {'RDM': np.array(['RDM_1'])}
129-
RDM_euc2 = rsr.RDMs(
127+
_ = rsr.RDMs(
130128
RDM_euc.dissimilarities,
131129
dissimilarity_measure=RDM_euc.dissimilarity_measure,
132130
descriptors=RDM_euc.descriptors,
@@ -136,6 +134,49 @@ def test_example_dissimilarities(self):
136134
dist_matrix = RDM_euc.get_matrices()
137135
print(dist_matrix)
138136

137+
def test_dual_boot(self):
138+
import numpy as np
139+
from scipy import io
140+
import rsatoolbox
141+
import os
142+
path = os.path.dirname(os.path.abspath(__file__))
143+
matlab_data = io.matlab.loadmat(
144+
os.path.join(path, '..', 'demos',
145+
'rdms_inferring', 'modelRDMs_A2020.mat'))
146+
matlab_data = matlab_data['modelRDMs']
147+
n_models = len(matlab_data[0])
148+
model_names = [matlab_data[0][i][0][0] for i in range(n_models)]
149+
measurement_model = [matlab_data[0][i][1][0] for i in range(n_models)]
150+
rdms_array = np.array([matlab_data[0][i][3][0] for i in range(n_models)])
151+
model_rdms = rsatoolbox.rdm.RDMs(
152+
rdms_array,
153+
rdm_descriptors={
154+
'brain_computational_model': model_names,
155+
'measurement_model': measurement_model},
156+
dissimilarity_measure='Euclidean'
157+
)
158+
model_names = [matlab_data[0][i][0][0] for i in range(n_models)]
159+
matlab_data = io.matlab.loadmat(
160+
os.path.join(path, '..', 'demos',
161+
'rdms_inferring', 'noisyModelRDMs_A2020.mat'))
162+
rdms_matlab = matlab_data['noisyModelRDMs']
163+
rdms_matrix = rdms_matlab.squeeze().astype('float')
164+
i_rep = 2 # np.random.randint(len(repr_names))
165+
i_noise = 1 # np.random.randint(len(noise_std))
166+
i_fwhm = 0 # np.random.randint(len(fwhms))
167+
rdms_data = rsatoolbox.rdm.RDMs(rdms_matrix[:, i_rep, i_fwhm, i_noise, :].transpose())
168+
models_flex = []
169+
for i_model in np.unique(model_names):
170+
models_flex.append(
171+
rsatoolbox.model.ModelSelect(
172+
i_model,
173+
model_rdms.subset('brain_computational_model', i_model)
174+
)
175+
)
176+
results_3_full = rsatoolbox.inference.eval_dual_bootstrap(
177+
models_flex, rdms_data, k_pattern=4, k_rdm=2, method='corr', N=5)
178+
print(results_3_full)
179+
139180
def test_exercise_all(self):
140181
import numpy as np
141182
from scipy import io
@@ -161,8 +202,9 @@ def test_exercise_all(self):
161202

162203
conv1_rdms = model_rdms.subset('brain_computational_model', 'conv1')
163204
plt.figure(figsize=(10, 10))
164-
rsatoolbox.vis.show_rdm(conv1_rdms,
165-
rdm_descriptor='measurement_model')
205+
rsatoolbox.vis.show_rdm(
206+
conv1_rdms,
207+
rdm_descriptor='measurement_model')
166208

167209
conv1_rdms = model_rdms.subset('brain_computational_model', 'conv1')
168210
print(conv1_rdms)
@@ -229,8 +271,10 @@ def test_exercise_all(self):
229271

230272
models_flex = []
231273
for i_model in np.unique(model_names):
232-
models_flex.append(rsatoolbox.model.ModelSelect(i_model,
233-
model_rdms.subset('brain_computational_model', i_model)))
274+
models_flex.append(
275+
rsatoolbox.model.ModelSelect(
276+
i_model,
277+
model_rdms.subset('brain_computational_model', i_model)))
234278

235279
print('created the following models:')
236280
for i in range(len(models_flex)):
@@ -332,9 +376,10 @@ def test_temporal_rsa(self):
332376
'%0.0f ms' % (np.round(x * 1000, 2))
333377
for x in rdms_data_binned.rdm_descriptors['time']]
334378

335-
rsatoolbox.vis.show_rdm(rdms_data_binned,
336-
pattern_descriptor='conds',
337-
rdm_descriptor='time_formatted')
379+
rsatoolbox.vis.show_rdm(
380+
rdms_data_binned,
381+
pattern_descriptor='conds',
382+
rdm_descriptor='time_formatted')
338383
from rsatoolbox.rdm import get_categorical_rdm
339384
rdms_model_in = get_categorical_rdm(['%d' % x for x in range(4)])
340385
rdms_model_lr = get_categorical_rdm(['l', 'r', 'l', 'r'])
@@ -347,8 +392,10 @@ def test_temporal_rsa(self):
347392
model_rdms.rdm_descriptors['model_names'] = model_names
348393
model_rdms.pattern_descriptors['cond_names'] = cond_names
349394
plt.figure(figsize=(10, 10))
350-
rsatoolbox.vis.show_rdm(model_rdms, rdm_descriptor='model_names',
351-
pattern_descriptor='cond_names')
395+
rsatoolbox.vis.show_rdm(
396+
model_rdms,
397+
rdm_descriptor='model_names',
398+
pattern_descriptor='cond_names')
352399
from rsatoolbox.rdm import compare
353400
r = []
354401
for mod in model_rdms:
@@ -375,16 +422,18 @@ def test_demo_rdm_scatterplot(self):
375422
matlab_data = loadmat(
376423
os.path.join(path, '..', 'demos', '92imageData/92_brainRDMs.mat'))['RDMs']
377424
n_rdms = len(matlab_data[0])
378-
rdms_ = RDMs(np.array([matlab_data[0][i][0][0] for i in range(n_rdms)]),
379-
pattern_descriptors=condition_descriptors,
380-
rdm_descriptors={'name': np.array([f"RDM{i}"
381-
for i in range(4)])}
382-
)
425+
rdms_ = RDMs(
426+
np.array([matlab_data[0][i][0][0] for i in range(n_rdms)]),
427+
pattern_descriptors=condition_descriptors,
428+
rdm_descriptors={
429+
'name': np.array([f"RDM{i}" for i in range(4)])}
430+
)
383431

384432
rdms_a = concat([rdms_[0], rdms_[1]])
385433
rdms_b = concat([rdms_[2], rdms_[3]])
386434

387-
rdm_comparison_scatterplot((rdms_a, rdms_b),
435+
rdm_comparison_scatterplot(
436+
(rdms_a, rdms_b),
388437
show_marginal_distributions=True,
389438
show_identity_line=True,
390439
show_legend=False,
@@ -397,5 +446,6 @@ def test_demo_rdm_scatterplot(self):
397446
}
398447
)
399448

449+
400450
if __name__ == '__main__':
401451
unittest.main()

tests/test_inference.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -338,10 +338,10 @@ def test_result_print(self):
338338
self.assertEqual(
339339
string,
340340
'Results for running fixed evaluation for corr on 2 models:\n\n'
341-
+ 'Model | Eval ± SEM | p (against 0) | p (against NC) |\n'
342-
+ '--------------------------------------------------------\n'
343-
+ 't1 | 0.873 ± 0.100 | 0.006 | 0.496 |\n'
344-
+ 't2 | 0.120 ± 0.141 | 0.243 | 0.037 |\n\n'
341+
+ 'Model | Eval ± SEM | p (against 0) | p (against NC) |\n'
342+
+ '---------------------------------------------------------\n'
343+
+ 't1 | 0.873 ± 0.100 | 0.006 | 0.496 |\n'
344+
+ 't2 | 0.120 ± 0.141 | 0.243 | 0.037 |\n\n'
345345
+ 'p-values are based on uncorrected t-tests')
346346

347347

0 commit comments

Comments
 (0)