Example #1
0
def searchlight(x,
                y,
                m=None,
                groups=None,
                cv=None,
                write=False,
                logger=None,
                **searchlight_args):
    """
    Wrapper to launch searchlight
    :param x: Data
    :param y: labels
    :param m: mask
    :param groups: group labels
    :param cv: cross validator
    :param write: if image for writing is desired or not
    :param logger:
    :param searchlight_args:(default) process_mask_img(None),
                            radius(2mm), estimator(svc),
                            n_jobs(-1), scoring(none), cv(3fold), verbose(0)
    :return: trained SL object and SL results
    """
    write_to_logger("starting searchlight... ", logger)
    from nilearn import image, decoding, masking
    if m is None:
        m = masking.compute_epi_mask(x)
    write_to_logger("searchlight params: " + str(searchlight_args))
    sl = decoding.SearchLight(mask_img=m, cv=cv, **searchlight_args)
    sl.fit(x, y, groups)
    if write:
        return sl, image.new_img_like(image.mean_img(x), sl.scores_)
    else:
        return sl
process_mask_img = nibabel.Nifti1Image(process_mask.astype(np.int), np.eye(4))

coefs = np.reshape(coefs, [size, size, size])
plot_slices(coefs, title="Ground truth")

###############################################################################
# Compute the results and estimated coef maps for different estimators
classifiers = [
    ('bayesian_ridge', linear_model.BayesianRidge(normalize=True)),
    ('enet_cv', linear_model.ElasticNetCV(alphas=[5, 1, 0.5, 0.1],
                                          l1_ratio=0.05)),
    ('ridge_cv', linear_model.RidgeCV(alphas=[100, 10, 1, 0.1], cv=5)),
    ('svr', svm.SVR(kernel='linear', C=0.001)),
    ('searchlight', decoding.SearchLight(
        mask_img, process_mask_img=process_mask_img,
        radius=2.7, scoring='r2', estimator=svm.SVR(kernel="linear"),
        cv=KFold(y_train.size, n_folds=4),
        verbose=1, n_jobs=1))
]

# Run the estimators
for name, classifier in classifiers:
    t1 = time()
    if name != "searchlight":
        classifier.fit(X_train, y_train)
    else:
        X = nilearn.masking.unmask(X_train, mask_img)
        classifier.fit(X, y_train)
        del X
    elapsed_time = time() - t1
# that stands for `cross-validation`: in the list of possible `alpha`
# values that they are given, they choose the best by cross-validation.

estimators = [('bayesian_ridge', linear_model.BayesianRidge(normalize=True)),
              ('enet_cv',
               linear_model.ElasticNetCV(alphas=[5, 1, 0.5, 0.1],
                                         l1_ratio=0.05)),
              ('ridge_cv', linear_model.RidgeCV(alphas=[100, 10, 1, 0.1],
                                                cv=5)),
              ('svr', svm.SVR(kernel='linear', C=0.001)),
              ('searchlight',
               decoding.SearchLight(
                   mask_img,
                   process_mask_img=process_mask_img,
                   radius=2.7,
                   scoring='r2',
                   estimator=svm.SVR(kernel="linear"),
                   cv=KFold(n_splits=4),
                   verbose=1,
                   n_jobs=1,
               ))]

###############################################################################
# Run the estimators
#
# As the estimators expose a fairly consistent API, we can all fit them in
# a for loop: they all have a `fit` method for fitting the data, a `score`
# method to retrieve the prediction score, and because they are all linear
# models, a `coef_` attribute that stores the coefficients **w** estimated

for name, estimator in estimators:
    t1 = time()
Example #4
0
        # Combine with localizer data
        X_full = np.vstack((X, Y))
        run_labels_full = np.hstack((run_labels, run_labels_test))
        ev_labels_full = np.hstack((ev_labels, mapped_labels))

        # Create CV generator (1-fold, train on localizer, test on retrieval)
        cv = []
        trainIndices = np.where(np.in1d(run_labels_full, loc_run_list))
        testIndices = np.where(np.in1d(run_labels_full, mem_run_list))
        cv.append((trainIndices, testIndices))

        classifier = decoding.SearchLight(mask_img,
                                          radius=5.6,
                                          estimator=LogisticRegression(
                                              penalty='l2', C=1.),
                                          cv=cv,
                                          verbose=0,
                                          n_jobs=25)

        X_unmask = nilearn.masking.unmask(X_full, mask_img)
        print X_unmask.shape
        y = ev_labels_full
        print y.shape

        classifier.fit(X_unmask, y)

        # Save out scores in subj native space
        mean_fmri = image.mean_img(ts_path)
        searchlight_scores = image.new_img_like(mean_fmri, classifier.scores_)
        searchlight_scores.to_filename(
Example #5
0
#Get Process Mask
process_mask = nifti_masker.mask_img_.get_data().astype(np.int)
picked_slice = 29
process_mask[..., (picked_slice + 1):] = 0
process_mask[..., :picked_slice] = 0
process_mask [:, 30:] = 0
process_mask_img = image.new_img_like(nifti_masker.mask_img_, process_mask)

#CrossValidation
cv = KFold(clean_labels.size, n_folds=6)
print("presearch")
#Process mask
searchlight = decoding.SearchLight(
	nifti_masker.mask_img_,
	radius = 5.0,
	estimator=algorithm,
	n_jobs = 1,
	verbose=1,
	cv=cv,
	)
print("postsearch")

print(smooth_img.shape)
searchlight.fit(smooth_img, clean_labels)
print(searchlight.scores_.shape)

unique, counts = np.unique(searchlight.scores_, return_counts=True)
map = dict(zip(unique,counts))
print(map) 
#Get searchlight_img, and plot it
mean_fmri = image.mean_img(smooth_img)
searchlight_img = image.new_img_like(mean_fmri, searchlight.scores_)
Example #6
0
def run_searchlight(sub, space='T1w', factor='expression'):

    event_files = sorted(glob(f'../../{sub}/ses-*/func/*task-face*_events.tsv'))
    events = []
    for i, ev in enumerate(event_files):
        ev = pd.read_csv(ev, sep='\t').query("trial_type != 'response' and trial_type != 'rating'")
        ev['run'] = i+1
        ev['face_eth'] = ['asian' if 'sian' in s else s for s in ev['face_eth']]
        events.append(ev)
    
    events = pd.concat(events, axis=0)
    S = events.loc[:, factor]
    lab_enc = LabelEncoder()
    S = lab_enc.fit_transform(S)
    runs = events.loc[:, 'run']
    files = sorted(glob(f'../../derivatives/nibetaseries_lsa_unn/{sub}/ses-*/func/*task-face*space-{space}*STIM*_betaseries.nii.gz'))
    R = []
    pca = PCA(n_components=10)
    for ses in [1, 2]:
        for run in [1, 2, 3, 4, 5, 6]:
            these_f = [f for f in files if f'run-{run}' in f and f'ses-{ses}' in f]
            this_R = image.concat_imgs(these_f)
            brain_mask = image.math_img('img.mean(axis=3) != 0', img=this_R)
            this_R = image.math_img('(img - img.mean(axis=3, keepdims=True)) / img.std(axis=3, keepdims=True)', img=this_R)
            tmp = masking.apply_mask(this_R, brain_mask)
            #tmp_pca = pca.fit_transform(tmp)[:, :6]
            x = np.arange(tmp.shape[0])
            #b = np.polyfit(x, tmp_pca, deg=8)
            b = np.polyfit(x, tmp, deg=8)
            lf = np.polyval(b, x[:, np.newaxis])
            #tmp -= (lf @ np.linalg.lstsq(lf, tmp, rcond=-1)[0])
            tmp = tmp - lf
            this_R = masking.unmask(tmp, brain_mask)
            R.append(this_R)

    R = image.concat_imgs(R)
    R.to_filename('filt.nii.gz')
    mask = image.math_img('img.sum(axis=-1) != 0', img=R)
    process_mask = np.zeros(mask.shape)
    process_mask[:, :, 18:27] = 1
    process_mask = image.new_img_like(mask, process_mask)
    process_mask = masking.intersect_masks([process_mask, mask], threshold=1)

    clf = SVC(kernel='linear', class_weight='balanced')
    cv = LeaveOneGroupOut()
    b_acc = make_scorer(balanced_accuracy_score, adjusted=True)

    sl = decoding.SearchLight(
        mask_img=mask,
        process_mask_img=process_mask,
        radius=8,
        verbose=True,
        estimator=clf,
        cv=cv,
        scoring=b_acc,
        n_jobs=20
    )
    print("Starting fit ...")
    sl.fit(R, S, runs)
    scores = image.new_img_like(mask, sl.scores_)
    scores.to_filename(f'{sub}_factor-{factor}_balancedaccuracyFILT.nii.gz')