<jupyter_start><jupyter_text>Section 2: Machine learning to predict age from rs-fmriWe will integrate what we've learned in the previous sections to extract data from *several* rs-fmri images, and use that data as features in a machine learning modelThe dataset consists of 50 children (ages 3-13) and 33 young adults (ages 18-39). We will use rs-fmri data to try to predict who are adults and who are children.  Load the data<jupyter_code># change this to the location where you downloaded the data
wdir = '/Users/jakevogel/Science/Nilearn_tutorial/reduced/'

# Now fetch the data

from glob import glob
import os
data = sorted(glob(os.path.join(wdir,'*.gz')))
confounds = sorted(glob(os.path.join(wdir,'*regressors.tsv')))<jupyter_output><empty_output><jupyter_text>How many individual subjects do we have?<jupyter_code>#len(data.func)
len(data)<jupyter_output><empty_output><jupyter_text>Extract features Here, we are going to use the same techniques we learned in the previous tutorial to extract rs-fmri connectivity features from every subject.How are we going to do that? With a for loop.Don't worry, it's not as scary as it sounds<jupyter_code># Here is a really simple for loop

for i in range(10):
    print('the number is', i)
container = []
for i in range(10):
    container.append(i)

container<jupyter_output><empty_output><jupyter_text>Now lets construct a more complicated loop to do what we want First we do some things we don't need to do in the loop. Let's reload our atlas, and re-iniate our masker and correlation_measure<jupyter_code>from nilearn.input_data import NiftiLabelsMasker
from nilearn.connectome import ConnectivityMeasure
from nilearn import datasets

# load atlas
multiscale = datasets.fetch_atlas_basc_multiscale_2015()
atlas_filename = multiscale.scale064

# initialize masker (change verbosity)
masker = NiftiLabelsMasker(labels_img=atlas_filename, standardize=True, 
                           memory='nilearn_cache', verbose=0)

# initialize correlation measure, set to vectorize
correlation_measure = ConnectivityMeasure(kind='correlation', vectorize=True,
                                         discard_diagonal=True)<jupyter_output><empty_output><jupyter_text>Okay -- now that we have that taken care of, let's run our big loop! **NOTE**: On a laptop, this might a few minutes.<jupyter_code>all_features = [] # here is where we will put the data (a container)

for i,sub in enumerate(data):
    # extract the timeseries from the ROIs in the atlas
    time_series = masker.fit_transform(sub, confounds=confounds[i])
    # create a region x region correlation matrix
    correlation_matrix = correlation_measure.fit_transform([time_series])[0]
    # add to our container
    all_features.append(correlation_matrix)
    # keep track of status
    print('finished %s of %s'%(i+1,len(data)))
# Let's save the data to disk
import numpy as np

np.savez_compressed('MAIN_BASC064_subsamp_features',a = all_features)<jupyter_output><empty_output><jupyter_text>In case you do not want to run the full loop on your computer, you can load the output of the loop here!<jupyter_code>feat_file = 'MAIN_BASC064_subsamp_features.npz'
X_features = np.load(feat_file)['a']
X_features.shape<jupyter_output><empty_output><jupyter_text>Okay so we've got our features. We can visualize our feature matrix<jupyter_code>import matplotlib.pyplot as plt

plt.imshow(X_features, aspect='auto')
plt.colorbar()
plt.title('feature matrix')
plt.xlabel('features')
plt.ylabel('subjects')<jupyter_output><empty_output><jupyter_text>Get Y (our target) and assess its distribution<jupyter_code># Let's load the phenotype data

pheno_path = os.path.join(wdir, 'participants.tsv')
from pandas import read_csv

pheno = read_csv(pheno_path, sep='\t').sort_values('participant_id')
pheno.head()<jupyter_output><empty_output><jupyter_text>Looks like there is a column labeling children and adults. Let's capture it in a variable<jupyter_code>y_ageclass = pheno['Child_Adult']
y_ageclass.head()<jupyter_output><empty_output><jupyter_text>Maybe we should have a look at the distribution of our target variable<jupyter_code>import matplotlib.pyplot as plt
import seaborn as sns
sns.countplot(y_ageclass)<jupyter_output><empty_output><jupyter_text>We are a bit unbalanced -- there seems to be more children than adults<jupyter_code>pheno.Child_Adult.value_counts()<jupyter_output><empty_output><jupyter_text>Prepare data for machine learningHere, we will define a "training sample" where we can play around with our models. We will also set aside a "test" sample that we will not touch until the end We want to be sure that our training and test sample are matched! We can do that with a "stratified split". Specifically, we will stratify by age class.<jupyter_code>from sklearn.model_selection import train_test_split

# Split the sample to training/test with a 60/40 ratio, and 
# stratify by age class, and also shuffle the data.

X_train, X_test, y_train, y_test = train_test_split(
                                                    X_features, # x
                                                    y_ageclass, # y
                                                    test_size = 0.4, # 60%/40% split  
                                                    shuffle = True, # shuffle dataset
                                                                    # before splitting
                                                    stratify = y_ageclass, # keep
                                                                           # distribution
                                                                           # of ageclass
                                                                           # consistent
                                                                           # betw. train
                                                                           # & test sets.
                                                    random_state = 123 # same shuffle each
                                                                       # time
                                                                       )

# print the size of our training and test groups
print('training:', len(X_train),
     'testing:', len(X_test))<jupyter_output><empty_output><jupyter_text>Let's visualize the distributions to be sure they are matched<jupyter_code>fig,(ax1,ax2) = plt.subplots(2)
sns.countplot(y_train, ax=ax1, order=['child','adult'])
ax1.set_title('Train')
sns.countplot(y_test, ax=ax2, order=['child','adult'])
ax2.set_title('Test')<jupyter_output><empty_output><jupyter_text>Run your first model!Machine learning can get pretty fancy pretty quickly. We'll start with a very standard classification model called a Support Vector Classifier (SVC). While this may seem unambitious, simple models can be very robust. And we don't have enough data to create more complex models.For more information, see this excellent resource:https://hal.inria.fr/hal-01824205 First, a quick review of SVM!![](https://docs.opencv.org/2.4/_images/optimal-hyperplane.png) Let's fit our first model!<jupyter_code>from sklearn.svm import SVC
l_svc = SVC(kernel='linear') # define the model

l_svc.fit(X_train, y_train) # fit the model<jupyter_output><empty_output><jupyter_text>Well... that was easy. Let's see how well the model learned the data!We can judge our model on several criteria:* Accuracy: The proportion of predictions that were correct overall.* Precision: Accuracy of cases predicted as positive* Recall: Number of true positives correctly predicted to be positive* f1 score: A balance between precision and recallOr, for a more visual explanation...![](https://upload.wikimedia.org/wikipedia/commons/2/26/Precisionrecall.svg)<jupyter_code>from sklearn.metrics import classification_report, confusion_matrix, precision_score, f1_score

# predict the training data based on the model
y_pred = l_svc.predict(X_train) 

# caluclate the model accuracy
acc = l_svc.score(X_train, y_train) 

# calculate the model precision, recall and f1, all in one convenient report!
cr = classification_report(y_true=y_train,
                      y_pred = y_pred)

# get a table to help us break down these scores
cm = confusion_matrix(y_true=y_train, y_pred = y_pred)<jupyter_output><empty_output><jupyter_text>Let's view our results and plot them all at once!<jupyter_code>import itertools
from pandas import DataFrame

# print results
print('accuracy:', acc)
print(cr)

# plot confusion matrix
cmdf = DataFrame(cm, index = ['Adult','Child'], columns = ['Adult','Child'])
sns.heatmap(cmdf, cmap = 'RdBu_r')
plt.xlabel('Predicted')
plt.ylabel('Observed')
# label cells in matrix
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j+0.5, i+0.5, format(cm[i, j], 'd'),
                 horizontalalignment="center",
                 color="white")<jupyter_output><empty_output><jupyter_text>![](https://sebastianraschka.com/images/faq/multiclass-metric/conf_mat.png) HOLY COW! Machine learning is amazing!!! Almost a perfect fit!...which means there's something wrong. What's the problem here?<jupyter_code>from sklearn.model_selection import cross_val_predict, cross_val_score

# predict
y_pred = cross_val_predict(l_svc, X_train, y_train, 
                           groups=y_train, cv=10)
# scores
acc = cross_val_score(l_svc, X_train, y_train, 
                     groups=y_train, cv=10)<jupyter_output><empty_output><jupyter_text>We can look at the accuracy of the predictions for each fold of the cross-validation<jupyter_code>for i in range(10):
    print('Fold %s -- Acc = %s'%(i, acc[i]))<jupyter_output><empty_output><jupyter_text>We can also look at the overall accuracy of the model<jupyter_code>from sklearn.metrics import accuracy_score
overall_acc = accuracy_score(y_pred = y_pred, y_true = y_train)
overall_cr = classification_report(y_pred = y_pred, y_true = y_train)
overall_cm = confusion_matrix(y_pred = y_pred, y_true = y_train)
print('Accuracy:',overall_acc)
print(overall_cr)

thresh = overall_cm.max() / 2
cmdf = DataFrame(overall_cm, index = ['Adult','Child'], columns = ['Adult','Child'])
sns.heatmap(cmdf, cmap='copper')
plt.xlabel('Predicted')
plt.ylabel('Observed')
for i, j in itertools.product(range(overall_cm.shape[0]), range(overall_cm.shape[1])):
        plt.text(j+0.5, i+0.5, format(overall_cm[i, j], 'd'),
                 horizontalalignment="center",
                 color="white")<jupyter_output><empty_output><jupyter_text>Not too bad at all!  Tweak your modelIt's very important to learn when and where its appropriate to "tweak" your model.Since we have done all of the previous analysis in our training data, it's find to try different models. But we **absolutely cannot** "test" it on our left out data. If we do, we are in great danger of overfitting.We could try other models, or tweak hyperparameters, but we are probably not powered sufficiently to do so, and would once again risk overfitting. But as a demonstration, we could see the impact of "scaling" our data. Certain machine learning algorithms perform better when all the input data is transformed to a uniform range of values. This is often between 0 and 1, or mean centered around with unit variance. We can perhaps look at the performance of the model after scaling the data<jupyter_code># Scale the training data
from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler().fit(X_train)
X_train_scl = scaler.transform(X_train)
plt.imshow(X_train, aspect='auto')
plt.colorbar()
plt.title('Training Data')
plt.xlabel('features')
plt.ylabel('subjects')
plt.imshow(X_train_scl, aspect='auto')
plt.colorbar()
plt.title('Scaled Training Data')
plt.xlabel('features')
plt.ylabel('subjects')
# repeat the steps above to re-fit the model 
# and assess its performance

# don't forget to switch X_train to X_train_scl

# predict
y_pred = cross_val_predict(l_svc, X_train_scl, y_train, 
                           groups=y_train, cv=10)

# get scores
overall_acc = accuracy_score(y_pred = y_pred, y_true = y_train)
overall_cr = classification_report(y_pred = y_pred, y_true = y_train)
overall_cm = confusion_matrix(y_pred = y_pred, y_true = y_train)
print('Accuracy:',overall_acc)
print(overall_cr)

# plot
thresh = overall_cm.max() / 2
cmdf = DataFrame(overall_cm, index = ['Adult','Child'], columns = ['Adult','Child'])
sns.heatmap(cmdf, cmap='copper')
plt.xlabel('Predicted')
plt.ylabel('Observed')
for i, j in itertools.product(range(overall_cm.shape[0]), range(overall_cm.shape[1])):
        plt.text(j+0.5, i+0.5, format(overall_cm[i, j], 'd'),
                 horizontalalignment="center",
                 color="white")<jupyter_output><empty_output><jupyter_text>What do you think about the results of this model compared to the non-transformed model? **Exercise:** Try fitting a new SVC model and tweak one of the many parameters. Run cross-validation and see how well it goes. Make a new cell and type SVC? to see the possible hyperparameters<jupyter_code># new_model = SVC()<jupyter_output><empty_output><jupyter_text>Can our model classify childrens from adults in completely un-seen data?Now that we've fit a model we think has possibly learned how to decode childhood vs adulthood based on rs-fmri signal, let's put it to the test. We will train our model on all of the training data, and try to predict the age of the subjects we left out at the beginning of this section. Because we performed a transformation on our training data, we will need to transform our testing data using the *same information!*<jupyter_code># Notice how we use the Scaler that was fit to X_train and apply to X_test,
# rather than creating a new Scaler for X_test
X_test_scl = scaler.transform(X_test)<jupyter_output><empty_output><jupyter_text>And now for the moment of truth! No cross-validation needed here. We simply fit the model with the training data and use it to predict the testing dataI'm so nervous. Let's just do it all in one cell<jupyter_code>l_svc.fit(X_train_scl, y_train) # fit to training data
y_pred = l_svc.predict(X_test_scl) # classify age class using testing data
acc = l_svc.score(X_test_scl, y_test) # get accuracy
cr = classification_report(y_pred=y_pred, y_true=y_test) # get prec., recall & f1
cm = confusion_matrix(y_pred=y_pred, y_true=y_test) # get confusion matrix

# print results
print('accuracy =', acc)
print(cr)

# plot results
thresh = cm.max() / 2
cmdf = DataFrame(cm, index = ['Adult','Child'], columns = ['Adult','Child'])
sns.heatmap(cmdf, cmap='RdBu_r')
plt.xlabel('Predicted')
plt.ylabel('Observed')
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
        plt.text(j+0.5, i+0.5, format(cm[i, j], 'd'),
                 horizontalalignment="center",
                 color="white")<jupyter_output><empty_output><jupyter_text>***Wow!!*** Congratulations. You just trained a machine learning model that used real rs-fmri data to predict the age of real humans.It seems like something in this data does seem to be systematically related to age ... but what?    Interpreting model feature importancesInterpreting the feature importances of a machine learning model is a real can of worms. This is an area of active research. Unfortunately, it's hard to trust the feature importance of some models. You can find a whole tutorial on this subject here:http://gael-varoquaux.info/interpreting_ml_tuto/index.htmlFor now, we'll just eschew better judgement and take a look at our feature importances We can access the feature importances (weights) used my the model<jupyter_code>l_svc.coef_<jupyter_output><empty_output><jupyter_text>lets plot these weights to see their distribution better<jupyter_code>plt.bar(range(l_svc.coef_.shape[-1]),l_svc.coef_[0])
plt.title('feature importances')
plt.xlabel('feature')
plt.ylabel('weight')<jupyter_output><empty_output><jupyter_text>Or perhaps it will be easier to visualize this information as a matrix similar to the one we started withWe can use the correlation measure from before to perform an inverse transform<jupyter_code>correlation_measure.inverse_transform(l_svc.coef_).shape
from nilearn import plotting

feat_exp_matrix = correlation_measure.inverse_transform(l_svc.coef_)[0]

plotting.plot_matrix(feat_exp_matrix, figure=(10, 8),  
                     labels=range(feat_exp_matrix.shape[0]),
                     reorder=False,
                    tri='lower')<jupyter_output><empty_output><jupyter_text>Let's see if we can throw those features onto an actual brain.First, we'll need to gather the coordinates of each ROI of our atlas<jupyter_code>coords = plotting.find_parcellation_cut_coords(atlas_filename)<jupyter_output><empty_output><jupyter_text>And now we can use our feature matrix and the wonders of nilearn to create a connectome map where each node is an ROI, and each connection is weighted by the importance of the feature to the model<jupyter_code>plotting.plot_connectome(feat_exp_matrix, coords, colorbar=True)<jupyter_output><empty_output><jupyter_text>Whoa!! That's...a lot to process. Maybe let's threshold the edges so that only the most important connections are visualized<jupyter_code>plotting.plot_connectome(feat_exp_matrix, coords, colorbar=True, edge_threshold=0.04)<jupyter_output><empty_output><jupyter_text>That's definitely an improvement, but it's still a bit hard to see what's going on.Nilearn has a new feature that let's use view this data interactively!<jupyter_code>plotting.view_connectome(feat_exp_matrix, coords, threshold='90%')
#view = plotting.view_connectome(feat_exp_matrix, coords, threshold='90%')    
#view.open_in_browser()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.08956152758132956, 'fraction_numerical': 0.006789250353606789, 'mean_word_length': 4.023017902813299, 'pattern_counts': {'":': 0, '<': 121, '<?xml version=': 0, '>': 121, 'https://': 4, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 39, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '30', 'dir': 'jupyter-structured-clean-dedup', 'id': '212468', 'license': 'MIT', 'n_tokens_mistral': 5437, 'n_tokens_neox': 5209, 'n_words': 1720, 'path': 'MAIN_tutorial_machine_learning_with_nilearn.ipynb', 'repo_name': 'ltetrel/introML', 'size': '17675'}