Skip to content

Commit

Permalink
Change all splitters in examples (#4031)
Browse files Browse the repository at this point in the history
  • Loading branch information
ymzayek committed Oct 9, 2023
1 parent 38522af commit 016f749
Show file tree
Hide file tree
Showing 71 changed files with 623 additions and 598 deletions.
12 changes: 6 additions & 6 deletions doc/connectivity/region_extraction.rst
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ dataset.

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # We use nilearn's datasets downloading utilities
:end-before: ##############################################################################
:end-before: # %%

.. currentmodule:: nilearn.decomposition

Expand Down Expand Up @@ -60,7 +60,7 @@ color and colors are random and automatically picked.

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # Show networks using plotting utilities
:end-before: ##############################################################################
:end-before: # %%

.. |dict-maps| image:: ../auto_examples/03_connectivity/images/sphx_glr_plot_extract_regions_dictlearning_maps_001.png
:target: ../auto_examples/03_connectivity/plot_extract_regions_dictlearning_maps.html
Expand Down Expand Up @@ -107,7 +107,7 @@ quite nicely into each hemisphere.

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # Visualization of region extraction results
:end-before: ##############################################################################
:end-before: # %%

.. |dict| image:: ../auto_examples/03_connectivity/images/sphx_glr_plot_extract_regions_dictlearning_maps_002.png
:target: ../auto_examples/03_connectivity/plot_extract_regions_dictlearning_maps.html
Expand Down Expand Up @@ -136,7 +136,7 @@ The third step, we compute the mean correlation across all subjects.

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # To estimate correlation matrices we import connectome utilities from nilearn
:end-before: #################################################################
:end-before: # %%

.. currentmodule:: nilearn.plotting

Expand All @@ -151,7 +151,7 @@ connectivity relations to brain regions plotted using :func:`plot_connectome`

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # connectome relations.
:end-before: ##############################################################################
:end-before: # %%

.. |matrix| image:: ../auto_examples/03_connectivity/images/sphx_glr_plot_extract_regions_dictlearning_maps_003.png
:target: ../auto_examples/03_connectivity/plot_extract_regions_dictlearning_maps.html
Expand All @@ -170,7 +170,7 @@ Showing only one specific network regions before and after region extraction. Th

.. literalinclude:: ../../examples/03_connectivity/plot_extract_regions_dictlearning_maps.py
:start-after: # without region extraction (left plot).
:end-before: ##############################################################################
:end-before: # %%

.. |dmn| image:: ../auto_examples/03_connectivity/images/sphx_glr_plot_extract_regions_dictlearning_maps_005.png
:target: ../auto_examples/03_connectivity/plot_extract_regions_dictlearning_maps.html
Expand Down
16 changes: 8 additions & 8 deletions examples/02_decoding/plot_haxby_anova_svm.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"""

#############################################################################
# %%
# Retrieve the files of the Haxby dataset
# ---------------------------------------
from nilearn import datasets
Expand All @@ -19,7 +19,7 @@
print(f"Mask nifti image (3D) is located at: {haxby_dataset.mask}")
print(f"Functional nifti image (4D) is located at: {func_img}")

#############################################################################
# %%
# Load the behavioral data
# ------------------------
import pandas as pd
Expand All @@ -42,7 +42,7 @@
# data. We have to apply our session mask, to select only faces and houses.
session_label = behavioral["chunks"][condition_mask]

#############################################################################
# %%
# ANOVA pipeline with :class:`nilearn.decoding.Decoder` object
# ------------------------------------------------------------
#
Expand All @@ -65,13 +65,13 @@
scoring="accuracy",
)

#############################################################################
# %%
# Fit the decoder and predict
# ---------------------------
decoder.fit(func_img, conditions)
y_pred = decoder.predict(func_img)

#############################################################################
# %%
# Obtain prediction scores via cross validation
# ---------------------------------------------
# Define the cross-validation scheme used for validation. Here we use a
Expand Down Expand Up @@ -99,7 +99,7 @@
# Print the CV scores
print(decoder.cv_scores_["face"])

#############################################################################
# %%
# Visualize the results
# ---------------------
# Look at the SVC's discriminating weights using
Expand All @@ -110,13 +110,13 @@
plot_stat_map(weight_img, bg_img=haxby_dataset.anat[0], title="SVM weights")

show()
#############################################################################
# %%
# Or we can plot the weights using :class:`nilearn.plotting.view_img` as a
# dynamic html viewer
from nilearn.plotting import view_img

view_img(weight_img, bg_img=haxby_dataset.anat[0], title="SVM weights", dim=-1)
#############################################################################
# %%
# Saving the results as a Nifti file may also be important
weight_img.to_filename("haxby_face_vs_house.nii")

Expand Down
12 changes: 6 additions & 6 deletions examples/02_decoding/plot_haxby_different_estimators.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
decoding task.
"""

#############################################################################
# %%
# Loading the data
# ----------------

Expand Down Expand Up @@ -60,7 +60,7 @@
fmri_niimgs = index_img(func_filename, task_mask)
classification_target = stimuli[task_mask]

#############################################################################
# %%
# Training the decoder
# --------------------

Expand Down Expand Up @@ -109,7 +109,7 @@
scores["AVERAGE"] = np.mean(list(scores.values()), axis=0)
classifiers_data[classifier_name]["score"] = scores

###############################################################################
# %%
# Visualization
# -------------

Expand Down Expand Up @@ -147,13 +147,13 @@
)
plt.tight_layout()

###############################################################################
# %%
# We can see that for a fixed penalty the results are similar between the svc
# and the logistic regression. The main difference relies on the penalty
# ($\ell_1$ and $\ell_2$). The sparse penalty works better because we are in
# an intra-subject setting.

###############################################################################
# %%
# Visualizing the face vs house map
# ---------------------------------
#
Expand All @@ -179,7 +179,7 @@
classifiers_data[classifier_name]["score"] = decoder.cv_scores_
classifiers_data[classifier_name]["map"] = decoder.coef_img_["face"]

###############################################################################
# %%
# Finally, we plot the face vs house map for the different classifiers
# Use the average EPI as a background

Expand Down
10 changes: 5 additions & 5 deletions examples/02_decoding/plot_haxby_frem.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
To have more details, see: :ref:`frem`.
"""

##############################################################################
# %%
# Load the Haxby dataset
# ----------------------
from nilearn.datasets import fetch_haxby
Expand Down Expand Up @@ -50,7 +50,7 @@

background_img = mean_img(func_filenames)

##############################################################################
# %%
# Fit FREM
# --------
from nilearn.decoding import FREMClassifier
Expand All @@ -62,7 +62,7 @@
accuracy = (y_pred == y_test).mean() * 100.0
print(f"FREM classification accuracy : {accuracy:g}%")

#############################################################################
# %%
# Plot confusion matrix
# ------------------------------------

Expand Down Expand Up @@ -96,7 +96,7 @@

plotting.show()

#############################################################################
# %%
# Visualization of FREM weights
# -----------------------------
from nilearn import plotting
Expand All @@ -109,7 +109,7 @@
display_mode="yz",
)
plotting.show()
#############################################################################
# %%
# FREM ensembling procedure yields an important improvement of decoding
# accuracy on this simple example compared to fitting only one model per
# fold and the clustering mechanism keeps its computational cost reasonable
Expand Down
8 changes: 4 additions & 4 deletions examples/02_decoding/plot_haxby_full_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"""

##########################################################################
# %%
# Load and prepare the data
# -------------------------

Expand Down Expand Up @@ -58,7 +58,7 @@

task_data = index_img(func_filename, task_mask)

##########################################################################
# %%
# Decoding on the different masks
# -------------------------------
#
Expand All @@ -73,7 +73,7 @@

cv = LeaveOneGroupOut()

##############################################################
# %%
# We use :class:`nilearn.decoding.Decoder` to estimate a baseline.

mask_names = ["mask_vt", "mask_face", "mask_house"]
Expand Down Expand Up @@ -123,7 +123,7 @@
]


##########################################################################
# %%
# We make a simple bar plot to summarize the results
# --------------------------------------------------
import matplotlib.pyplot as plt
Expand Down
16 changes: 8 additions & 8 deletions examples/02_decoding/plot_haxby_glm_decoding.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
3. Analyze the decoding performance using a classifier.
"""

##############################################################################
# %%
# Fetch example Haxby dataset
# ---------------------------
# We download the Haxby dataset
Expand All @@ -30,7 +30,7 @@
# repetition has to be known
TR = 2.5

##############################################################################
# %%
# Load the behavioral data
# ------------------------

Expand All @@ -45,7 +45,7 @@
# fMRI data: a unique file for each session
func_filename = haxby_dataset.func[0]

##############################################################################
# %%
# Build a proper event structure for each session
# -----------------------------------------------

Expand All @@ -71,7 +71,7 @@
# remove the rest condition and insert into the dictionary
events[session] = events_[events_.trial_type != "rest"]

##############################################################################
# %%
# Instantiate and run FirstLevelModel
# -----------------------------------
#
Expand All @@ -92,7 +92,7 @@
memory="nilearn_cache",
)

##############################################################################
# %%
# Run the glm on data from each session
# -------------------------------------
events[session].trial_type.unique()
Expand All @@ -112,7 +112,7 @@
conditions_label.append(condition_)
session_label.append(session)

##############################################################################
# %%
# Generating a report
# -------------------
# Since we have already computed the FirstLevelModel
Expand All @@ -130,14 +130,14 @@

report # This report can be viewed in a notebook

##############################################################################
# %%
# In a jupyter notebook, the report will be automatically inserted, as above.
# We have several other ways to access the report:

# report.save_as_html('report.html')
# report.open_in_browser()

##############################################################################
# %%
# Build the decoding pipeline
# ---------------------------
# To define the decoding pipeline we use Decoder object, we choose :
Expand Down
12 changes: 6 additions & 6 deletions examples/02_decoding/plot_haxby_grid_search.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
"""

###########################################################################
# %%
# Load the Haxby dataset
# ----------------------
from nilearn import datasets
Expand Down Expand Up @@ -62,7 +62,7 @@
y = y[condition_mask]
session = labels["chunks"][condition_mask]

###########################################################################
# %%
# ANOVA pipeline with :class:`nilearn.decoding.Decoder` object
# ------------------------------------------------------------
#
Expand Down Expand Up @@ -102,7 +102,7 @@
param_grid=param_grid,
)

###########################################################################
# %%
# Fit the Decoder and predict the responses
# -----------------------------------------
# As a complete pipeline by itself, decoder will perform cross-validation
Expand Down Expand Up @@ -131,7 +131,7 @@
# Output the prediction with Decoder
y_pred = decoder.predict(fmri_niimgs)

###########################################################################
# %%
# Compute prediction scores with different values of screening percentile
# -----------------------------------------------------------------------
import numpy as np
Expand Down Expand Up @@ -159,7 +159,7 @@
val_scores.append(np.mean(y_pred == y[session == 10]))
print(f"Validation score: {val_scores[-1]:.4f}")

###########################################################################
# %%
# Nested cross-validation
# -----------------------
# We are going to tune the parameter 'screening_percentile' in the
Expand Down Expand Up @@ -192,7 +192,7 @@

print(f"Nested CV score: {np.mean(nested_cv_scores):.4f}")

###########################################################################
# %%
# Plot the prediction scores using matplotlib
# -------------------------------------------
from matplotlib import pyplot as plt
Expand Down

0 comments on commit 016f749

Please sign in to comment.