Skip to content

Instantly share code, notes, and snippets.

@feilong
Last active January 23, 2021 16:43
Show Gist options
  • Select an option

  • Save feilong/ccd73895cd9646870fae to your computer and use it in GitHub Desktop.

Select an option

Save feilong/ccd73895cd9646870fae to your computer and use it in GitHub Desktop.
#!/usr/bin/env python
"""
Enable debugging from commond line:
MVPA_DEBUG_METRICS=pid,asctime,reltime MVPA_DEBUG=SLC.* python some_script.py
"""
## kNN
kNN(k=2, dfx=<function squared_euclidean_distance>, voting='weighted')
"""
dfx : {one_minus_correlation, ...}
voting : {majority, weighted}
If 'weighted', votes are weighted according to the relative frequencies of each class in the training data.
"""
## detrending
poly_detrend(ds, polyord=1, chunks_attr='chunks')
## zscore
# zscore with the resting period (fixation etc.) as baseline
zscore(ds, param_est=('targets', ['rest']))
## Remove resting period
ds = ds[ds.sa.targets != 'rest']
## Average samples within each run
run_averager = mean_group_sample(['targets', 'chunks'])
ds = ds.get_mapped(run_averager)
## Feature selection
fsel = SensitivityBasedFeatureSelection(
OneWayAnova(),
FixedNElementTailSelector(500, mode='select', tail='upper'))
## Classification
clf.train(ds_train)
predictions = clf.predict(ds_test.samples)
np.mean(predictions == ds_test.sa.targets)
clf.set_postproc(BinaryFxNode(mean_mismatch_error, 'targets'))
clf.train(ds_train)
err = clf(ds_test) # err is a Dataset w/ only one number
## Meta classifiers
# MappedClassifier
metaclf = MappedClassifier(LinearCSVMC(), SVDMapper())
# FeatureSelectionClassifier is also MappedClassifier
fclf = FeatureSelectionClassifier(clf, fsel)
## Chain mapper
# select the first 2 SVD components
mapper = ChainMapper([SVDMapper(), StaticFeatureSelection(slice(None, 2))])
# Find events from targets
# an event looks like {'chunks': 0, 'duration': 6, 'onset': 0, 'targets': 'rest'}
find_events(targets=ds.sa.targets, chunks=ds.sa.chunks)
## GLM fit
evds = fit_event_hrf_model(ds, events, time_attr='time_coords', condition_attr=('targets', 'chunks'))
## From Dataset back to NIFTI files
# The mapper in `dataset` is used for reverse-mapping. If `data` is None, samples in `dataset` is used.
img = map2nifti(dataset, data=None)
img.to_filename('foobar.nii.gz')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment