Skip to content

Commit 3c92bcf

Browse files
committed
0.10.2
1 parent 5836d3e commit 3c92bcf

File tree

1,895 files changed

+617413
-0
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

1,895 files changed

+617413
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
"""
2+
Visualizing multiscale functional brain parcellations
3+
=====================================================
4+
5+
This example shows how to download and fetch brain parcellations of
6+
multiple networks using
7+
:func:`nilearn.datasets.fetch_atlas_basc_multiscale_2015`
8+
and visualize them using plotting function :func:`nilearn.plotting.plot_roi`.
9+
10+
We show here only three different networks of 'symmetric' version. For more
11+
details about different versions and different networks, please refer to its
12+
documentation.
13+
"""
14+
15+
# %%
16+
# Retrieving multiscale group brain parcellations
17+
# -----------------------------------------------
18+
19+
# import datasets module and use `fetch_atlas_basc_multiscale_2015` function
20+
from nilearn import datasets
21+
22+
parcellations = [
23+
datasets.fetch_atlas_basc_multiscale_2015(version="sym", resolution=64),
24+
datasets.fetch_atlas_basc_multiscale_2015(version="sym", resolution=197),
25+
datasets.fetch_atlas_basc_multiscale_2015(version="sym", resolution=444),
26+
]
27+
28+
# We show here networks of 64, 197, 444
29+
networks_64 = parcellations[0]["maps"]
30+
networks_197 = parcellations[1]["maps"]
31+
networks_444 = parcellations[2]["maps"]
32+
33+
# %%
34+
# Visualizing brain parcellations
35+
# -------------------------------
36+
37+
# import plotting module and use `plot_roi` function, since the maps are in 3D
38+
from nilearn import plotting
39+
40+
# The coordinates of all plots are selected automatically by itself
41+
# We manually change the colormap of our choice
42+
plotting.plot_roi(
43+
networks_64, cmap=plotting.cm.bwr, title="64 regions of brain clusters"
44+
)
45+
46+
plotting.plot_roi(
47+
networks_197, cmap=plotting.cm.bwr, title="197 regions of brain clusters"
48+
)
49+
50+
plotting.plot_roi(
51+
networks_444, cmap=plotting.cm.bwr_r, title="444 regions of brain clusters"
52+
)
53+
54+
plotting.show()
Lines changed: 254 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,254 @@
1+
"""
2+
================================================
3+
Example of pattern recognition on simulated data
4+
================================================
5+
6+
This example simulates data according to a very simple sketch of brain
7+
imaging data and applies machine learning techniques to predict output
8+
values.
9+
10+
We use a very simple generating function to simulate data, as in `Michel
11+
et al. 2012 <http://dx.doi.org/10.1109/TMI.2011.2113378>`_ , a linear
12+
model with a random design matrix **X**:
13+
14+
.. math::
15+
16+
\\mathbf{y} = \\mathbf{X} \\mathbf{w} + \\mathbf{e}
17+
18+
* **w**: the weights of the linear model correspond to the predictive
19+
brain regions. Here, in the simulations, they form a 3D image with 5, four
20+
of which in opposite corners and one in the middle, as plotted below.
21+
22+
* **X**: the design matrix corresponds to the observed fMRI data. Here
23+
we simulate random normal variables and smooth them as in Gaussian
24+
fields.
25+
26+
* **e** is random normal noise.
27+
28+
"""
29+
30+
print(__doc__)
31+
32+
from time import time
33+
34+
import matplotlib.pyplot as plt
35+
import nibabel
36+
import numpy as np
37+
from scipy import linalg
38+
from scipy.ndimage import gaussian_filter
39+
from sklearn import linear_model, svm
40+
from sklearn.feature_selection import f_regression
41+
from sklearn.model_selection import KFold
42+
from sklearn.pipeline import make_pipeline
43+
from sklearn.preprocessing import StandardScaler
44+
from sklearn.utils import check_random_state
45+
46+
import nilearn.masking
47+
from nilearn import decoding
48+
from nilearn.plotting import show
49+
50+
51+
##############################################################################
52+
# A function to generate data
53+
##############################################################################
54+
def create_simulation_data(snr=0, n_samples=2 * 100, size=12, random_state=1):
55+
generator = check_random_state(random_state)
56+
roi_size = 2 # size / 3
57+
smooth_X = 1
58+
# Coefs
59+
w = np.zeros((size, size, size))
60+
w[0:roi_size, 0:roi_size, 0:roi_size] = -0.6
61+
w[-roi_size:, -roi_size:, 0:roi_size] = 0.5
62+
w[0:roi_size, -roi_size:, -roi_size:] = -0.6
63+
w[-roi_size:, 0:roi_size:, -roi_size:] = 0.5
64+
w[
65+
(size - roi_size) // 2 : (size + roi_size) // 2,
66+
(size - roi_size) // 2 : (size + roi_size) // 2,
67+
(size - roi_size) // 2 : (size + roi_size) // 2,
68+
] = 0.5
69+
w = w.ravel()
70+
# Generate smooth background noise
71+
XX = generator.randn(n_samples, size, size, size)
72+
noise = []
73+
for i in range(n_samples):
74+
Xi = gaussian_filter(XX[i, :, :, :], smooth_X)
75+
Xi = Xi.ravel()
76+
noise.append(Xi)
77+
noise = np.array(noise)
78+
# Generate the signal y
79+
y = generator.randn(n_samples)
80+
X = np.dot(y[:, np.newaxis], w[np.newaxis])
81+
norm_noise = linalg.norm(X, 2) / np.exp(snr / 20.0)
82+
noise_coef = norm_noise / linalg.norm(noise, 2)
83+
noise *= noise_coef
84+
snr = 20 * np.log(linalg.norm(X, 2) / linalg.norm(noise, 2))
85+
print(f"SNR: {snr:.1f} dB")
86+
# Mixing of signal + noise and splitting into train/test
87+
X += noise
88+
X -= X.mean(axis=-1)[:, np.newaxis]
89+
X /= X.std(axis=-1)[:, np.newaxis]
90+
X_test = X[n_samples // 2 :, :]
91+
X_train = X[: n_samples // 2, :]
92+
y_test = y[n_samples // 2 :]
93+
y = y[: n_samples // 2]
94+
95+
return X_train, X_test, y, y_test, snr, w, size
96+
97+
98+
##############################################################################
99+
# A simple function to plot slices
100+
##############################################################################
101+
def plot_slices(data, title=None):
102+
plt.figure(figsize=(5.5, 2.2))
103+
vmax = np.abs(data).max()
104+
for i in (0, 6, 11):
105+
plt.subplot(1, 3, i // 5 + 1)
106+
plt.imshow(
107+
data[:, :, i],
108+
vmin=-vmax,
109+
vmax=vmax,
110+
interpolation="nearest",
111+
cmap=plt.cm.RdBu_r,
112+
)
113+
plt.xticks(())
114+
plt.yticks(())
115+
plt.subplots_adjust(
116+
hspace=0.05, wspace=0.05, left=0.03, right=0.97, top=0.9
117+
)
118+
if title is not None:
119+
plt.suptitle(title)
120+
121+
122+
###############################################################################
123+
# Create data
124+
###############################################################################
125+
X_train, X_test, y_train, y_test, snr, coefs, size = create_simulation_data(
126+
snr=-10, n_samples=100, size=12
127+
)
128+
129+
# Create masks for SearchLight. process_mask is the voxels where SearchLight
130+
# computation is performed. It is a subset of the brain mask, just to reduce
131+
# computation time.
132+
mask = np.ones((size, size, size), dtype=bool)
133+
mask_img = nibabel.Nifti1Image(mask.astype("uint8"), np.eye(4))
134+
process_mask = np.zeros((size, size, size), dtype=bool)
135+
process_mask[:, :, 0] = True
136+
process_mask[:, :, 6] = True
137+
process_mask[:, :, 11] = True
138+
process_mask_img = nibabel.Nifti1Image(process_mask.astype("uint8"), np.eye(4))
139+
140+
coefs = np.reshape(coefs, [size, size, size])
141+
plot_slices(coefs, title="Ground truth")
142+
143+
###############################################################################
144+
# Run different estimators
145+
###############################################################################
146+
#
147+
# We can now run different estimators and look at their prediction score,
148+
# as well as the feature maps that they recover. Namely, we will use
149+
#
150+
# * A support vector regression (`SVM
151+
# <http://scikit-learn.org/stable/modules/svm.html>`_)
152+
#
153+
# * An `elastic-net
154+
# <http://scikit-learn.org/stable/modules/linear_model.html#elastic-net>`_
155+
#
156+
# * A *Bayesian* ridge estimator, i.e. a ridge estimator that sets its
157+
# parameter according to a metaprior
158+
#
159+
# * A ridge estimator that set its parameter by cross-validation
160+
#
161+
# Note that the `RidgeCV` and the `ElasticNetCV` have names ending in `CV`
162+
# that stands for `cross-validation`: in the list of possible `alpha`
163+
# values that they are given, they choose the best by cross-validation.
164+
165+
bayesian_ridge = make_pipeline(StandardScaler(), linear_model.BayesianRidge())
166+
167+
estimators = [
168+
("bayesian_ridge", bayesian_ridge),
169+
(
170+
"enet_cv",
171+
linear_model.ElasticNetCV(alphas=[5, 1, 0.5, 0.1], l1_ratio=0.05),
172+
),
173+
("ridge_cv", linear_model.RidgeCV(alphas=[100, 10, 1, 0.1], cv=5)),
174+
("svr", svm.SVR(kernel="linear", C=0.001)),
175+
(
176+
"searchlight",
177+
decoding.SearchLight(
178+
mask_img,
179+
process_mask_img=process_mask_img,
180+
radius=2.7,
181+
scoring="r2",
182+
estimator=svm.SVR(kernel="linear"),
183+
cv=KFold(n_splits=4),
184+
verbose=1,
185+
n_jobs=1,
186+
),
187+
),
188+
]
189+
190+
###############################################################################
191+
# Run the estimators
192+
#
193+
# As the estimators expose a fairly consistent API, we can all fit them in
194+
# a for loop: they all have a `fit` method for fitting the data, a `score`
195+
# method to retrieve the prediction score, and because they are all linear
196+
# models, a `coef_` attribute that stores the coefficients **w** estimated
197+
198+
for name, estimator in estimators:
199+
t1 = time()
200+
if name != "searchlight":
201+
estimator.fit(X_train, y_train)
202+
else:
203+
X = nilearn.masking.unmask(X_train, mask_img)
204+
estimator.fit(X, y_train)
205+
del X
206+
elapsed_time = time() - t1
207+
208+
if name != "searchlight":
209+
if name == "bayesian_ridge":
210+
coefs = estimator.named_steps["bayesianridge"].coef_
211+
else:
212+
coefs = estimator.coef_
213+
coefs = np.reshape(coefs, [size, size, size])
214+
score = estimator.score(X_test, y_test)
215+
title = (
216+
f"{name}: prediction score {score:.3f}, "
217+
f"training time: {elapsed_time:.2f}s"
218+
)
219+
220+
else: # Searchlight
221+
coefs = estimator.scores_
222+
title = (
223+
f"{estimator.__class__.__name__}: "
224+
f"training time: {elapsed_time:.2f}s"
225+
)
226+
227+
# We use the plot_slices function provided in the example to
228+
# plot the results
229+
plot_slices(coefs, title=title)
230+
231+
print(title)
232+
233+
_, p_values = f_regression(X_train, y_train)
234+
p_values = np.reshape(p_values, (size, size, size))
235+
p_values = -np.log10(p_values)
236+
p_values[np.isnan(p_values)] = 0
237+
p_values[p_values > 10] = 10
238+
plot_slices(p_values, title="f_regress")
239+
240+
show()
241+
242+
###############################################################################
243+
# An exercise to go further
244+
###############################################################################
245+
#
246+
# As an exercice, you can use recursive feature elimination (RFE) with
247+
# the SVM
248+
#
249+
# Read the object's documentation to find out how to use RFE.
250+
#
251+
# **Performance tip**: increase the `step` parameter, or it will be very
252+
# slow.
253+
254+
# from sklearn.feature_selection import RFE

0 commit comments

Comments
 (0)