X = X[perm] # 2. CONSTRUCT TRAINING & TEST DATA rng = check_random_state(42) X_train, X_test, y_train, y_test = train_test_split( X, y, train_size=.8, random_state=rng) ########################################################################### # Fit the SpaceNet and predict with it decoder = SpaceNetRegressor(memory="nilearn_cache", penalty=fitpenalty, screening_percentile=screenp, memory_level=2, n_jobs=4) logging.info('Classifier set up. Starting model fit.') decoder.fit(X_train, y_train) # fit logging.info('Model fit complete. Saving outputs...') y_pred = decoder.predict(X_test).ravel() # predict mse = np.mean(np.abs(y_test - y_pred)) logging.info('Mean square error (MSE) of the prediction: %.2f' % mse) # 4. OUTPUTS # Save csv metadata inputdata.to_csv(logdir+inputcsv) # Save decoder object decoder_dir = './outputs/%s-%sx%s/decoder_sma/' % (timestamp,taskcode,predictor) # directory if not os.path.exists(decoder_dir): os.makedirs(decoder_dir) # create if missing dec_filename = '%s%s_decoder_SpaceNet_%sscreen%d.jbl' % ( decoder_dir, timestamp, decoder.penalty, screenp) joblib.dump(decoder, dec_filename) # Save coefficients to nifti file
# ------------------------------------- from nilearn.decoding import SpaceNetRegressor # To save time (because these are anat images with many voxels), we include # only the 5-percent voxels most correlated with the age variable to fit. # Also, we set memory_level=2 so that more of the intermediate computations # are cached. Also, you may pass and n_jobs=<some_high_value> to the # SpaceNetRegressor class, to take advantage of a multi-core system. # # Also, here we use a graph-net penalty but more beautiful results can be # obtained using the TV-l1 penalty, at the expense of longer runtimes. decoder = SpaceNetRegressor(memory="nilearn_cache", penalty="graph-net", screening_percentile=5., memory_level=2) decoder.fit(gm_imgs_train, age_train) # fit coef_img = decoder.coef_img_ y_pred = decoder.predict(gm_imgs_test).ravel() # predict mse = np.mean(np.abs(age_test - y_pred)) print('Mean square error (MSE) on the predicted age: %.2f' % mse) ########################################################################### # Visualize the resulting maps from nilearn.plotting import plot_stat_map, show # weights map background_img = gm_imgs[0] plot_stat_map(coef_img, background_img, title="graph-net weights", display_mode="z", cut_coords=1) ########################################################################### # Visualize the quality of predictions