-
Notifications
You must be signed in to change notification settings - Fork 0
/
perform_encoding.py
217 lines (179 loc) · 8.35 KB
/
perform_encoding.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# -*- coding: utf-8 -*-
import numpy as np
import os
import glob
import random
import argparse
import itertools
import nibabel as nib
from nilearn import plotting
from tqdm import tqdm
from sklearn.cross_decomposition import PLSRegression
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.preprocessing import StandardScaler
import torch
import time
import pickle
from tqdm import tqdm
from utils.ols import vectorized_correlation,OLS_pytorch
from utils.helper import save_dict,load_dict, saveasnii
def get_activations(activations_dir, layer_name):
"""This function loads neural network features/activations (preprocessed using PCA) into a
numpy array according to a given layer.
Parameters
----------
activations_dir : str
Path to PCA processed Neural Network features
layer_name : str
which layer of the neural network to load,
Returns
-------
train_activations : np.array
matrix of dimensions #train_vids x #pca_components
containing activations of train videos
test_activations : np.array
matrix of dimensions #test_vids x #pca_components
containing activations of test videos
"""
train_file = os.path.join(activations_dir,"train_" + layer_name + ".npy")
test_file = os.path.join(activations_dir,"test_" + layer_name + ".npy")
train_activations = np.load(train_file)
test_activations = np.load(test_file)
scaler = StandardScaler()
train_activations = scaler.fit_transform(train_activations)
test_activations = scaler.fit_transform(test_activations)
return train_activations, test_activations
def get_fmri(fmri_dir, ROI):
"""This function loads fMRI data into a numpy array for to a given ROI.
Parameters
----------
fmri_dir : str
path to fMRI data.
ROI : str
name of ROI.
Returns
-------
np.array
matrix of dimensions #train_vids x #repetitions x #voxels
containing fMRI responses to train videos of a given ROI
"""
# Loading ROI data
ROI_file = os.path.join(fmri_dir, ROI + ".pkl")
ROI_data = load_dict(ROI_file)
# averaging ROI data across repetitions
ROI_data_train = np.mean(ROI_data["train"], axis = 1)
if ROI == "WB":
voxel_mask = ROI_data['voxel_mask']
return ROI_data_train, voxel_mask
return ROI_data_train
def predict_fmri_fast(train_activations, test_activations, train_fmri,use_gpu=False):
"""This function fits a linear regressor using train_activations and train_fmri,
then returns the predicted fmri_pred_test using the fitted weights and
test_activations.
Parameters
----------
train_activations : np.array
matrix of dimensions #train_vids x #pca_components
containing activations of train videos.
test_activations : np.array
matrix of dimensions #test_vids x #pca_components
containing activations of test videos
train_fmri : np.array
matrix of dimensions #train_vids x #voxels
containing fMRI responses to train videos
use_gpu : bool
Description of parameter `use_gpu`.
Returns
-------
fmri_pred_test: np.array
matrix of dimensions #test_vids x #voxels
containing predicted fMRI responses to test videos .
"""
reg = OLS_pytorch(use_gpu)
reg.fit(train_activations,train_fmri.T)
fmri_pred_test = reg.predict(test_activations)
return fmri_pred_test
def main():
parser = argparse.ArgumentParser(description='Encoding model analysis for Algonauts 2021')
parser.add_argument('-rd','--result_dir', help='saves predicted fMRI activity',default = './results', type=str)
parser.add_argument('-ad','--activation_dir',help='directory containing DNN activations',default = './alexnet/', type=str)
parser.add_argument('-model','--model',help='model name under which predicted fMRI activity will be saved', default = 'alexnet_devkit', type=str)
parser.add_argument('-l','--layer',help='layer from which activations will be used to train and predict fMRI activity', default = 'layer_5', type=str)
parser.add_argument('-sub','--sub',help='subject number from which real fMRI data will be used', default = 'sub04', type=str)
parser.add_argument('-r','--roi',help='brain region, from which real fMRI data will be used', default = 'EBA', type=str)
parser.add_argument('-m','--mode',help='test or val, val returns mean correlation by using 10% of training data for validation', default = 'val', type=str)
parser.add_argument('-fd','--fmri_dir',help='directory containing fMRI activity', default = './participants_data_v2021', type=str)
parser.add_argument('-v','--visualize',help='visualize whole brain results in MNI space or not', default = True, type=bool)
parser.add_argument('-b', '--batch_size',help=' number of voxel to fit at one time in case of memory constraints', default = 1000, type=int)
args = vars(parser.parse_args())
mode = args['mode'] # test or val
sub = args['sub']
ROI = args['roi']
model = args['model']
layer = args['layer']
visualize_results = args['visualize']
batch_size = args['batch_size'] # number of voxel to fit at one time in case of memory constraints
if torch.cuda.is_available():
use_gpu = True
else:
use_gpu = False
if ROI == "WB":
track = "full_track"
else:
track = "mini_track"
activation_dir = os.path.join(args['activation_dir'],'pca_100')
fmri_dir = os.path.join(args['fmri_dir'], track)
sub_fmri_dir = os.path.join(fmri_dir, sub)
results_dir = os.path.join(args['result_dir'],args['model'], args['layer'], track, sub)
if not os.path.exists(results_dir):
os.makedirs(results_dir)
print("ROi is : ", ROI)
train_activations,test_activations = get_activations(activation_dir, layer)
if track == "full_track":
fmri_train_all,voxel_mask = get_fmri(sub_fmri_dir,ROI)
else:
fmri_train_all = get_fmri(sub_fmri_dir,ROI)
num_voxels = fmri_train_all.shape[1]
if mode == 'val':
# Here as an example we use first 900 videos as training and rest of the videos as validation
test_activations = train_activations[900:,:]
train_activations = train_activations[:900,:]
fmri_train = fmri_train_all[:900,:]
fmri_test = fmri_train_all[900:,:]
pred_fmri = np.zeros_like(fmri_test)
pred_fmri_save_path = os.path.join(results_dir, ROI + '_val.npy')
else:
fmri_train = fmri_train_all
num_test_videos = 102
pred_fmri = np.zeros((num_test_videos,num_voxels))
pred_fmri_save_path = os.path.join(results_dir, ROI + '_test.npy')
print("number of voxels is ", num_voxels)
iter = 0
while iter < num_voxels-batch_size:
pred_fmri[:,iter:iter+batch_size] = predict_fmri_fast(train_activations,test_activations,fmri_train[:,iter:iter+batch_size], use_gpu = use_gpu)
iter = iter+batch_size
print((100*iter)//num_voxels," percent complete")
pred_fmri[:,iter:] = predict_fmri_fast(train_activations,test_activations,fmri_train[:,iter:iter+batch_size], use_gpu = use_gpu)
if mode == 'val':
score = vectorized_correlation(fmri_test,pred_fmri)
print("----------------------------------------------------------------------------")
print("Mean correlation for ROI : ",ROI, "in ",sub, " is :", round(score.mean(), 3))
# result visualization for whole brain (full_track)
if track == "full_track" and visualize_results:
visual_mask_3D = np.zeros((78,93,71))
visual_mask_3D[voxel_mask==1]= score
brain_mask = './example.nii'
nii_save_path = os.path.join(results_dir, ROI + '_val.nii')
saveasnii(brain_mask,nii_save_path,visual_mask_3D)
view = plotting.view_img_on_surf(nii_save_path, threshold=None, surf_mesh='fsaverage',\
title = 'Correlation for sub' + sub, colorbar=False)
view_save_path = os.path.join(results_dir,ROI + '_val.html')
view.save_as_html(view_save_path)
print("Results saved in this directory: ", results_dir)
view.open_in_browser()
np.save(pred_fmri_save_path, pred_fmri)
print("----------------------------------------------------------------------------")
print("ROI done : ", ROI)
if __name__ == "__main__":
main()