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}")
First subject functional nifti images (4D) are at: /home/himanshu/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), threshold=None)
/home/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/numpy/core/fromnumeric.py:771: UserWarning: Warning: 'partition' will ignore the 'mask' of the MaskedArray.
  a.partition(kth, axis=axis, kind=kind, order=order)


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 0x73326b4956a0>

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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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.89377228e-02 -1.87167306e-02 -3.23027652e-02 -2.88747011e-02
   4.18696687e-02  1.10743611e-02  1.69998682e-02 -5.50955349e-02
  -1.94205748e-02 -3.51226572e-02  1.08510293e-02 -1.28797049e-02
  -1.54677859e-02 -3.78908367e-02 -3.69169765e-02  2.28087059e-02
   6.56425333e-03 -7.65751445e-03  1.67105976e-02 -8.02152550e-03
   5.29514875e-02 -8.17595636e-02 -6.36991320e-02  2.41326645e-02
   4.59875009e-02 -2.22602676e-02 -1.77310595e-02  2.22197609e-02
  -9.53196498e-03  5.76046302e-02  2.14299644e-02 -9.14228638e-02
   4.03666713e-03 -2.89275691e-02 -3.89031025e-02 -3.35115790e-02
   2.21399655e-03  8.73140783e-03 -3.37416821e-02 -2.41275446e-02
  -6.81650518e-02  1.65404596e-02  2.70785515e-02 -6.56835996e-03
  -1.21661953e-02  5.47674715e-02  8.13289692e-03  3.60956977e-02
  -1.52763227e-02  7.02913016e-02  1.28098698e-03  2.08010481e-02
  -4.09942332e-03  3.72430192e-02 -3.77393683e-02 -1.03858494e-02
  -2.38237790e-02 -5.48880996e-02  4.43027853e-02 -1.47419311e-01
  -2.34043678e-02  1.87115410e-02  6.65858698e-02 -9.07603317e-02
  -1.22034405e-02 -2.95627971e-03  3.22092618e-02 -3.04054251e-02
   6.15345921e-02  1.12250947e-02  1.93776946e-02 -1.30543906e-02
   4.42975845e-02 -2.23066124e-02  6.88147913e-02  1.69389952e-02
   1.78947490e-02  1.00277315e-02  2.99187122e-02 -2.52169211e-02
   1.06156010e-02 -6.31944991e-03  2.21521921e-03 -2.23347709e-02
   1.42561352e-02 -1.53124080e-02 -1.98227408e-02 -4.32639039e-02
  -4.55124699e-02  3.41589449e-02 -2.79200031e-02 -2.80912118e-02
  -3.70158666e-02 -5.71451734e-02 -6.98950105e-02  3.20171510e-03
  -8.35452283e-03 -3.37627075e-02  3.04260341e-02  8.68458693e-03
   6.19383507e-03  5.94179212e-02  9.07294979e-03 -1.48931207e-02
   1.43560562e-02 -1.09026901e-02  2.67698524e-02  4.73788553e-02
  -2.96433422e-02  3.09421422e-02  1.57926831e-02 -3.16719922e-02
  -4.00106652e-02 -5.40260919e-02  2.82611669e-02 -1.12100489e-02
  -5.45402133e-02  6.32178332e-02 -1.49996375e-02  2.47544828e-03
  -4.56643982e-02 -1.83881784e-02  1.19957171e-02 -3.72172668e-02
  -2.25510295e-03  4.58655583e-02  4.79164912e-02  2.51824448e-03
  -4.31721229e-02 -5.35313429e-03  5.76994687e-02  7.40822969e-03
  -3.20591251e-02  4.35702146e-03  1.68302699e-02 -2.92570450e-02
  -2.24495603e-03 -8.30219412e-03 -1.00013163e-02  2.17135950e-02
  -1.92619225e-03 -1.33222290e-02 -2.80300083e-02 -1.75292414e-02
  -9.17806469e-03 -7.09932424e-03 -1.43033536e-02  5.06830922e-02
  -1.84813159e-02 -4.71508977e-02  1.72568269e-02 -4.76641270e-02
  -9.09096504e-04  4.00770335e-02  7.53995499e-02  7.25608626e-03
   4.82604650e-02  4.50556302e-02  3.61202185e-02 -8.16485461e-03
   1.95406503e-02  3.57885629e-02  4.89305423e-02  3.82972041e-02
   6.23918580e-02  6.13672894e-02 -1.68751255e-02  1.66514333e-02
   3.35522823e-02 -1.80213717e-02  4.46411432e-02 -3.53244911e-02
  -3.67292980e-02 -4.62249662e-03  4.86829444e-02  3.39666759e-02
   6.21716673e-03  1.73611161e-02  2.01699186e-02  2.17096673e-02
   2.91414341e-02  2.37776844e-02  4.84696346e-02 -9.22620821e-03
  -2.82637727e-02 -2.13779790e-02  1.80783255e-03  4.79689609e-02
  -9.78891320e-03  1.11430408e-02 -1.65021742e-02 -2.89088825e-02
   2.42852130e-02 -1.22346512e-02 -2.92869485e-02 -2.89846679e-02
  -3.39534156e-02 -3.65276233e-03  2.65322880e-02  4.58039440e-02
  -5.93380708e-02 -2.13631179e-02 -3.09404652e-02  5.50179050e-02
  -3.38817257e-02  6.12634373e-03  1.41484020e-02  1.10216174e-02
   5.33811409e-02 -2.12341165e-02  6.37421660e-03 -1.13075312e-02
  -2.64225887e-02 -2.22399990e-02 -5.31920546e-02 -3.98653926e-02
  -1.29727839e-01 -3.28092114e-02 -2.89710032e-02 -9.13471242e-03
  -7.28717497e-03 -3.71050886e-02 -6.34905667e-02  2.04378098e-03
  -8.26796072e-02 -6.71217780e-02 -2.29135839e-03 -2.33450994e-02
   1.77914744e-02 -8.74668244e-02 -2.76491462e-03 -4.38275304e-02
  -1.28052306e-02  2.78032969e-02 -4.32696006e-02 -3.22690425e-02
  -2.28028849e-02 -2.57415443e-02  2.03623305e-02 -9.90249578e-03
  -3.15034580e-02 -1.81419681e-02 -1.12311944e-03 -4.17433657e-02
  -6.23479276e-02  2.54685359e-04 -6.73679078e-02  6.53964802e-02
   1.06522143e-02  2.21984087e-02 -1.98728166e-02 -1.85519226e-02
   4.05702390e-02 -3.02838979e-02 -8.10050029e-02 -7.42458980e-02
  -4.93850063e-02 -1.01770722e-02  1.09407959e-02 -4.49252846e-02
   2.92749134e-02  7.05312003e-03  5.07530322e-03 -4.84057513e-03
   2.48720110e-03  3.00655976e-02 -2.63095538e-03  4.64688365e-03
   7.90210125e-02  1.04857974e-02  1.68081157e-02 -4.36719531e-02
  -1.08855393e-02  2.10243016e-02 -4.41964706e-02  3.16485987e-03
   6.98672193e-02  8.61631402e-02  4.96234289e-02  6.03895454e-03
   5.56492924e-02 -2.98921665e-02  4.13044780e-03 -3.21952823e-02
  -3.14991155e-02 -5.31276955e-02  2.67255352e-02  3.14427268e-02
   6.67120622e-03 -1.28702907e-02  2.20150290e-02  5.68525102e-02
   2.25603001e-02 -2.04616604e-02  5.10342269e-03  2.85355864e-02
  -1.81666341e-02 -8.48435559e-03 -3.18823640e-02 -1.18499865e-02
  -4.10846259e-02  3.11778864e-02  9.63473544e-03 -8.25921256e-03
  -3.12229584e-02  8.57641705e-03 -9.70192782e-03  1.32376161e-02
   4.06446548e-02  8.23399022e-03 -3.27356748e-02 -4.33885368e-03
  -1.75529424e-02  6.88835633e-03  3.45132567e-02  7.03299722e-02
   2.16784483e-02  5.32226420e-03  8.17563087e-02  6.40061525e-02
  -2.31131174e-03 -1.17556908e-02  1.75889236e-01  3.18129016e-02
  -3.15886654e-02  3.34028006e-02  2.22782797e-02  1.00231572e-02
  -4.74916037e-02 -2.12759026e-02 -3.98717765e-02 -6.04068597e-02
  -4.65059160e-02  1.03005459e-02 -3.05778488e-04  1.80742459e-02
  -1.75453537e-02 -8.72592037e-02  1.00662641e-01  4.46109498e-03
   7.46870541e-02 -6.13410606e-02  2.81704116e-02 -1.40979182e-02
   3.14638238e-02 -1.63834491e-02  3.66531948e-02 -5.15664713e-03
   1.45093227e-02  6.35867142e-02  2.34599337e-02  8.81059753e-02
   6.15344441e-02 -1.39362484e-02  2.07247451e-02 -3.15472736e-03
   5.15423503e-02 -2.88767774e-02  1.60264567e-02  2.09702079e-02
  -3.29173348e-02 -2.59462197e-02 -5.60400961e-02 -3.64627581e-02
   1.12881525e-02  2.17266589e-02 -1.51638092e-02 -7.82882683e-03
   2.42549580e-02  9.47013713e-02 -2.63032890e-02  1.17316535e-04
  -5.24168394e-03  4.17988902e-02  8.85680192e-02  6.23641849e-03
   1.86599372e-02  1.54628524e-02  3.50532381e-03  6.20608352e-03
  -1.19789686e-02  1.59526632e-02  7.12129021e-03 -8.93193402e-02
  -3.54325803e-03  1.23477425e-02  3.03927833e-02 -2.37294989e-02
  -3.82794298e-02 -4.98745367e-02  4.66895767e-02 -1.23290779e-02
  -1.10332734e-02  2.18106427e-02  2.18720565e-02  2.63536925e-02
   1.05279823e-02  1.84618261e-02  8.36047197e-04 -6.65213622e-03
   3.49397254e-02  1.49353646e-02 -1.11598506e-02  6.69091883e-03
  -2.00059098e-02 -3.99013771e-02  3.01871895e-02 -1.09867188e-02
  -4.11778215e-02  2.72051831e-02  1.16426575e-02 -1.55501870e-02
   3.27701336e-02  3.95493853e-02  8.48732749e-03  2.19934646e-02
  -9.88650081e-03 -3.61421404e-02 -4.77019801e-02  1.90072105e-02
  -5.58287147e-02 -3.31741049e-02 -2.24913074e-02 -3.36176644e-02
  -4.07355744e-02  1.08862347e-02  1.12810730e-02  7.63145451e-02
   4.04804053e-03  3.07013452e-02  2.89176782e-02  4.71620452e-03
   5.13382376e-02 -4.10364093e-02  1.23249969e-03 -2.50404233e-02
   5.85904629e-02 -1.04965540e-01 -4.41705026e-02  1.18518787e-02
  -5.83203292e-02 -4.82243848e-02  9.17662415e-03  1.03260206e-02
  -5.09182557e-03 -3.23390987e-02 -3.19385169e-02 -1.53769619e-02
  -5.21212464e-02  1.55619546e-02  2.93485284e-02 -1.92529310e-02
   1.76693485e-02  2.67990767e-02  5.76554197e-02 -1.38162425e-02
   2.60399956e-02  1.50401353e-02  1.27426571e-02 -2.29243134e-02
  -1.06665399e-02  9.81936663e-03 -4.77511848e-02  1.64243756e-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/himanshu/Desktop/nilearn_work/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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/numpy/core/fromnumeric.py:771: 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/himanshu/.local/miniconda3/envs/nilearnpy/lib/python3.12/site-packages/nilearn/image/resampling.py:492: 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 36.149 seconds)

Estimated memory usage: 926 MB

Gallery generated by Sphinx-Gallery