We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Improve task mask pattern in examples
``` python
classification_target = stimuli[
    np.logical_not(resting_state)] == category
```

From #740, @AlexandreAbraham  said:

> I already found this line hard to understand before (I particularly dislike playing with the priority of operators = and ==) but now the new_line make it even more obscure. Maybe we could change by:
> 
> ```
> task_mask = np.logical_not(resting_state)  # or sample_mask?
> classification_target = (stimuli[task_mask] == category)
> ```

Quickly git-grepping it looks like this pattern is both present in:
examples/decoding/plot_haxby_different_estimators.py
examples/decoding/plot_haxby_full_analysis.py

They may be other places where this is used.


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `examples/decoding/plot_haxby_different_estimators.py`
Content:
```
1 """
2 Different classifiers in decoding the Haxby dataset
3 =====================================================
4 
5 Here we compare different classifiers on a visual object recognition
6 decoding task.
7 """
8 
9 import time
10 
11 ### Fetch data using nilearn dataset fetcher ################################
12 from nilearn import datasets
13 haxby_dataset = datasets.fetch_haxby(n_subjects=1)
14 
15 # print basic information on the dataset
16 print('First subject anatomical nifti image (3D) located is at: %s' %
17       haxby_dataset.anat[0])
18 print('First subject functional nifti image (4D) is located at: %s' %
19       haxby_dataset.func[0])
20 
21 # load labels
22 import numpy as np
23 labels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=" ")
24 stimuli = labels['labels']
25 # identify resting state labels in order to be able to remove them
26 resting_state = stimuli == b'rest'
27 
28 # find names of remaining active labels
29 categories = np.unique(stimuli[np.logical_not(resting_state)])
30 
31 # extract tags indicating to which acquisition run a tag belongs
32 session_labels = labels["chunks"][np.logical_not(resting_state)]
33 
34 # Load the fMRI data
35 from nilearn.input_data import NiftiMasker
36 
37 # For decoding, standardizing is often very important
38 mask_filename = haxby_dataset.mask_vt[0]
39 masker = NiftiMasker(mask_img=mask_filename, standardize=True)
40 func_filename = haxby_dataset.func[0]
41 masked_timecourses = masker.fit_transform(
42     func_filename)[np.logical_not(resting_state)]
43 
44 # Classifiers definition
45 
46 # A support vector classifier
47 from sklearn.svm import SVC
48 svm = SVC(C=1., kernel="linear")
49 
50 from sklearn.grid_search import GridSearchCV
51 # GridSearchCV is slow, but note that it takes an 'n_jobs' parameter that
52 # can significantly speed up the fitting process on computers with
53 # multiple cores
54 svm_cv = GridSearchCV(SVC(C=1., kernel="linear"),
55                       param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},
56                       scoring='f1')
57 
58 # The logistic regression
59 from sklearn.linear_model import LogisticRegression, RidgeClassifier, \
60     RidgeClassifierCV
61 logistic = LogisticRegression(C=1., penalty="l1")
62 logistic_50 = LogisticRegression(C=50., penalty="l1")
63 logistic_l2 = LogisticRegression(C=1., penalty="l2")
64 
65 logistic_cv = GridSearchCV(LogisticRegression(C=1., penalty="l1"),
66                            param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},
67                            scoring='f1')
68 logistic_l2_cv = GridSearchCV(LogisticRegression(C=1., penalty="l2"),
69                               param_grid={
70                                   'C': [.1, .5, 1., 5., 10., 50., 100.]},
71                               scoring='f1')
72 
73 ridge = RidgeClassifier()
74 ridge_cv = RidgeClassifierCV()
75 
76 
77 # Make a data splitting object for cross validation
78 from sklearn.cross_validation import LeaveOneLabelOut, cross_val_score
79 cv = LeaveOneLabelOut(session_labels)
80 
81 classifiers = {'SVC': svm,
82                'SVC cv': svm_cv,
83                'log l1': logistic,
84                'log l1 50': logistic_50,
85                'log l1 cv': logistic_cv,
86                'log l2': logistic_l2,
87                'log l2 cv': logistic_l2_cv,
88                'ridge': ridge,
89                'ridge cv': ridge_cv}
90 
91 classifiers_scores = {}
92 
93 for classifier_name, classifier in sorted(classifiers.items()):
94     classifiers_scores[classifier_name] = {}
95     print(70 * '_')
96 
97     for category in categories:
98         classification_target = stimuli[
99             np.logical_not(resting_state)] == category
100         t0 = time.time()
101         classifiers_scores[classifier_name][category] = cross_val_score(
102             classifier,
103             masked_timecourses,
104             classification_target,
105             cv=cv, scoring="f1")
106 
107         print("%10s: %14s -- scores: %1.2f +- %1.2f, time %.2fs" % (
108             classifier_name, category,
109             classifiers_scores[classifier_name][category].mean(),
110             classifiers_scores[classifier_name][category].std(),
111             time.time() - t0))
112 
113 ###############################################################################
114 # make a rudimentary diagram
115 import matplotlib.pyplot as plt
116 plt.figure()
117 
118 tick_position = np.arange(len(categories))
119 plt.xticks(tick_position, categories, rotation=45)
120 
121 for color, classifier_name in zip(
122         ['b', 'c', 'm', 'g', 'y', 'k', '.5', 'r', '#ffaaaa'],
123         sorted(classifiers)):
124     score_means = [classifiers_scores[classifier_name][category].mean()
125                    for category in categories]
126     plt.bar(tick_position, score_means, label=classifier_name,
127             width=.11, color=color)
128     tick_position = tick_position + .09
129 
130 plt.ylabel('Classification accurancy (f1 score)')
131 plt.xlabel('Visual stimuli category')
132 plt.ylim(ymin=0)
133 plt.legend(loc='lower center', ncol=3)
134 plt.title('Category-specific classification accuracy for different classifiers')
135 plt.tight_layout()
136 
137 ###############################################################################
138 # Plot the face vs house map for the different estimators
139 
140 # use the average EPI as a background
141 from nilearn import image
142 mean_epi_img = image.mean_img(func_filename)
143 
144 # Restrict the decoding to face vs house
145 condition_mask = np.logical_or(stimuli == b'face', stimuli == b'house')
146 masked_timecourses = masked_timecourses[
147     condition_mask[np.logical_not(resting_state)]]
148 stimuli = stimuli[condition_mask]
149 # Transform the stimuli to binary values
150 stimuli = (stimuli == b'face').astype(np.int)
151 
152 from nilearn.plotting import plot_stat_map, show
153 
154 for classifier_name, classifier in sorted(classifiers.items()):
155     classifier.fit(masked_timecourses, stimuli)
156 
157     if hasattr(classifier, 'coef_'):
158         weights = classifier.coef_[0]
159     elif hasattr(classifier, 'best_estimator_'):
160         weights = classifier.best_estimator_.coef_[0]
161     else:
162         continue
163     weight_img = masker.inverse_transform(weights)
164     weight_map = weight_img.get_data()
165     threshold = np.max(np.abs(weight_map)) * 1e-3
166     plot_stat_map(weight_img, bg_img=mean_epi_img,
167                   display_mode='z', cut_coords=[-17],
168                   threshold=threshold,
169                   title='%s: face vs house' % classifier_name)
170 
171 show()
172
```

Path: `examples/decoding/plot_haxby_full_analysis.py`
Content:
```
1 """
2 ROI-based decoding analysis in Haxby et al. dataset
3 =====================================================
4 
5 In this script we reproduce the data analysis conducted by
6 Haxby et al. in "Distributed and Overlapping Representations of Faces and
7 Objects in Ventral Temporal Cortex".
8 
9 Specifically, we look at decoding accuracy for different objects in
10 three different masks: the full ventral stream (mask_vt), the house
11 selective areas (mask_house) and the face selective areas (mask_face),
12 that have been defined via a standard GLM-based analysis.
13 
14 """
15 
16 
17 ### Fetch data using nilearn dataset fetcher ################################
18 from nilearn import datasets
19 haxby_dataset = datasets.fetch_haxby(n_subjects=1)
20 
21 # print basic information on the dataset
22 print('First subject anatomical nifti image (3D) located is at: %s' %
23       haxby_dataset.anat[0])
24 print('First subject functional nifti image (4D) is located at: %s' %
25       haxby_dataset.func[0])
26 
27 # Load nilearn NiftiMasker, the practical masking and unmasking tool
28 from nilearn.input_data import NiftiMasker
29 
30 # load labels
31 import numpy as np
32 labels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=" ")
33 stimuli = labels['labels']
34 
35 # identify resting state labels in order to be able to remove them
36 resting_state = stimuli == b"rest"
37 
38 # find names of remaining active labels
39 categories = np.unique(stimuli[np.logical_not(resting_state)])
40 
41 # extract tags indicating to which acquisition run a tag belongs
42 session_labels = labels["chunks"][np.logical_not(resting_state)]
43 
44 # The classifier: a support vector classifier
45 from sklearn.svm import SVC
46 classifier = SVC(C=1., kernel="linear")
47 
48 # A classifier to set the chance level
49 from sklearn.dummy import DummyClassifier
50 dummy_classifier = DummyClassifier()
51 
52 # Make a data splitting object for cross validation
53 from sklearn.cross_validation import LeaveOneLabelOut, cross_val_score
54 cv = LeaveOneLabelOut(session_labels)
55 
56 func_filename = haxby_dataset.func[0]
57 mask_names = ['mask_vt', 'mask_face', 'mask_house']
58 
59 mask_scores = {}
60 mask_chance_scores = {}
61 
62 for mask_name in mask_names:
63     print("Working on mask %s" % mask_name)
64     # For decoding, standardizing is often very important
65     mask_filename = haxby_dataset[mask_name][0]
66     masker = NiftiMasker(mask_img=mask_filename, standardize=True)
67     masked_timecourses = masker.fit_transform(
68         func_filename)[np.logical_not(resting_state)]
69 
70     mask_scores[mask_name] = {}
71     mask_chance_scores[mask_name] = {}
72 
73     for category in categories:
74         print("Processing %s %s" % (mask_name, category))
75         classification_target = stimuli[
76             np.logical_not(resting_state)] == category
77         mask_scores[mask_name][category] = cross_val_score(
78             classifier,
79             masked_timecourses,
80             classification_target,
81             cv=cv, scoring="f1")
82 
83         mask_chance_scores[mask_name][category] = cross_val_score(
84             dummy_classifier,
85             masked_timecourses,
86             classification_target,
87             cv=cv, scoring="f1")
88 
89         print("Scores: %1.2f +- %1.2f" % (
90             mask_scores[mask_name][category].mean(),
91             mask_scores[mask_name][category].std()))
92 
93 # make a rudimentary diagram
94 import matplotlib.pyplot as plt
95 plt.figure()
96 
97 tick_position = np.arange(len(categories))
98 plt.xticks(tick_position, categories, rotation=45)
99 
100 for color, mask_name in zip('rgb', mask_names):
101     score_means = [mask_scores[mask_name][category].mean()
102                    for category in categories]
103     plt.bar(tick_position, score_means, label=mask_name,
104             width=.25, color=color)
105 
106     score_chance = [mask_chance_scores[mask_name][category].mean()
107                     for category in categories]
108     plt.bar(tick_position, score_chance,
109             width=.25, edgecolor='k', facecolor='none')
110 
111     tick_position = tick_position + .2
112 
113 plt.ylabel('Classification accurancy (f1 score)')
114 plt.xlabel('Visual stimuli category')
115 plt.legend(loc='best')
116 plt.title('Category-specific classification accuracy for different masks')
117 plt.tight_layout()
118 
119 
120 plt.show()
121
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/examples/decoding/plot_haxby_different_estimators.py b/examples/decoding/plot_haxby_different_estimators.py
--- a/examples/decoding/plot_haxby_different_estimators.py
+++ b/examples/decoding/plot_haxby_different_estimators.py
@@ -95,8 +95,8 @@
     print(70 * '_')
 
     for category in categories:
-        classification_target = stimuli[
-            np.logical_not(resting_state)] == category
+        task_mask = np.logical_not(resting_state)
+        classification_target = (stimuli[task_mask] == category)
         t0 = time.time()
         classifiers_scores[classifier_name][category] = cross_val_score(
             classifier,
diff --git a/examples/decoding/plot_haxby_full_analysis.py b/examples/decoding/plot_haxby_full_analysis.py
--- a/examples/decoding/plot_haxby_full_analysis.py
+++ b/examples/decoding/plot_haxby_full_analysis.py
@@ -72,8 +72,8 @@
 
     for category in categories:
         print("Processing %s %s" % (mask_name, category))
-        classification_target = stimuli[
-            np.logical_not(resting_state)] == category
+        task_mask = np.logical_not(resting_state)
+        classification_target = (stimuli[task_mask] == category)
         mask_scores[mask_name][category] = cross_val_score(
             classifier,
             masked_timecourses,

{"golden_diff": "diff --git a/examples/decoding/plot_haxby_different_estimators.py b/examples/decoding/plot_haxby_different_estimators.py\n--- a/examples/decoding/plot_haxby_different_estimators.py\n+++ b/examples/decoding/plot_haxby_different_estimators.py\n@@ -95,8 +95,8 @@\n     print(70 * '_')\n \n     for category in categories:\n-        classification_target = stimuli[\n-            np.logical_not(resting_state)] == category\n+        task_mask = np.logical_not(resting_state)\n+        classification_target = (stimuli[task_mask] == category)\n         t0 = time.time()\n         classifiers_scores[classifier_name][category] = cross_val_score(\n             classifier,\ndiff --git a/examples/decoding/plot_haxby_full_analysis.py b/examples/decoding/plot_haxby_full_analysis.py\n--- a/examples/decoding/plot_haxby_full_analysis.py\n+++ b/examples/decoding/plot_haxby_full_analysis.py\n@@ -72,8 +72,8 @@\n \n     for category in categories:\n         print(\"Processing %s %s\" % (mask_name, category))\n-        classification_target = stimuli[\n-            np.logical_not(resting_state)] == category\n+        task_mask = np.logical_not(resting_state)\n+        classification_target = (stimuli[task_mask] == category)\n         mask_scores[mask_name][category] = cross_val_score(\n             classifier,\n             masked_timecourses,\n", "issue": "Improve task mask pattern in examples\n``` python\nclassification_target = stimuli[\n    np.logical_not(resting_state)] == category\n```\n\nFrom #740, @AlexandreAbraham  said:\n\n> I already found this line hard to understand before (I particularly dislike playing with the priority of operators = and ==) but now the new_line make it even more obscure. Maybe we could change by:\n> \n> ```\n> task_mask = np.logical_not(resting_state)  # or sample_mask?\n> classification_target = (stimuli[task_mask] == category)\n> ```\n\nQuickly git-grepping it looks like this pattern is both present in:\nexamples/decoding/plot_haxby_different_estimators.py\nexamples/decoding/plot_haxby_full_analysis.py\n\nThey may be other places where this is used.\n\n", "before_files": [{"content": "\"\"\"\nDifferent classifiers in decoding the Haxby dataset\n=====================================================\n\nHere we compare different classifiers on a visual object recognition\ndecoding task.\n\"\"\"\n\nimport time\n\n### Fetch data using nilearn dataset fetcher ################################\nfrom nilearn import datasets\nhaxby_dataset = datasets.fetch_haxby(n_subjects=1)\n\n# print basic information on the dataset\nprint('First subject anatomical nifti image (3D) located is at: %s' %\n      haxby_dataset.anat[0])\nprint('First subject functional nifti image (4D) is located at: %s' %\n      haxby_dataset.func[0])\n\n# load labels\nimport numpy as np\nlabels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=\" \")\nstimuli = labels['labels']\n# identify resting state labels in order to be able to remove them\nresting_state = stimuli == b'rest'\n\n# find names of remaining active labels\ncategories = np.unique(stimuli[np.logical_not(resting_state)])\n\n# extract tags indicating to which acquisition run a tag belongs\nsession_labels = labels[\"chunks\"][np.logical_not(resting_state)]\n\n# Load the fMRI data\nfrom nilearn.input_data import NiftiMasker\n\n# For decoding, standardizing is often very important\nmask_filename = haxby_dataset.mask_vt[0]\nmasker = NiftiMasker(mask_img=mask_filename, standardize=True)\nfunc_filename = haxby_dataset.func[0]\nmasked_timecourses = masker.fit_transform(\n    func_filename)[np.logical_not(resting_state)]\n\n# Classifiers definition\n\n# A support vector classifier\nfrom sklearn.svm import SVC\nsvm = SVC(C=1., kernel=\"linear\")\n\nfrom sklearn.grid_search import GridSearchCV\n# GridSearchCV is slow, but note that it takes an 'n_jobs' parameter that\n# can significantly speed up the fitting process on computers with\n# multiple cores\nsvm_cv = GridSearchCV(SVC(C=1., kernel=\"linear\"),\n                      param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                      scoring='f1')\n\n# The logistic regression\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier, \\\n    RidgeClassifierCV\nlogistic = LogisticRegression(C=1., penalty=\"l1\")\nlogistic_50 = LogisticRegression(C=50., penalty=\"l1\")\nlogistic_l2 = LogisticRegression(C=1., penalty=\"l2\")\n\nlogistic_cv = GridSearchCV(LogisticRegression(C=1., penalty=\"l1\"),\n                           param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                           scoring='f1')\nlogistic_l2_cv = GridSearchCV(LogisticRegression(C=1., penalty=\"l2\"),\n                              param_grid={\n                                  'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                              scoring='f1')\n\nridge = RidgeClassifier()\nridge_cv = RidgeClassifierCV()\n\n\n# Make a data splitting object for cross validation\nfrom sklearn.cross_validation import LeaveOneLabelOut, cross_val_score\ncv = LeaveOneLabelOut(session_labels)\n\nclassifiers = {'SVC': svm,\n               'SVC cv': svm_cv,\n               'log l1': logistic,\n               'log l1 50': logistic_50,\n               'log l1 cv': logistic_cv,\n               'log l2': logistic_l2,\n               'log l2 cv': logistic_l2_cv,\n               'ridge': ridge,\n               'ridge cv': ridge_cv}\n\nclassifiers_scores = {}\n\nfor classifier_name, classifier in sorted(classifiers.items()):\n    classifiers_scores[classifier_name] = {}\n    print(70 * '_')\n\n    for category in categories:\n        classification_target = stimuli[\n            np.logical_not(resting_state)] == category\n        t0 = time.time()\n        classifiers_scores[classifier_name][category] = cross_val_score(\n            classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        print(\"%10s: %14s -- scores: %1.2f +- %1.2f, time %.2fs\" % (\n            classifier_name, category,\n            classifiers_scores[classifier_name][category].mean(),\n            classifiers_scores[classifier_name][category].std(),\n            time.time() - t0))\n\n###############################################################################\n# make a rudimentary diagram\nimport matplotlib.pyplot as plt\nplt.figure()\n\ntick_position = np.arange(len(categories))\nplt.xticks(tick_position, categories, rotation=45)\n\nfor color, classifier_name in zip(\n        ['b', 'c', 'm', 'g', 'y', 'k', '.5', 'r', '#ffaaaa'],\n        sorted(classifiers)):\n    score_means = [classifiers_scores[classifier_name][category].mean()\n                   for category in categories]\n    plt.bar(tick_position, score_means, label=classifier_name,\n            width=.11, color=color)\n    tick_position = tick_position + .09\n\nplt.ylabel('Classification accurancy (f1 score)')\nplt.xlabel('Visual stimuli category')\nplt.ylim(ymin=0)\nplt.legend(loc='lower center', ncol=3)\nplt.title('Category-specific classification accuracy for different classifiers')\nplt.tight_layout()\n\n###############################################################################\n# Plot the face vs house map for the different estimators\n\n# use the average EPI as a background\nfrom nilearn import image\nmean_epi_img = image.mean_img(func_filename)\n\n# Restrict the decoding to face vs house\ncondition_mask = np.logical_or(stimuli == b'face', stimuli == b'house')\nmasked_timecourses = masked_timecourses[\n    condition_mask[np.logical_not(resting_state)]]\nstimuli = stimuli[condition_mask]\n# Transform the stimuli to binary values\nstimuli = (stimuli == b'face').astype(np.int)\n\nfrom nilearn.plotting import plot_stat_map, show\n\nfor classifier_name, classifier in sorted(classifiers.items()):\n    classifier.fit(masked_timecourses, stimuli)\n\n    if hasattr(classifier, 'coef_'):\n        weights = classifier.coef_[0]\n    elif hasattr(classifier, 'best_estimator_'):\n        weights = classifier.best_estimator_.coef_[0]\n    else:\n        continue\n    weight_img = masker.inverse_transform(weights)\n    weight_map = weight_img.get_data()\n    threshold = np.max(np.abs(weight_map)) * 1e-3\n    plot_stat_map(weight_img, bg_img=mean_epi_img,\n                  display_mode='z', cut_coords=[-17],\n                  threshold=threshold,\n                  title='%s: face vs house' % classifier_name)\n\nshow()\n", "path": "examples/decoding/plot_haxby_different_estimators.py"}, {"content": "\"\"\"\nROI-based decoding analysis in Haxby et al. dataset\n=====================================================\n\nIn this script we reproduce the data analysis conducted by\nHaxby et al. in \"Distributed and Overlapping Representations of Faces and\nObjects in Ventral Temporal Cortex\".\n\nSpecifically, we look at decoding accuracy for different objects in\nthree different masks: the full ventral stream (mask_vt), the house\nselective areas (mask_house) and the face selective areas (mask_face),\nthat have been defined via a standard GLM-based analysis.\n\n\"\"\"\n\n\n### Fetch data using nilearn dataset fetcher ################################\nfrom nilearn import datasets\nhaxby_dataset = datasets.fetch_haxby(n_subjects=1)\n\n# print basic information on the dataset\nprint('First subject anatomical nifti image (3D) located is at: %s' %\n      haxby_dataset.anat[0])\nprint('First subject functional nifti image (4D) is located at: %s' %\n      haxby_dataset.func[0])\n\n# Load nilearn NiftiMasker, the practical masking and unmasking tool\nfrom nilearn.input_data import NiftiMasker\n\n# load labels\nimport numpy as np\nlabels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=\" \")\nstimuli = labels['labels']\n\n# identify resting state labels in order to be able to remove them\nresting_state = stimuli == b\"rest\"\n\n# find names of remaining active labels\ncategories = np.unique(stimuli[np.logical_not(resting_state)])\n\n# extract tags indicating to which acquisition run a tag belongs\nsession_labels = labels[\"chunks\"][np.logical_not(resting_state)]\n\n# The classifier: a support vector classifier\nfrom sklearn.svm import SVC\nclassifier = SVC(C=1., kernel=\"linear\")\n\n# A classifier to set the chance level\nfrom sklearn.dummy import DummyClassifier\ndummy_classifier = DummyClassifier()\n\n# Make a data splitting object for cross validation\nfrom sklearn.cross_validation import LeaveOneLabelOut, cross_val_score\ncv = LeaveOneLabelOut(session_labels)\n\nfunc_filename = haxby_dataset.func[0]\nmask_names = ['mask_vt', 'mask_face', 'mask_house']\n\nmask_scores = {}\nmask_chance_scores = {}\n\nfor mask_name in mask_names:\n    print(\"Working on mask %s\" % mask_name)\n    # For decoding, standardizing is often very important\n    mask_filename = haxby_dataset[mask_name][0]\n    masker = NiftiMasker(mask_img=mask_filename, standardize=True)\n    masked_timecourses = masker.fit_transform(\n        func_filename)[np.logical_not(resting_state)]\n\n    mask_scores[mask_name] = {}\n    mask_chance_scores[mask_name] = {}\n\n    for category in categories:\n        print(\"Processing %s %s\" % (mask_name, category))\n        classification_target = stimuli[\n            np.logical_not(resting_state)] == category\n        mask_scores[mask_name][category] = cross_val_score(\n            classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        mask_chance_scores[mask_name][category] = cross_val_score(\n            dummy_classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        print(\"Scores: %1.2f +- %1.2f\" % (\n            mask_scores[mask_name][category].mean(),\n            mask_scores[mask_name][category].std()))\n\n# make a rudimentary diagram\nimport matplotlib.pyplot as plt\nplt.figure()\n\ntick_position = np.arange(len(categories))\nplt.xticks(tick_position, categories, rotation=45)\n\nfor color, mask_name in zip('rgb', mask_names):\n    score_means = [mask_scores[mask_name][category].mean()\n                   for category in categories]\n    plt.bar(tick_position, score_means, label=mask_name,\n            width=.25, color=color)\n\n    score_chance = [mask_chance_scores[mask_name][category].mean()\n                    for category in categories]\n    plt.bar(tick_position, score_chance,\n            width=.25, edgecolor='k', facecolor='none')\n\n    tick_position = tick_position + .2\n\nplt.ylabel('Classification accurancy (f1 score)')\nplt.xlabel('Visual stimuli category')\nplt.legend(loc='best')\nplt.title('Category-specific classification accuracy for different masks')\nplt.tight_layout()\n\n\nplt.show()\n", "path": "examples/decoding/plot_haxby_full_analysis.py"}], "after_files": [{"content": "\"\"\"\nDifferent classifiers in decoding the Haxby dataset\n=====================================================\n\nHere we compare different classifiers on a visual object recognition\ndecoding task.\n\"\"\"\n\nimport time\n\n### Fetch data using nilearn dataset fetcher ################################\nfrom nilearn import datasets\nhaxby_dataset = datasets.fetch_haxby(n_subjects=1)\n\n# print basic information on the dataset\nprint('First subject anatomical nifti image (3D) located is at: %s' %\n      haxby_dataset.anat[0])\nprint('First subject functional nifti image (4D) is located at: %s' %\n      haxby_dataset.func[0])\n\n# load labels\nimport numpy as np\nlabels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=\" \")\nstimuli = labels['labels']\n# identify resting state labels in order to be able to remove them\nresting_state = stimuli == b'rest'\n\n# find names of remaining active labels\ncategories = np.unique(stimuli[np.logical_not(resting_state)])\n\n# extract tags indicating to which acquisition run a tag belongs\nsession_labels = labels[\"chunks\"][np.logical_not(resting_state)]\n\n# Load the fMRI data\nfrom nilearn.input_data import NiftiMasker\n\n# For decoding, standardizing is often very important\nmask_filename = haxby_dataset.mask_vt[0]\nmasker = NiftiMasker(mask_img=mask_filename, standardize=True)\nfunc_filename = haxby_dataset.func[0]\nmasked_timecourses = masker.fit_transform(\n    func_filename)[np.logical_not(resting_state)]\n\n# Classifiers definition\n\n# A support vector classifier\nfrom sklearn.svm import SVC\nsvm = SVC(C=1., kernel=\"linear\")\n\nfrom sklearn.grid_search import GridSearchCV\n# GridSearchCV is slow, but note that it takes an 'n_jobs' parameter that\n# can significantly speed up the fitting process on computers with\n# multiple cores\nsvm_cv = GridSearchCV(SVC(C=1., kernel=\"linear\"),\n                      param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                      scoring='f1')\n\n# The logistic regression\nfrom sklearn.linear_model import LogisticRegression, RidgeClassifier, \\\n    RidgeClassifierCV\nlogistic = LogisticRegression(C=1., penalty=\"l1\")\nlogistic_50 = LogisticRegression(C=50., penalty=\"l1\")\nlogistic_l2 = LogisticRegression(C=1., penalty=\"l2\")\n\nlogistic_cv = GridSearchCV(LogisticRegression(C=1., penalty=\"l1\"),\n                           param_grid={'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                           scoring='f1')\nlogistic_l2_cv = GridSearchCV(LogisticRegression(C=1., penalty=\"l2\"),\n                              param_grid={\n                                  'C': [.1, .5, 1., 5., 10., 50., 100.]},\n                              scoring='f1')\n\nridge = RidgeClassifier()\nridge_cv = RidgeClassifierCV()\n\n\n# Make a data splitting object for cross validation\nfrom sklearn.cross_validation import LeaveOneLabelOut, cross_val_score\ncv = LeaveOneLabelOut(session_labels)\n\nclassifiers = {'SVC': svm,\n               'SVC cv': svm_cv,\n               'log l1': logistic,\n               'log l1 50': logistic_50,\n               'log l1 cv': logistic_cv,\n               'log l2': logistic_l2,\n               'log l2 cv': logistic_l2_cv,\n               'ridge': ridge,\n               'ridge cv': ridge_cv}\n\nclassifiers_scores = {}\n\nfor classifier_name, classifier in sorted(classifiers.items()):\n    classifiers_scores[classifier_name] = {}\n    print(70 * '_')\n\n    for category in categories:\n        task_mask = np.logical_not(resting_state)\n        classification_target = (stimuli[task_mask] == category)\n        t0 = time.time()\n        classifiers_scores[classifier_name][category] = cross_val_score(\n            classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        print(\"%10s: %14s -- scores: %1.2f +- %1.2f, time %.2fs\" % (\n            classifier_name, category,\n            classifiers_scores[classifier_name][category].mean(),\n            classifiers_scores[classifier_name][category].std(),\n            time.time() - t0))\n\n###############################################################################\n# make a rudimentary diagram\nimport matplotlib.pyplot as plt\nplt.figure()\n\ntick_position = np.arange(len(categories))\nplt.xticks(tick_position, categories, rotation=45)\n\nfor color, classifier_name in zip(\n        ['b', 'c', 'm', 'g', 'y', 'k', '.5', 'r', '#ffaaaa'],\n        sorted(classifiers)):\n    score_means = [classifiers_scores[classifier_name][category].mean()\n                   for category in categories]\n    plt.bar(tick_position, score_means, label=classifier_name,\n            width=.11, color=color)\n    tick_position = tick_position + .09\n\nplt.ylabel('Classification accurancy (f1 score)')\nplt.xlabel('Visual stimuli category')\nplt.ylim(ymin=0)\nplt.legend(loc='lower center', ncol=3)\nplt.title('Category-specific classification accuracy for different classifiers')\nplt.tight_layout()\n\n###############################################################################\n# Plot the face vs house map for the different estimators\n\n# use the average EPI as a background\nfrom nilearn import image\nmean_epi_img = image.mean_img(func_filename)\n\n# Restrict the decoding to face vs house\ncondition_mask = np.logical_or(stimuli == b'face', stimuli == b'house')\nmasked_timecourses = masked_timecourses[\n    condition_mask[np.logical_not(resting_state)]]\nstimuli = stimuli[condition_mask]\n# Transform the stimuli to binary values\nstimuli = (stimuli == b'face').astype(np.int)\n\nfrom nilearn.plotting import plot_stat_map, show\n\nfor classifier_name, classifier in sorted(classifiers.items()):\n    classifier.fit(masked_timecourses, stimuli)\n\n    if hasattr(classifier, 'coef_'):\n        weights = classifier.coef_[0]\n    elif hasattr(classifier, 'best_estimator_'):\n        weights = classifier.best_estimator_.coef_[0]\n    else:\n        continue\n    weight_img = masker.inverse_transform(weights)\n    weight_map = weight_img.get_data()\n    threshold = np.max(np.abs(weight_map)) * 1e-3\n    plot_stat_map(weight_img, bg_img=mean_epi_img,\n                  display_mode='z', cut_coords=[-17],\n                  threshold=threshold,\n                  title='%s: face vs house' % classifier_name)\n\nshow()\n", "path": "examples/decoding/plot_haxby_different_estimators.py"}, {"content": "\"\"\"\nROI-based decoding analysis in Haxby et al. dataset\n=====================================================\n\nIn this script we reproduce the data analysis conducted by\nHaxby et al. in \"Distributed and Overlapping Representations of Faces and\nObjects in Ventral Temporal Cortex\".\n\nSpecifically, we look at decoding accuracy for different objects in\nthree different masks: the full ventral stream (mask_vt), the house\nselective areas (mask_house) and the face selective areas (mask_face),\nthat have been defined via a standard GLM-based analysis.\n\n\"\"\"\n\n\n### Fetch data using nilearn dataset fetcher ################################\nfrom nilearn import datasets\nhaxby_dataset = datasets.fetch_haxby(n_subjects=1)\n\n# print basic information on the dataset\nprint('First subject anatomical nifti image (3D) located is at: %s' %\n      haxby_dataset.anat[0])\nprint('First subject functional nifti image (4D) is located at: %s' %\n      haxby_dataset.func[0])\n\n# Load nilearn NiftiMasker, the practical masking and unmasking tool\nfrom nilearn.input_data import NiftiMasker\n\n# load labels\nimport numpy as np\nlabels = np.recfromcsv(haxby_dataset.session_target[0], delimiter=\" \")\nstimuli = labels['labels']\n\n# identify resting state labels in order to be able to remove them\nresting_state = stimuli == b\"rest\"\n\n# find names of remaining active labels\ncategories = np.unique(stimuli[np.logical_not(resting_state)])\n\n# extract tags indicating to which acquisition run a tag belongs\nsession_labels = labels[\"chunks\"][np.logical_not(resting_state)]\n\n# The classifier: a support vector classifier\nfrom sklearn.svm import SVC\nclassifier = SVC(C=1., kernel=\"linear\")\n\n# A classifier to set the chance level\nfrom sklearn.dummy import DummyClassifier\ndummy_classifier = DummyClassifier()\n\n# Make a data splitting object for cross validation\nfrom sklearn.cross_validation import LeaveOneLabelOut, cross_val_score\ncv = LeaveOneLabelOut(session_labels)\n\nfunc_filename = haxby_dataset.func[0]\nmask_names = ['mask_vt', 'mask_face', 'mask_house']\n\nmask_scores = {}\nmask_chance_scores = {}\n\nfor mask_name in mask_names:\n    print(\"Working on mask %s\" % mask_name)\n    # For decoding, standardizing is often very important\n    mask_filename = haxby_dataset[mask_name][0]\n    masker = NiftiMasker(mask_img=mask_filename, standardize=True)\n    masked_timecourses = masker.fit_transform(\n        func_filename)[np.logical_not(resting_state)]\n\n    mask_scores[mask_name] = {}\n    mask_chance_scores[mask_name] = {}\n\n    for category in categories:\n        print(\"Processing %s %s\" % (mask_name, category))\n        task_mask = np.logical_not(resting_state)\n        classification_target = (stimuli[task_mask] == category)\n        mask_scores[mask_name][category] = cross_val_score(\n            classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        mask_chance_scores[mask_name][category] = cross_val_score(\n            dummy_classifier,\n            masked_timecourses,\n            classification_target,\n            cv=cv, scoring=\"f1\")\n\n        print(\"Scores: %1.2f +- %1.2f\" % (\n            mask_scores[mask_name][category].mean(),\n            mask_scores[mask_name][category].std()))\n\n# make a rudimentary diagram\nimport matplotlib.pyplot as plt\nplt.figure()\n\ntick_position = np.arange(len(categories))\nplt.xticks(tick_position, categories, rotation=45)\n\nfor color, mask_name in zip('rgb', mask_names):\n    score_means = [mask_scores[mask_name][category].mean()\n                   for category in categories]\n    plt.bar(tick_position, score_means, label=mask_name,\n            width=.25, color=color)\n\n    score_chance = [mask_chance_scores[mask_name][category].mean()\n                    for category in categories]\n    plt.bar(tick_position, score_chance,\n            width=.25, edgecolor='k', facecolor='none')\n\n    tick_position = tick_position + .2\n\nplt.ylabel('Classification accurancy (f1 score)')\nplt.xlabel('Visual stimuli category')\nplt.legend(loc='best')\nplt.title('Category-specific classification accuracy for different masks')\nplt.tight_layout()\n\n\nplt.show()\n", "path": "examples/decoding/plot_haxby_full_analysis.py"}]}