A introduction tutorial to fMRI decoding

Here is a simple tutorial on decoding with nilearn. It reproduces the Haxby et al.[1] study on a face vs cat discrimination task in a mask of the ventral stream.

This tutorial is meant as an introduction to the various steps of a decoding analysis using Nilearn meta-estimator: nilearn.decoding.Decoder

It is not a minimalistic example, as it strives to be didactic. It is not meant to be copied to analyze new data: many of the steps are unnecessary.

Retrieve and load the fMRI data from the Haxby study

First download the data

The nilearn.datasets.fetch_haxby function will download the Haxby dataset if not present on the disk, in the nilearn data directory. It can take a while to download about 310 Mo of data from the Internet.

from nilearn import datasets

# By default 2nd subject will be fetched
haxby_dataset = datasets.fetch_haxby()
# 'func' is a list of filenames: one for each subject
fmri_filename = haxby_dataset.func[0]

# print basic information on the dataset
print(f"First subject functional nifti images (4D) are at: {fmri_filename}")
[get_dataset_dir] Dataset found in /home/runner/nilearn_data/haxby2001
First subject functional nifti images (4D) are at: /home/runner/nilearn_data/haxby2001/subj2/bold.nii.gz

Visualizing the fMRI volume

One way to visualize a fMRI volume is using nilearn.plotting.plot_epi. We will visualize the previously fetched fMRI data from Haxby dataset.

Because fMRI data are 4D (they consist of many 3D EPI images), we cannot plot them directly using nilearn.plotting.plot_epi (which accepts just 3D input). Here we are using nilearn.image.mean_img to extract a single 3D EPI image from the fMRI data.

from nilearn import plotting
from nilearn.image import mean_img

plotting.view_img(mean_img(fmri_filename, copy_header=True), threshold=None)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/numpy/core/fromnumeric.py:758: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray.
  a.partition(kth, axis=axis, kind=kind, order=order)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(


Feature extraction: from fMRI volumes to a data matrix

These are some really lovely images, but for machine learning we need matrices to work with the actual data. Fortunately, the nilearn.decoding.Decoder object we will use later on can automatically transform Nifti images into matrices. All we have to do for now is define a mask filename.

A mask of the Ventral Temporal (VT) cortex coming from the Haxby study is available:

mask_filename = haxby_dataset.mask_vt[0]

# Let's visualize it, using the subject's anatomical image as a
# background
plotting.plot_roi(mask_filename, bg_img=haxby_dataset.anat[0], cmap="Paired")
plot decoding tutorial
<nilearn.plotting.displays._slicers.OrthoSlicer object at 0x7f845b6fc130>

Load the behavioral labels

Now that the brain images are converted to a data matrix, we can apply machine-learning to them, for instance to predict the task that the subject was doing. The behavioral labels are stored in a CSV file, separated by spaces.

We use pandas to load them in an array.

import pandas as pd

# Load behavioral information
behavioral = pd.read_csv(haxby_dataset.session_target[0], delimiter=" ")
print(behavioral)
     labels  chunks
0      rest       0
1      rest       0
2      rest       0
3      rest       0
4      rest       0
...     ...     ...
1447   rest      11
1448   rest      11
1449   rest      11
1450   rest      11
1451   rest      11

[1452 rows x 2 columns]

The task was a visual-recognition task, and the labels denote the experimental condition: the type of object that was presented to the subject. This is what we are going to try to predict.

conditions = behavioral["labels"]
print(conditions)
0       rest
1       rest
2       rest
3       rest
4       rest
        ...
1447    rest
1448    rest
1449    rest
1450    rest
1451    rest
Name: labels, Length: 1452, dtype: object

Restrict the analysis to cats and faces

As we can see from the targets above, the experiment contains many conditions. As a consequence, the data is quite big. Not all of this data has an interest to us for decoding, so we will keep only fMRI signals corresponding to faces or cats. We create a mask of the samples belonging to the condition; this mask is then applied to the fMRI data to restrict the classification to the face vs cat discrimination.

The input data will become much smaller (i.e. fMRI signal is shorter):

condition_mask = conditions.isin(["face", "cat"])

Because the data is in one single large 4D image, we need to use index_img to do the split easily.

We apply the same mask to the targets

(216,)

Decoding with Support Vector Machine

As a decoder, we use a Support Vector Classifier with a linear kernel. We first create it using by using nilearn.decoding.Decoder.

from nilearn.decoding import Decoder

decoder = Decoder(
    estimator="svc", mask=mask_filename, standardize="zscore_sample"
)

The decoder object is an object that can be fit (or trained) on data with labels, and then predict labels on data without.

We first fit it on the data

/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(

We can then predict the labels from the data

['face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'cat'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'face' 'face' 'cat' 'cat' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'cat' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'face' 'face' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'face' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat'
 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'face' 'face' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat'
 'cat' 'cat' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'face' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'face'
 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat'
 'cat' 'cat' 'cat' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face' 'face'
 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat' 'cat']

Note that for this classification task both classes contain the same number of samples (the problem is balanced). Then, we can use accuracy to measure the performance of the decoder. This is done by defining accuracy as the scoring. Let’s measure the prediction accuracy:

print((prediction == conditions).sum() / float(len(conditions)))
1.0

This prediction accuracy score is meaningless. Why?

Measuring prediction scores using cross-validation

The proper way to measure error rates or prediction accuracy is via cross-validation: leaving out some data and testing on it.

Manually leaving out data

Let’s leave out the 30 last data points during training, and test the prediction on these 30 last points:

fmri_niimgs_train = index_img(fmri_niimgs, slice(0, -30))
fmri_niimgs_test = index_img(fmri_niimgs, slice(-30, None))
conditions_train = conditions[:-30]
conditions_test = conditions[-30:]

decoder = Decoder(
    estimator="svc", mask=mask_filename, standardize="zscore_sample"
)
decoder.fit(fmri_niimgs_train, conditions_train)

prediction = decoder.predict(fmri_niimgs_test)

# The prediction accuracy is calculated on the test data: this is the accuracy
# of our model on examples it hasn't seen to examine how well the model perform
# in general.

predicton_accuracy = (prediction == conditions_test).sum() / float(
    len(conditions_test)
)
print(f"Prediction Accuracy: {predicton_accuracy:.3f}")
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
Prediction Accuracy: 0.767

Implementing a KFold loop

We can manually split the data in train and test set repetitively in a KFold strategy by importing scikit-learn’s object:

from sklearn.model_selection import KFold

cv = KFold(n_splits=5)

for fold, (train, test) in enumerate(cv.split(conditions), start=1):
    decoder = Decoder(
        estimator="svc", mask=mask_filename, standardize="zscore_sample"
    )
    decoder.fit(index_img(fmri_niimgs, train), conditions[train])
    prediction = decoder.predict(index_img(fmri_niimgs, test))
    predicton_accuracy = (prediction == conditions[test]).sum() / float(
        len(conditions[test])
    )
    print(
        f"CV Fold {fold:01d} | "
        f"Prediction Accuracy: {predicton_accuracy:.3f}"
    )
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
CV Fold 1 | Prediction Accuracy: 0.886
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
CV Fold 2 | Prediction Accuracy: 0.767
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
CV Fold 3 | Prediction Accuracy: 0.767
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
CV Fold 4 | Prediction Accuracy: 0.698
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
CV Fold 5 | Prediction Accuracy: 0.744

Cross-validation with the decoder

The decoder also implements a cross-validation loop by default and returns an array of shape (cross-validation parameters, n_folds). We can use accuracy score to measure its performance by defining accuracy as the scoring parameter.

n_folds = 5
decoder = Decoder(
    estimator="svc",
    mask=mask_filename,
    standardize="zscore_sample",
    cv=n_folds,
    scoring="accuracy",
)
decoder.fit(fmri_niimgs, conditions)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(

Cross-validation pipeline can also be implemented manually. More details can be found on scikit-learn website.

Then we can check the best performing parameters per fold.

print(decoder.cv_params_["face"])
{'C': [100.0, 100.0, 100.0, 100.0, 100.0]}

Note

We can speed things up to use all the CPUs of our computer with the n_jobs parameter.

The best way to do cross-validation is to respect the structure of the experiment, for instance by leaving out full runs of acquisition.

The number of the run is stored in the CSV file giving the behavioral data. We have to apply our run mask, to select only cats and faces.

The fMRI data is acquired by runs, and the noise is autocorrelated in a given run. Hence, it is better to predict across runs when doing cross-validation. To leave a run out, pass the cross-validator object to the cv parameter of decoder.

from sklearn.model_selection import LeaveOneGroupOut

cv = LeaveOneGroupOut()

decoder = Decoder(
    estimator="svc", mask=mask_filename, standardize="zscore_sample", cv=cv
)
decoder.fit(fmri_niimgs, conditions, groups=run_label)

print(decoder.cv_scores_)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
{'cat': [1.0, 1.0, 1.0, 1.0, 0.9629629629629629, 0.8518518518518519, 0.9753086419753086, 0.40740740740740744, 0.9876543209876543, 1.0, 0.9259259259259259, 0.8765432098765432], 'face': [1.0, 1.0, 1.0, 1.0, 0.9629629629629629, 0.8518518518518519, 0.9753086419753086, 0.40740740740740744, 0.9876543209876543, 1.0, 0.9259259259259259, 0.8765432098765432]}

Inspecting the model weights

Finally, it may be useful to inspect and display the model weights.

Turning the weights into a nifti image

We retrieve the SVC discriminating weights

[[-3.89375921e-02 -1.87166759e-02 -3.23026578e-02 -2.88746584e-02
   4.18696481e-02  1.10744577e-02  1.69997724e-02 -5.50954313e-02
  -1.94205093e-02 -3.51226418e-02  1.08512235e-02 -1.28796806e-02
  -1.54677523e-02 -3.78908684e-02 -3.69167107e-02  2.28087496e-02
   6.56412980e-03 -7.65766066e-03  1.67105157e-02 -8.02149604e-03
   5.29515867e-02 -8.17594077e-02 -6.36991837e-02  2.41324248e-02
   4.59875702e-02 -2.22603689e-02 -1.77309255e-02  2.22196853e-02
  -9.53197180e-03  5.76045935e-02  2.14300572e-02 -9.14225956e-02
   4.03659603e-03 -2.89275521e-02 -3.89030529e-02 -3.35114545e-02
   2.21398022e-03  8.73126199e-03 -3.37415944e-02 -2.41275899e-02
  -6.81646787e-02  1.65409219e-02  2.70785483e-02 -6.56855194e-03
  -1.21663834e-02  5.47675221e-02  8.13267644e-03  3.60955317e-02
  -1.52762155e-02  7.02913710e-02  1.28088586e-03  2.08007644e-02
  -4.09943868e-03  3.72429650e-02 -3.77395247e-02 -1.03858002e-02
  -2.38236852e-02 -5.48880801e-02  4.43027176e-02 -1.47419299e-01
  -2.34042502e-02  1.87113421e-02  6.65858711e-02 -9.07603417e-02
  -1.22034465e-02 -2.95652602e-03  3.22092516e-02 -3.04054632e-02
   6.15345016e-02  1.12247633e-02  1.93774114e-02 -1.30540078e-02
   4.42975059e-02 -2.23065519e-02  6.88146342e-02  1.69390010e-02
   1.78947363e-02  1.00275568e-02  2.99185929e-02 -2.52173560e-02
   1.06154425e-02 -6.31941008e-03  2.21502129e-03 -2.23348996e-02
   1.42561301e-02 -1.53123098e-02 -1.98226346e-02 -4.32637778e-02
  -4.55124295e-02  3.41589787e-02 -2.79199973e-02 -2.80909555e-02
  -3.70159594e-02 -5.71451559e-02 -6.98950318e-02  3.20170012e-03
  -8.35435390e-03 -3.37628496e-02  3.04261543e-02  8.68453246e-03
   6.19383704e-03  5.94178676e-02  9.07295888e-03 -1.48930630e-02
   1.43558833e-02 -1.09027562e-02  2.67697807e-02  4.73787298e-02
  -2.96432346e-02  3.09423410e-02  1.57927927e-02 -3.16719844e-02
  -4.00105788e-02 -5.40261006e-02  2.82612681e-02 -1.12101121e-02
  -5.45402160e-02  6.32177261e-02 -1.49997646e-02  2.47545095e-03
  -4.56645081e-02 -1.83882627e-02  1.19957656e-02 -3.72172183e-02
  -2.25520630e-03  4.58657660e-02  4.79166408e-02  2.51819578e-03
  -4.31720945e-02 -5.35345783e-03  5.76993178e-02  7.40849739e-03
  -3.20590769e-02  4.35709470e-03  1.68303413e-02 -2.92569673e-02
  -2.24496343e-03 -8.30206980e-03 -1.00013832e-02  2.17135142e-02
  -1.92619729e-03 -1.33221864e-02 -2.80300443e-02 -1.75294259e-02
  -9.17791989e-03 -7.09948423e-03 -1.43032577e-02  5.06832447e-02
  -1.84814762e-02 -4.71507631e-02  1.72569699e-02 -4.76642923e-02
  -9.09145455e-04  4.00768182e-02  7.53995145e-02  7.25616785e-03
   4.82605946e-02  4.50555301e-02  3.61202332e-02 -8.16475941e-03
   1.95406247e-02  3.57882699e-02  4.89306008e-02  3.82974356e-02
   6.23919851e-02  6.13675461e-02 -1.68752132e-02  1.66514205e-02
   3.35521767e-02 -1.80211709e-02  4.46410784e-02 -3.53246074e-02
  -3.67291337e-02 -4.62252769e-03  4.86829898e-02  3.39667822e-02
   6.21721396e-03  1.73612830e-02  2.01695816e-02  2.17098836e-02
   2.91412674e-02  2.37777112e-02  4.84699191e-02 -9.22625939e-03
  -2.82636915e-02 -2.13782321e-02  1.80783345e-03  4.79687613e-02
  -9.78899674e-03  1.11431722e-02 -1.65020900e-02 -2.89090810e-02
   2.42849430e-02 -1.22346212e-02 -2.92870284e-02 -2.89844642e-02
  -3.39533258e-02 -3.65283317e-03  2.65324782e-02  4.58043831e-02
  -5.93381775e-02 -2.13629669e-02 -3.09406359e-02  5.50178977e-02
  -3.38815115e-02  6.12595814e-03  1.41485239e-02  1.10216758e-02
   5.33811171e-02 -2.12339572e-02  6.37417481e-03 -1.13075726e-02
  -2.64225074e-02 -2.22399344e-02 -5.31922106e-02 -3.98653030e-02
  -1.29727860e-01 -3.28090485e-02 -2.89712046e-02 -9.13470895e-03
  -7.28734531e-03 -3.71052667e-02 -6.34906357e-02  2.04371936e-03
  -8.26795499e-02 -6.71214524e-02 -2.29120790e-03 -2.33451479e-02
   1.77914774e-02 -8.74665082e-02 -2.76476972e-03 -4.38275447e-02
  -1.28050539e-02  2.78033659e-02 -4.32694530e-02 -3.22686029e-02
  -2.28028678e-02 -2.57414168e-02  2.03624955e-02 -9.90246529e-03
  -3.15032719e-02 -1.81419401e-02 -1.12318198e-03 -4.17431676e-02
  -6.23478792e-02  2.54588176e-04 -6.73680104e-02  6.53967844e-02
   1.06522851e-02  2.21982473e-02 -1.98728980e-02 -1.85517880e-02
   4.05702650e-02 -3.02838055e-02 -8.10051061e-02 -7.42458158e-02
  -4.93847877e-02 -1.01773204e-02  1.09407748e-02 -4.49254881e-02
   2.92747755e-02  7.05317299e-03  5.07534417e-03 -4.84044479e-03
   2.48740168e-03  3.00653594e-02 -2.63079884e-03  4.64686021e-03
   7.90209834e-02  1.04857644e-02  1.68079904e-02 -4.36718530e-02
  -1.08856434e-02  2.10240120e-02 -4.41965720e-02  3.16504518e-03
   6.98672007e-02  8.61629460e-02  4.96235466e-02  6.03900345e-03
   5.56496609e-02 -2.98920303e-02  4.13019247e-03 -3.21951847e-02
  -3.14991287e-02 -5.31274489e-02  2.67257668e-02  3.14428330e-02
   6.67094075e-03 -1.28703513e-02  2.20151095e-02  5.68521612e-02
   2.25602944e-02 -2.04617436e-02  5.10336347e-03  2.85357674e-02
  -1.81664333e-02 -8.48430104e-03 -3.18825736e-02 -1.18498582e-02
  -4.10845223e-02  3.11777495e-02  9.63466553e-03 -8.25908060e-03
  -3.12226228e-02  8.57655787e-03 -9.70205691e-03  1.32372550e-02
   4.06447199e-02  8.23405268e-03 -3.27356069e-02 -4.33874103e-03
  -1.75531228e-02  6.88845082e-03  3.45133925e-02  7.03299152e-02
   2.16783993e-02  5.32226447e-03  8.17563478e-02  6.40062662e-02
  -2.31157526e-03 -1.17559017e-02  1.75889110e-01  3.18129469e-02
  -3.15887358e-02  3.34027518e-02  2.22780378e-02  1.00232322e-02
  -4.74911652e-02 -2.12755565e-02 -3.98718317e-02 -6.04068361e-02
  -4.65060837e-02  1.03001785e-02 -3.05735305e-04  1.80744007e-02
  -1.75450301e-02 -8.72589682e-02  1.00662490e-01  4.46111116e-03
   7.46870868e-02 -6.13412611e-02  2.81705515e-02 -1.40977388e-02
   3.14637919e-02 -1.63833929e-02  3.66534385e-02 -5.15691493e-03
   1.45093807e-02  6.35864201e-02  2.34598244e-02  8.81065167e-02
   6.15345712e-02 -1.39360992e-02  2.07248047e-02 -3.15451674e-03
   5.15424618e-02 -2.88767567e-02  1.60262616e-02  2.09701852e-02
  -3.29172061e-02 -2.59461436e-02 -5.60400221e-02 -3.64627762e-02
   1.12881631e-02  2.17267526e-02 -1.51638318e-02 -7.82891216e-03
   2.42550473e-02  9.47011818e-02 -2.63033669e-02  1.17329879e-04
  -5.24178380e-03  4.17987780e-02  8.85680935e-02  6.23653763e-03
   1.86601967e-02  1.54629136e-02  3.50535289e-03  6.20596212e-03
  -1.19789389e-02  1.59526708e-02  7.12131288e-03 -8.93191538e-02
  -3.54358412e-03  1.23478864e-02  3.03926462e-02 -2.37294326e-02
  -3.82792528e-02 -4.98745546e-02  4.66896601e-02 -1.23293214e-02
  -1.10332382e-02  2.18105221e-02  2.18719975e-02  2.63539185e-02
   1.05280494e-02  1.84617843e-02  8.36066203e-04 -6.65211669e-03
   3.49396648e-02  1.49353080e-02 -1.11599846e-02  6.69110602e-03
  -2.00059033e-02 -3.99014778e-02  3.01873883e-02 -1.09867171e-02
  -4.11782885e-02  2.72051814e-02  1.16424794e-02 -1.55502564e-02
   3.27699876e-02  3.95493583e-02  8.48730444e-03  2.19935789e-02
  -9.88675323e-03 -3.61421503e-02 -4.77021789e-02  1.90073937e-02
  -5.58286659e-02 -3.31737867e-02 -2.24914025e-02 -3.36173956e-02
  -4.07355008e-02  1.08860910e-02  1.12811940e-02  7.63142019e-02
   4.04806882e-03  3.07013405e-02  2.89177837e-02  4.71597992e-03
   5.13385621e-02 -4.10364517e-02  1.23263359e-03 -2.50402324e-02
   5.85904493e-02 -1.04965733e-01 -4.41705737e-02  1.18520110e-02
  -5.83203207e-02 -4.82245667e-02  9.17677435e-03  1.03260495e-02
  -5.09191037e-03 -3.23389605e-02 -3.19385161e-02 -1.53770610e-02
  -5.21211024e-02  1.55620044e-02  2.93484798e-02 -1.92527293e-02
   1.76695156e-02  2.67992789e-02  5.76553369e-02 -1.38162996e-02
   2.60399335e-02  1.50400188e-02  1.27423341e-02 -2.29244588e-02
  -1.06665890e-02  9.81925067e-03 -4.77512060e-02  1.64243189e-02]]

It’s a numpy array with only one coefficient per voxel:

print(coef_.shape)
(1, 464)

To get the Nifti image of these coefficients, we only need retrieve the coef_img_ in the decoder and select the class

coef_img is now a NiftiImage. We can save the coefficients as a nii.gz file:

from pathlib import Path

output_dir = Path.cwd() / "results" / "plot_decoding_tutorial"
output_dir.mkdir(exist_ok=True, parents=True)
print(f"Output will be saved to: {output_dir}")
decoder.coef_img_["face"].to_filename(output_dir / "haxby_svc_weights.nii.gz")
Output will be saved to: /home/runner/work/nilearn/nilearn/examples/00_tutorials/results/plot_decoding_tutorial

Plotting the SVM weights

We can plot the weights, using the subject’s anatomical as a background

plotting.view_img(
    decoder.coef_img_["face"],
    bg_img=haxby_dataset.anat[0],
    title="SVM weights",
    dim=-1,
)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/numpy/core/fromnumeric.py:758: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray.
  a.partition(kth, axis=axis, kind=kind, order=order)


What is the chance level accuracy?

Does the model above perform better than chance? To answer this question, we measure a score at random using simple strategies that are implemented in the nilearn.decoding.Decoder object. This is useful to inspect the decoding performance by comparing to a score at chance.

Let’s define a object with Dummy estimator replacing ‘svc’ for classification setting. This object initializes estimator with default dummy strategy.

dummy_decoder = Decoder(
    estimator="dummy_classifier",
    mask=mask_filename,
    cv=cv,
    standardize="zscore_sample",
)
dummy_decoder.fit(fmri_niimgs, conditions, groups=run_label)

# Now, we can compare these scores by simply taking a mean over folds
print(dummy_decoder.cv_scores_)
/home/runner/work/nilearn/nilearn/.tox/doc/lib/python3.9/site-packages/nilearn/image/resampling.py:524: UserWarning: The provided image has no sform in its header. Please check the provided file. Results may not be as expected.
  warnings.warn(
{'cat': [0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895], 'face': [0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.38888888888888895, 0.6111111111111112, 0.38888888888888895]}

References

See also


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

Estimated memory usage: 1054 MB

Gallery generated by Sphinx-Gallery