code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
max_sigma = 2.0 * math.pow(np.nanmax(np.std(R, axis=0)), 2)
return max_sigma | def _get_max_sigma(self, R) | Calculate maximum sigma of scanner RAS coordinates
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
max_sigma : float
The maximum sigma of scanner coordinates. | 4.91178 | 5.244704 | 0.936522 |
max_sigma = self._get_max_sigma(R)
final_lower = np.zeros(self.K * (self.n_dim + 1))
final_lower[0:self.K * self.n_dim] =\
np.tile(np.nanmin(R, axis=0), self.K)
final_lower[self.K * self.n_dim:] =\
np.repeat(self.lower_ratio * max_sigma, self.K)
... | def get_bounds(self, R) | Calculate lower and upper bounds for centers and widths
Parameters
----------
R : 2D array, with shape [n_voxel, n_dim]
The coordinate matrix of fMRI data from one subject
Returns
-------
bounds : 2-tuple of array_like, default: None
The lower... | 1.8959 | 1.842941 | 1.028736 |
centers = self.get_centers(estimate)
widths = self.get_widths(estimate)
recon = X.size
other_err = 0 if template_centers is None else (2 * self.K)
final_err = np.zeros(recon + other_err)
F = self.get_factors(unique_R, inds, centers, widths)
sigma = np.ze... | def _residual_multivariate(
self,
estimate,
unique_R,
inds,
X,
W,
template_centers,
template_centers_mean_cov,
template_widths,
template_widths_mean_var_reci,
data_sigma) | Residual function for estimating centers and widths
Parameters
----------
estimate : 1D array
Initial estimation on centers
unique_R : a list of array,
Each element contains unique value in one dimension of
coordinate matrix R.
inds : a lis... | 4.738464 | 4.440427 | 1.067119 |
# least_squares only accept x in 1D format
init_estimate = np.hstack(
(init_centers.ravel(), init_widths.ravel())) # .copy()
data_sigma = 1.0 / math.sqrt(2.0) * np.std(X)
final_estimate = least_squares(
self._residual_multivariate,
init_estim... | def _estimate_centers_widths(
self,
unique_R,
inds,
X,
W,
init_centers,
init_widths,
template_centers,
template_widths,
template_centers_mean_cov,
template_widths_mean_var_reci) | Estimate centers and widths
Parameters
----------
unique_R : a list of array,
Each element contains unique value in one dimension of
coordinate matrix R.
inds : a list of array,
Each element contains the indices to reconstruct one
dimens... | 3.152459 | 3.183125 | 0.990366 |
if template_prior is None:
template_centers = None
template_widths = None
template_centers_mean_cov = None
template_widths_mean_var_reci = None
else:
template_centers = self.get_centers(template_prior)
template_widths = sel... | def _fit_tfa(self, data, R, template_prior=None) | TFA main algorithm
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data from one subject.
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_prior : 1D array,
The template prior... | 2.773533 | 2.846088 | 0.974507 |
unique_R = []
inds = []
for d in np.arange(self.n_dim):
tmp_unique, tmp_inds = np.unique(R[:, d], return_inverse=True)
unique_R.append(tmp_unique)
inds.append(tmp_inds)
return unique_R, inds | def get_unique_R(self, R) | Get unique vlaues from coordinate matrix
Parameters
----------
R : 2D array
The coordinate matrix of a subject's fMRI data
Return
------
unique_R : a list of array,
Each element contains unique value in one dimension of
coordinate ma... | 2.268545 | 2.079082 | 1.091129 |
nfeature = data.shape[0]
nsample = data.shape[1]
feature_indices =\
np.random.choice(nfeature, self.max_num_voxel, replace=False)
sample_features = np.zeros(nfeature).astype(bool)
sample_features[feature_indices] = True
samples_indices =\
... | def _fit_tfa_inner(
self,
data,
R,
template_centers,
template_widths,
template_centers_mean_cov,
template_widths_mean_var_reci) | Fit TFA model, the inner loop part
Parameters
----------
data: 2D array, in shape [n_voxel, n_tr]
The fMRI data of a subject
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_centers: 1D array
The tem... | 2.981094 | 2.880653 | 1.034867 |
if self.verbose:
logger.info('Start to fit TFA ')
if not isinstance(X, np.ndarray):
raise TypeError("Input data should be an array")
if X.ndim != 2:
raise TypeError("Input data should be 2D array")
if not isinstance(R, np.ndarray):
... | def fit(self, X, R, template_prior=None) | Topographical Factor Analysis (TFA)[Manning2014]
Parameters
----------
X : 2D array, in shape [n_voxel, n_sample]
The fMRI data of one subject
R : 2D array, in shape [n_voxel, n_dim]
The voxel coordinate matrix of fMRI data
template_prior : None or 1D a... | 3.133541 | 2.927403 | 1.070416 |
recon = F.dot(W).ravel()
err = mean_squared_error(
data.ravel(),
recon,
multioutput='uniform_average')
return math.sqrt(err) | def recon_err(data, F, W) | Calcuate reconstruction error
Parameters
----------
data : 2D array
True data to recover.
F : 2D array
HTFA factor matrix.
W : 2D array
HTFA weight matrix.
Returns
-------
float
Returns root mean squared reconstruction error. | 4.492583 | 6.174216 | 0.727636 |
W = htfa.get_weights(data, F)
return recon_err(data, F, W) | def get_train_err(htfa, data, F) | Calcuate training error
Parameters
----------
htfa : HTFA
An instance of HTFA, factor anaysis class in BrainIAK.
data : 2D array
Input data to HTFA.
F : 2D array
HTFA factor matrix.
Returns
-------
float
Returns root mean squared error o... | 5.959761 | 8.76231 | 0.680159 |
clf = bcast_var[2]
data = l[0][mask, :].T
# print(l[0].shape, mask.shape, data.shape)
skf = model_selection.StratifiedKFold(n_splits=bcast_var[1],
shuffle=False)
accuracy = np.mean(model_selection.cross_val_score(clf, data,
... | def _sfn(l, mask, myrad, bcast_var) | Score classifier on searchlight data using cross-validation.
The classifier is in `bcast_var[2]`. The labels are in `bast_var[0]`. The
number of cross-validation folds is in `bast_var[1]. | 3.48752 | 2.863548 | 1.217902 |
rank = MPI.COMM_WORLD.Get_rank()
if rank == 0:
logger.info(
'running activity-based voxel selection via Searchlight'
)
self.sl.distribute([self.data], self.mask)
self.sl.broadcast((self.labels, self.num_folds, clf))
if rank == 0:
... | def run(self, clf) | run activity-based voxel selection
Sort the voxels based on the cross-validation accuracy
of their activity vectors within the searchlight
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-----... | 5.902512 | 4.261989 | 1.38492 |
# no shuffling in cv
skf = model_selection.StratifiedKFold(n_splits=num_folds,
shuffle=False)
scores = model_selection.cross_val_score(clf, subject_data,
y=labels,
cv=skf,... | def _cross_validation_for_one_voxel(clf, vid, num_folds, subject_data, labels) | Score classifier on data using cross validation. | 3.141211 | 3.234481 | 0.971164 |
rank = MPI.COMM_WORLD.Get_rank()
if rank == self.master_rank:
results = self._master()
# Sort the voxels
results.sort(key=lambda tup: tup[1], reverse=True)
else:
self._worker(clf)
results = []
return results | def run(self, clf) | Run correlation-based voxel selection in master-worker model.
Sort the voxels based on the cross-validation accuracy
of their correlation vectors
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
... | 5.18786 | 4.250209 | 1.220613 |
logger.info(
'Master at rank %d starts to allocate tasks',
MPI.COMM_WORLD.Get_rank()
)
results = []
comm = MPI.COMM_WORLD
size = comm.Get_size()
sending_voxels = self.voxel_unit if self.voxel_unit < self.num_voxels \
else self.... | def _master(self) | Master node's operation.
Assigning tasks to workers and collecting results from them
Parameters
----------
None
Returns
-------
results: list of tuple (voxel_id, accuracy)
the accuracy numbers of all voxels, in accuracy descending order
... | 2.292363 | 2.202826 | 1.040646 |
logger.debug(
'worker %d is running, waiting for tasks from master at rank %d' %
(MPI.COMM_WORLD.Get_rank(), self.master_rank)
)
comm = MPI.COMM_WORLD
status = MPI.Status()
while 1:
task = comm.recv(source=self.master_rank,
... | def _worker(self, clf) | Worker node's operation.
Receiving tasks from the master to process and sending the result back
Parameters
----------
clf: classification function
the classifier to be used in cross validation
Returns
-------
None | 3.664976 | 3.575085 | 1.025144 |
time1 = time.time()
s = task[0]
nEpochs = len(self.raw_data)
logger.debug(
'start to compute the correlation: #epochs: %d, '
'#processed voxels: %d, #total voxels to compute against: %d' %
(nEpochs, task[1], self.num_voxels2)
)
... | def _correlation_computation(self, task) | Use BLAS API to do correlation computation (matrix multiplication).
Parameters
----------
task: tuple (start_voxel_id, num_processed_voxels)
depicting the voxels assigned to compute
Returns
-------
corr: 3D array in shape [num_processed_voxels, num_epochs, n... | 3.581337 | 3.20664 | 1.11685 |
time1 = time.time()
(sv, e, av) = corr.shape
for i in range(sv):
start = 0
while start < e:
cur_val = corr[i, start: start + self.epochs_per_subj, :]
cur_val = .5 * np.log((cur_val + 1) / (1 - cur_val))
corr[i, star... | def _correlation_normalization(self, corr) | Do within-subject normalization.
This method uses scipy.zscore to normalize the data,
but is much slower than its C++ counterpart.
It is doing in-place z-score.
Parameters
----------
corr: 3D array in shape [num_processed_voxels, num_epochs, num_voxels]
the ... | 4.064946 | 3.53786 | 1.148984 |
time1 = time.time()
(num_processed_voxels, num_epochs, _) = corr.shape
if isinstance(clf, sklearn.svm.SVC) and clf.kernel == 'precomputed':
# kernel matrices should be computed
kernel_matrices = np.zeros((num_processed_voxels, num_epochs,
... | def _prepare_for_cross_validation(self, corr, clf) | Prepare data for voxelwise cross validation.
If the classifier is sklearn.svm.SVC with precomputed kernel,
the kernel matrix of each voxel is computed, otherwise do nothing.
Parameters
----------
corr: 3D array in shape [num_processed_voxels, num_epochs, num_voxels]
... | 4.42861 | 3.644763 | 1.215061 |
time1 = time.time()
if isinstance(clf, sklearn.svm.SVC) and clf.kernel == 'precomputed'\
and self.use_multiprocessing:
inlist = [(clf, i + task[0], self.num_folds, data[i, :, :],
self.labels) for i in range(task[1])]
with multipro... | def _do_cross_validation(self, clf, data, task) | Run voxelwise cross validation based on correlation vectors.
clf: classification function
the classifier to be used in cross validation
data: 3D numpy array
If using sklearn.svm.SVC with precomputed kernel,
it is in shape [num_processed_voxels, num_epochs, num_epochs... | 2.844017 | 2.541203 | 1.119162 |
time1 = time.time()
# correlation computation
corr = self._correlation_computation(task)
# normalization
# corr = self._correlation_normalization(corr)
time3 = time.time()
fcma_extension.normalization(corr, self.epochs_per_subj)
time4 = time.time(... | def _voxel_scoring(self, task, clf) | The voxel selection process done in the worker node.
Take the task in,
do analysis on voxels specified by the task (voxel id, num_voxels)
It is a three-stage pipeline consisting of:
1. correlation computation
2. within-subject normalization
3. voxelwise cross validation
... | 5.239889 | 4.504151 | 1.163346 |
logger.info('Starting SS-SRM')
# Check that the alpha value is in range (0.0,1.0)
if 0.0 >= self.alpha or self.alpha >= 1.0:
raise ValueError("Alpha parameter should be in range (0.0, 1.0)")
# Check that the regularizer value is positive
if 0.0 >= self.gamm... | def fit(self, X, y, Z) | Compute the Semi-Supervised Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, n_align]
Each element in the list contains the fMRI data for alignment of
one subject. There are n_align samples for each subject.
y : ... | 3.446848 | 3.195484 | 1.078662 |
self.classes_ = unique_labels(utils.concatenate_not_none(y))
new_y = [None] * len(y)
for s in range(len(y)):
new_y[s] = np.digitize(y[s], self.classes_) - 1
return new_y | def _init_classes(self, y) | Map all possible classes to the range [0,..,C-1]
Parameters
----------
y : list of arrays of int, each element has shape=[samples_i,]
Labels of the samples for each subject
Returns
-------
new_y : list of arrays of int, each element has shape=[samples_i,]
... | 3.81769 | 3.318319 | 1.150489 |
# Check if the model exist
if hasattr(self, 'w_') is False:
raise NotFittedError("The model fit has not been run yet.")
# Check the number of subjects
if len(X) != len(self.w_):
raise ValueError("The number of subjects does not match the one"
... | def predict(self, X) | Classify the output for given data
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples_i]
Each element in the list contains the fMRI data of one subject
The number of voxels should be according to each subject at
the moment of... | 3.997304 | 3.852075 | 1.037702 |
classes = self.classes_.size
# Initialization:
self.random_state_ = np.random.RandomState(self.rand_seed)
random_states = [
np.random.RandomState(self.random_state_.randint(2**32))
for i in range(len(data_align))]
# Set Wi's to a random orthogona... | def _sssrm(self, data_align, data_sup, labels) | Block-Coordinate Descent algorithm for fitting SS-SRM.
Parameters
----------
data_align : list of 2D arrays, element i has shape=[voxels_i, n_align]
Each element in the list contains the fMRI data for alignment of
one subject. There are n_align samples for each subject.... | 2.677859 | 2.503807 | 1.069515 |
# Stack the data and labels for training the classifier
data_stacked, labels_stacked, weights = \
SSSRM._stack_list(data, labels, w)
features = w[0].shape[1]
total_samples = weights.size
data_th = S.shared(data_stacked.astype(theano.config.floatX))
... | def _update_classifier(self, data, labels, w, classes) | Update the classifier parameters theta and bias
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples_i]
Each element in the list contains the fMRI data of one subject for
the classification task.
labels : list of arrays of int,... | 3.98794 | 3.847744 | 1.036436 |
s = np.zeros((w[0].shape[1], data[0].shape[1]))
for m in range(len(w)):
s = s + w[m].T.dot(data[m])
s /= len(w)
return s | def _compute_shared_response(data, w) | Compute the shared response S
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
w : list of 2D arrays, element i has shape=[voxels_i, features]
The orthogonal ... | 2.863352 | 2.609467 | 1.097294 |
subjects = len(data_align)
# Compute the SRM loss
f_val = 0.0
for subject in range(subjects):
samples = data_align[subject].shape[1]
f_val += (1 - self.alpha) * (0.5 / samples) \
* np.linalg.norm(data_align[subject] - w[subject].dot(s),
... | def _objective_function(self, data_align, data_sup, labels, w, s, theta,
bias) | Compute the objective function of the Semi-Supervised SRM
See :eq:`sssrm-eq`.
Parameters
----------
data_align : list of 2D arrays, element i has shape=[voxels_i, n_align]
Each element in the list contains the fMRI data for alignment of
one subject. There are n... | 4.038027 | 3.565099 | 1.132655 |
# Compute the SRM loss
f_val = 0.0
samples = data_align.shape[1]
f_val += (1 - self.alpha) * (0.5 / samples) \
* np.linalg.norm(data_align - w.dot(s), 'fro')**2
# Compute the MLR loss
f_val += self._loss_lr_subject(data_sup, labels, w, theta, bias)
... | def _objective_function_subject(self, data_align, data_sup, labels, w, s,
theta, bias) | Compute the objective function for one subject.
.. math:: (1-C)*Loss_{SRM}_i(W_i,S;X_i)
.. math:: + C/\\gamma * Loss_{MLR_i}(\\theta, bias; {(W_i^T*Z_i, y_i})
.. math:: + R(\\theta)
Parameters
----------
data_align : 2D array, shape=[voxels_i, samples_align]
... | 4.451812 | 3.707336 | 1.200811 |
if data is None:
return 0.0
samples = data.shape[1]
thetaT_wi_zi_plus_bias = theta.T.dot(w.T.dot(data)) + bias
sum_exp, max_value, _ = utils.sumexp_stable(thetaT_wi_zi_plus_bias)
sum_exp_values = np.log(sum_exp) + max_value
aux = 0.0
for sa... | def _loss_lr_subject(self, data, labels, w, theta, bias) | Compute the Loss MLR for a single subject (without regularization)
Parameters
----------
data : array, shape=[voxels, samples]
The fMRI data of subject i for the classification task.
labels : array of int, shape=[samples]
The labels for the data samples in data... | 4.241104 | 4.657131 | 0.910669 |
subjects = len(data)
loss = 0.0
for subject in range(subjects):
if labels[subject] is not None:
loss += self._loss_lr_subject(data[subject], labels[subject],
w[subject], theta, bias)
return loss + 0.5 * n... | def _loss_lr(self, data, labels, w, theta, bias) | Compute the Loss MLR (with the regularization)
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples_i]
Each element in the list contains the fMRI data of one subject for
the classification task.
labels : list of arrays of int, ... | 2.92911 | 3.024371 | 0.968502 |
labels_stacked = utils.concatenate_not_none(data_labels)
weights = np.empty((labels_stacked.size,))
data_shared = [None] * len(data)
curr_samples = 0
for s in range(len(data)):
if data[s] is not None:
subject_samples = data[s].shape[1]
... | def _stack_list(data, data_labels, w) | Construct a numpy array by stacking arrays in a list
Parameter
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples_i]
Each element in the list contains the fMRI data of one subject for
the classification task.
data_labels : list of array... | 3.378434 | 3.010392 | 1.122257 |
voxel_fn = extra_params[0]
shape_mask = extra_params[1]
min_active_voxels_proportion = extra_params[2]
outmat = np.empty(msk.shape, dtype=np.object)[mysl_rad:-mysl_rad,
mysl_rad:-mysl_rad,
mysl_rad:... | def _singlenode_searchlight(l, msk, mysl_rad, bcast_var, extra_params) | Run searchlight function on block data in parallel.
`extra_params` contains:
- Searchlight function.
- `Shape` mask.
- Minimum active voxels proportion required to run the searchlight
function. | 2.25598 | 2.018317 | 1.117753 |
rank = self.comm.rank
B = [(rank, idx) for (idx, c) in enumerate(data) if c is not None]
C = self.comm.allreduce(B)
ownership = [None] * len(data)
for c in C:
ownership[c[1]] = c[0]
return ownership | def _get_ownership(self, data) | Determine on which rank each subject currently resides
Parameters
----------
data: list of 4D arrays with subject data
Returns
-------
list of ranks indicating the owner of each subject | 4.349696 | 4.652554 | 0.934905 |
blocks = []
outerblk = self.max_blk_edge + 2*self.sl_rad
for i in range(0, mask.shape[0], self.max_blk_edge):
for j in range(0, mask.shape[1], self.max_blk_edge):
for k in range(0, mask.shape[2], self.max_blk_edge):
block_shape = mask[i:i+... | def _get_blocks(self, mask) | Divide the volume into a set of blocks
Ignore blocks that have no active voxels in the mask
Parameters
----------
mask: a boolean 3D array which is true at every active voxel
Returns
-------
list of tuples containing block information:
- a triple c... | 2.197445 | 2.131971 | 1.030711 |
(pt, sz) = block
if len(mat.shape) == 3:
return mat[pt[0]:pt[0]+sz[0],
pt[1]:pt[1]+sz[1],
pt[2]:pt[2]+sz[2]].copy()
elif len(mat.shape) == 4:
return mat[pt[0]:pt[0]+sz[0],
pt[1]:pt[1]+sz[1],
... | def _get_block_data(self, mat, block) | Retrieve a block from a 3D or 4D volume
Parameters
----------
mat: a 3D or 4D volume
block: a tuple containing block information:
- a triple containing the lowest-coordinate voxel in the block
- a triple containing the size in voxels of the block
Returns
... | 1.804486 | 1.788728 | 1.00881 |
return [self._get_block_data(mat, block) for block in blocks] | def _split_volume(self, mat, blocks) | Convert a volume into a list of block data
Parameters
----------
mat: A 3D or 4D array to be split
blocks: a list of tuples containing block information:
- a triple containing the top left point of the block and
- a triple containing the size in voxels of the block... | 5.389194 | 6.491529 | 0.830189 |
rank = self.comm.rank
size = self.comm.size
subject_submatrices = []
nblocks = self.comm.bcast(len(data)
if rank == owner else None, root=owner)
# For each submatrix
for idx in range(0, nblocks, size):
padded = None... | def _scatter_list(self, data, owner) | Distribute a list from one rank to other ranks in a cyclic manner
Parameters
----------
data: list of pickle-able data
owner: rank that owns the data
Returns
-------
A list containing the data in a cyclic layout across ranks | 4.662355 | 4.686542 | 0.994839 |
if mask.ndim != 3:
raise ValueError('mask should be a 3D array')
for (idx, subj) in enumerate(subjects):
if subj is not None:
if subj.ndim != 4:
raise ValueError('subjects[{}] must be 4D'.format(idx))
self.mask = mask
... | def distribute(self, subjects, mask) | Distribute data to MPI ranks
Parameters
----------
subjects : list of 4D arrays containing data for one or more subjects.
Each entry of the list must be present on at most one rank,
and the other ranks contain a "None" at this list location.
For examp... | 3.846568 | 3.718835 | 1.034348 |
rank = self.comm.rank
results = []
usable_cpus = usable_cpu_count()
if pool_size is None:
processes = usable_cpus
else:
processes = min(pool_size, usable_cpus)
if processes > 1:
with Pool(processes) as pool:
f... | def run_block_function(self, block_fn, extra_block_fn_params=None,
pool_size=None) | Perform a function for each block in a volume.
Parameters
----------
block_fn: function to apply to each block:
Parameters
data: list of 4D arrays containing subset of subject data,
which is padded with sl_rad voxels.
mas... | 3.302493 | 3.07704 | 1.07327 |
extra_block_fn_params = (voxel_fn, self.shape,
self.min_active_voxels_proportion)
block_fn_result = self.run_block_function(_singlenode_searchlight,
extra_block_fn_params,
... | def run_searchlight(self, voxel_fn, pool_size=None) | Perform a function at each voxel which is set to True in the
user-provided mask. The mask passed to the searchlight function will be
further masked by the user-provided searchlight shape.
Parameters
----------
voxel_fn: function to apply at each voxel
Must be `seri... | 6.31097 | 7.915668 | 0.797276 |
shape = data.shape
data = zscore(data, axis=axis, ddof=0)
# if zscore fails (standard deviation is zero),
# optionally set all values to be zero
if not return_nans:
data = np.nan_to_num(data)
data = data / math.sqrt(shape[axis])
return data | def _normalize_for_correlation(data, axis, return_nans=False) | normalize the data before computing correlation
The data will be z-scored and divided by sqrt(n)
along the assigned axis
Parameters
----------
data: 2D array
axis: int
specify which dimension of the data should be normalized
return_nans: bool, default:False
If False, retu... | 4.524957 | 4.498696 | 1.005837 |
matrix1 = matrix1.astype(np.float32)
matrix2 = matrix2.astype(np.float32)
[r1, d1] = matrix1.shape
[r2, d2] = matrix2.shape
if d1 != d2:
raise ValueError('Dimension discrepancy')
# preprocess two components
matrix1 = _normalize_for_correlation(matrix1, 1,
... | def compute_correlation(matrix1, matrix2, return_nans=False) | compute correlation between two sets of variables
Correlate the rows of matrix1 with the rows of matrix2.
If matrix1 == matrix2, it is auto-correlation computation
resulting in a symmetric correlation matrix.
The number of columns MUST agree between set1 and set2.
The correlation being computed her... | 2.933596 | 2.955496 | 0.99259 |
alpha = 2
tau2 = (y_invK_y + 2 * tau_range**2) / (alpha * 2 + 2 + n_y)
log_ptau = scipy.stats.invgamma.logpdf(
tau2, scale=tau_range**2, a=2)
return tau2, log_ptau | def prior_GP_var_inv_gamma(y_invK_y, n_y, tau_range) | Imposing an inverse-Gamma prior onto the variance (tau^2)
parameter of a Gaussian Process, which is in turn a prior
imposed over an unknown function y = f(x).
The inverse-Gamma prior of tau^2, tau^2 ~ invgamma(shape, scale)
is described by a shape parameter alpha=2 and a scale parameter
... | 4.289187 | 3.707706 | 1.15683 |
tau2 = (y_invK_y - n_y * tau_range**2
+ np.sqrt(n_y**2 * tau_range**4 + (2 * n_y + 8)
* tau_range**2 * y_invK_y + y_invK_y**2))\
/ 2 / (n_y + 2)
log_ptau = scipy.stats.halfcauchy.logpdf(
tau2**0.5, scale=tau_range)
return tau2, log_ptau | def prior_GP_var_half_cauchy(y_invK_y, n_y, tau_range) | Imposing a half-Cauchy prior onto the standard deviation (tau)
of the Gaussian Process which is in turn a prior imposed over
a function y = f(x).
The scale parameter of the half-Cauchy prior is tau_range.
The function returns the MAP estimate of tau^2 and
log(p(tau|tau_range)) fo... | 3.434268 | 3.430038 | 1.001233 |
beta = X.shape[0] / X.shape[1]
if beta > 1:
beta = 1 / beta
omega = 0.56 * beta ** 3 - 0.95 * beta ** 2 + 1.82 * beta + 1.43
if zscore:
sing = np.linalg.svd(_zscore(X), False, False)
else:
sing = np.linalg.svd(X, False, False)
thresh = omega * np.median(sing)
nco... | def Ncomp_SVHT_MG_DLD_approx(X, zscore=True) | This function implements the approximate calculation of the
optimal hard threshold for singular values, by Matan Gavish
and David L. Donoho:
"The optimal hard threshold for singular values is 4 / sqrt(3)"
http://ieeexplore.ieee.org/stamp/stamp.jsp?arnumber=6846297
Parameters
---... | 5.37253 | 5.586894 | 0.961631 |
assert a.ndim > 1, 'a must have more than one dimensions'
zscore = scipy.stats.zscore(a, axis=0)
zscore[:, np.logical_not(np.all(np.isfinite(zscore), axis=0))] = 0
return zscore | def _zscore(a) | Calculating z-score of data on the first axis.
If the numbers in any column are all equal, scipy.stats.zscore
will return NaN for this column. We shall correct them all to
be zeros.
Parameters
----------
a: numpy array
Returns
-------
zscore: numpy array
The z-s... | 2.968623 | 2.956703 | 1.004031 |
assert X.ndim == 2 and X.shape[1] == self.beta_.shape[1], \
'The shape of X is not consistent with the shape of data '\
'used in the fitting step. They should have the same number '\
'of voxels'
assert scan_onsets is None or (scan_onsets.ndim == 1 and
... | def transform(self, X, y=None, scan_onsets=None) | Use the model to estimate the time course of response to
each condition (ts), and the time course unrelated to task
(ts0) which is spread across the brain.
This is equivalent to "decoding" the design matrix and
nuisance regressors from a new dataset different from the
... | 3.472832 | 3.171684 | 1.094949 |
assert X.ndim == 2 and X.shape[1] == self.beta_.shape[1], \
'The shape of X is not consistent with the shape of data '\
'used in the fitting step. They should have the same number '\
'of voxels'
assert scan_onsets is None or (scan_onsets.ndim == 1 and
... | def score(self, X, design, scan_onsets=None) | Use the model and parameters estimated by fit function
from some data of a participant to evaluate the log
likelihood of some new data of the same participant.
Design matrix of the same set of experimental
conditions in the testing data should be provided, with each
... | 2.685309 | 2.454894 | 1.093859 |
run_TRs, n_run = self._run_TR_from_scan_onsets(n_T, scan_onsets)
D_ele = map(self._D_gen, run_TRs)
F_ele = map(self._F_gen, run_TRs)
D = scipy.linalg.block_diag(*D_ele)
F = scipy.linalg.block_diag(*F_ele)
# D and F above are templates for constructing
# t... | def _prepare_DF(self, n_T, scan_onsets=None) | Prepare the essential template matrices D and F for
pre-calculating some terms to be re-used.
The inverse covariance matrix of AR(1) noise is
sigma^-2 * (I - rho1*D + rho1**2 * F).
And we denote A = I - rho1*D + rho1**2 * F | 4.413514 | 3.966551 | 1.112683 |
XTY, XTDY, XTFY = self._make_templates(D, F, X, Y)
YTY_diag = np.sum(Y * Y, axis=0)
YTDY_diag = np.sum(Y * np.dot(D, Y), axis=0)
YTFY_diag = np.sum(Y * np.dot(F, Y), axis=0)
XTX, XTDX, XTFX = self._make_templates(D, F, X, X)
return XTY, XTDY, XTFY, YTY_diag, Y... | def _prepare_data_XY(self, X, Y, D, F) | Prepares different forms of products of design matrix X
and data Y, or between themselves.
These products are re-used a lot during fitting.
So we pre-calculate them. Because these are reused,
it is in principle possible to update the fitting
as new data come i... | 2.080883 | 2.126164 | 0.978703 |
X_DC = self._gen_X_DC(run_TRs)
reg_sol = np.linalg.lstsq(X_DC, X)
if np.any(np.isclose(reg_sol[1], 0)):
raise ValueError('Your design matrix appears to have '
'included baseline time series.'
'Either remove them, or m... | def _prepare_data_XYX0(self, X, Y, X_base, X_res, D, F, run_TRs,
no_DC=False) | Prepares different forms of products between design matrix X or
data Y or nuisance regressors X0.
These products are re-used a lot during fitting.
So we pre-calculate them.
no_DC means not inserting regressors for DC components
into nuisance regressor.
... | 2.880663 | 2.741368 | 1.050812 |
if X_base is not None:
reg_sol = np.linalg.lstsq(X_DC, X_base)
if not no_DC:
if not np.any(np.isclose(reg_sol[1], 0)):
# No columns in X_base can be explained by the
# baseline regressors. So we insert them.
... | def _merge_DC_to_base(self, X_DC, X_base, no_DC) | Merge DC components X_DC to the baseline time series
X_base (By baseline, this means any fixed nuisance
regressors not updated during fitting, including DC
components and any nuisance regressors provided by
the user.
X_DC is always in the first few columns of ... | 4.236484 | 4.05469 | 1.044835 |
idx_param_sing = {'Cholesky': np.arange(n_l), 'a1': n_l}
# for simplified fitting
idx_param_fitU = {'Cholesky': np.arange(n_l),
'a1': np.arange(n_l, n_l + n_V)}
# for the likelihood function when we fit U (the shared covariance).
idx_param_fitV ... | def _build_index_param(self, n_l, n_V, n_smooth) | Build dictionaries to retrieve each parameter
from the combined parameters. | 5.054386 | 4.927182 | 1.025817 |
chol = np.linalg.cholesky(M)
if M.ndim == 2:
return np.sum(np.log(np.abs(np.diag(chol))))
else:
return np.sum(np.log(np.abs(np.diagonal(
chol, axis1=-2, axis2=-1))), axis=-1) | def _half_log_det(self, M) | Return log(|M|)*0.5. For positive definite matrix M
of more than 2 dimensions, calculate this for the
last two dimension and return a value corresponding
to each element in the first few dimensions. | 2.244925 | 2.114244 | 1.06181 |
logger.info('Transforming new data.')
# Constructing the transition matrix and the variance of
# innovation noise as prior for the latent variable X and X0
# in new data.
n_C = beta.shape[0]
n_T = Y.shape[0]
weight = np.concatenate((beta, beta0), axis=0)... | def _transform(self, Y, scan_onsets, beta, beta0,
rho_e, sigma_e, rho_X, sigma2_X, rho_X0, sigma2_X0) | Given the data Y and the response amplitudes beta and beta0
estimated in the fit step, estimate the corresponding X and X0.
It is done by a forward-backward algorithm.
We assume X and X0 both are vector autoregressive (VAR)
processes, to capture temporal smoothness. Their... | 2.88857 | 2.851804 | 1.012892 |
logger.info('Estimating cross-validated score for new data.')
n_T = Y.shape[0]
if design is not None:
Y = Y - np.dot(design, beta)
# The function works for both full model and null model.
# If design matrix is not provided, the whole data is
# used as... | def _score(self, Y, design, beta, scan_onsets, beta0, rho_e, sigma_e,
rho_X0, sigma2_X0) | Given the data Y, and the spatial pattern beta0
of nuisance time series, return the cross-validated score
of the data Y given all parameters of the subject estimated
during the first step.
It is assumed that the user has design matrix built for the
data Y. Bot... | 4.577852 | 4.407941 | 1.038547 |
if same_para:
n_c = x.shape[1]
x = np.reshape(x, x.size, order='F')
rho, sigma2 = alg.AR_est_YW(x, 1)
# We concatenate all the design matrix to estimate common AR(1)
# parameters. This creates some bias because the end of one column
... | def _est_AR1(self, x, same_para=False) | Estimate the AR(1) parameters of input x.
Each column of x is assumed as independent from other columns,
and each column is treated as an AR(1) process.
If same_para is set as True, then all columns of x
are concatenated and a single set of AR(1) parameters
is... | 3.814788 | 3.441514 | 1.108462 |
n_T = len(Gamma_inv)
# All the terms with hat before are parameters of posterior
# distributions of X conditioned on data from all time points,
# whereas the ones without hat calculated by _forward_step
# are mean and covariance of posterior of X conditioned on
#... | def _backward_step(self, deltaY, deltaY_sigma2inv_rho_weightT,
sigma2_e, weight, mu, mu_Gamma_inv, Gamma_inv,
Lambda_0, Lambda_1, H) | backward step for HMM, assuming both the hidden state and noise
have 1-step dependence on the previous value. | 2.754465 | 2.780325 | 0.990699 |
X = self._check_data_GBRSA(X, for_fit=False)
scan_onsets = self._check_scan_onsets_GBRSA(scan_onsets, X)
assert len(X) == self.n_subj_
ts = [None] * self.n_subj_
ts0 = [None] * self.n_subj_
log_p = [None] * self.n_subj_
for i, x in enumerate(X):
... | def transform(self, X, y=None, scan_onsets=None) | Use the model to estimate the time course of response to
each condition (ts), and the time course unrelated to task
(ts0) which is spread across the brain.
This is equivalent to "decoding" the design matrix and
nuisance regressors from a new dataset different from the
... | 2.993141 | 2.753137 | 1.087175 |
boundaries = np.flip(scipy.stats.expon.isf(
np.linspace(0, 1, n_bin + 1),
scale=scale), axis=0)
bins = np.empty(n_bin)
for i in np.arange(n_bin):
bins[i] = utils.center_mass_exp(
(boundaries[i], boundaries[i + 1]), scale=scale)
... | def _bin_exp(self, n_bin, scale=1.0) | Calculate the bin locations to approximate exponential distribution.
It breaks the cumulative probability of exponential distribution
into n_bin equal bins, each covering 1 / n_bin probability. Then it
calculates the center of mass in each bins and returns the
centers of ... | 3.181073 | 3.119428 | 1.019762 |
if self.SNR_prior == 'unif':
SNR_grids = np.linspace(0, 1, self.SNR_bins)
SNR_weights = np.ones(self.SNR_bins) / (self.SNR_bins - 1)
SNR_weights[0] = SNR_weights[0] / 2.0
SNR_weights[-1] = SNR_weights[-1] / 2.0
elif self.SNR_prior == 'lognorm':
... | def _set_SNR_grids(self) | Set the grids and weights for SNR used in numerical integration
of SNR parameters. | 2.982758 | 2.924313 | 1.019986 |
rho_grids = np.arange(self.rho_bins) * 2 / self.rho_bins - 1 \
+ 1 / self.rho_bins
rho_weights = np.ones(self.rho_bins) / self.rho_bins
return rho_grids, rho_weights | def _set_rho_grids(self) | Set the grids and weights for rho used in numerical integration
of AR(1) parameters. | 3.101884 | 2.79876 | 1.108306 |
half_log_det_X0TAX0 = np.reshape(
np.repeat(self._half_log_det(X0TAX0)[None, :],
self.SNR_bins, axis=0), n_grid)
X0TAX0 = np.reshape(
np.repeat(X0TAX0[None, :, :, :],
self.SNR_bins, axis=0),
(n_grid, n_X0, n_X0))
... | def _matrix_flattened_grid(self, X0TAX0, X0TAX0_i, SNR_grids, XTAcorrX,
YTAcorrY_diag, XTAcorrY, X0TAY, XTAX0,
n_C, n_V, n_X0, n_grid) | We need to integrate parameters SNR and rho on 2-d discrete grids.
This function generates matrices which have only one dimension for
these two parameters, with each slice in that dimension
corresponding to each combination of the discrete grids of SNR
and discrete grids ... | 1.601341 | 1.634348 | 0.979804 |
logger.info('Starting RSRM')
# Check that the regularizer value is positive
if 0.0 >= self.lam:
raise ValueError("Gamma parameter should be positive.")
# Check the number of subjects
if len(X) <= 1:
raise ValueError("There are not enough subject... | def fit(self, X) | Compute the Robust Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data of one subject. | 4.041771 | 3.812639 | 1.060098 |
# Check if the model exist
if hasattr(self, 'w_') is False:
raise NotFittedError("The model fit has not been run yet.")
# Check the number of subjects
if len(X) != len(self.w_):
raise ValueError("The number of subjects does not match the one"
... | def transform(self, X) | Use the model to transform new data to Shared Response space
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints_i]
Each element in the list contains the fMRI data of one subject.
Returns
-------
r : list of 2D arrays, el... | 3.250835 | 2.840767 | 1.144351 |
S = np.zeros_like(X)
R = None
for i in range(self.n_iter):
R = self.w_[subject].T.dot(X - S)
S = self._shrink(X - self.w_[subject].dot(R), self.lam)
return R, S | def _transform_new_data(self, X, subject) | Transform new data for a subjects by projecting to the shared subspace and
computing the individual information.
Parameters
----------
X : array, shape=[voxels, timepoints]
The fMRI data of the subject.
subject : int
The subject id.
Returns
... | 4.374014 | 4.463033 | 0.980054 |
# Check if the model exist
if hasattr(self, 'w_') is False:
raise NotFittedError("The model fit has not been run yet.")
# Check the number of TRs in the subject
if X.shape[1] != self.r_.shape[1]:
raise ValueError("The number of timepoints(TRs) does not m... | def transform_subject(self, X) | Transform a new subject using the existing model
Parameters
----------
X : 2D array, shape=[voxels, timepoints]
The fMRI data of the new subject.
Returns
-------
w : 2D array, shape=[voxels, features]
Orthogonal mapping `W_{new}` for new subjec... | 4.722648 | 4.079994 | 1.157513 |
subjs = len(X)
voxels = [X[i].shape[0] for i in range(subjs)]
TRs = X[0].shape[1]
features = self.features
# Initialization
W = self._init_transforms(subjs, voxels, features, self.random_state_)
S = self._init_individual(subjs, voxels, TRs)
R = s... | def _rsrm(self, X) | Block-Coordinate Descent algorithm for fitting RSRM.
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data for alignment of
one subject.
Returns
-------
W : list ... | 2.891613 | 2.388194 | 1.210795 |
# Init the Random seed generator
np.random.seed(self.rand_seed)
# Draw a random W for each subject
W = [random_state.random_sample((voxels[i], features))
for i in range(subjs)]
# Make it orthogonal it with QR decomposition
for i in range(subjs):
... | def _init_transforms(self, subjs, voxels, features, random_state) | Initialize the mappings (Wi) with random orthogonal matrices.
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
features : int
The number of features in the model.
... | 5.602273 | 4.219152 | 1.32782 |
subjs = len(X)
func = .0
for i in range(subjs):
func += 0.5 * np.sum((X[i] - W[i].dot(R) - S[i])**2) \
+ gamma * np.sum(np.abs(S[i]))
return func | def _objective_function(X, W, R, S, gamma) | Evaluate the objective function.
.. math:: \\sum_{i=1}^{N} 1/2 \\| X_i - W_i R - S_i \\|_F^2
.. math:: + /\\gamma * \\|S_i\\|_1
Parameters
----------
X : list of array, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data for a... | 3.461295 | 3.17733 | 1.089372 |
subjs = len(X)
S = []
for i in range(subjs):
S.append(RSRM._shrink(X[i] - W[i].dot(R), gamma))
return S | def _update_individual(X, W, R, gamma) | Update the individual components `S_i`.
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data for alignment of
one subject.
W : list of array, element i has shape=[voxels_i, featu... | 6.909562 | 6.814937 | 1.013885 |
return [np.zeros((voxels[i], TRs)) for i in range(subjs)] | def _init_individual(subjs, voxels, TRs) | Initializes the individual components `S_i` to empty (all zeros).
Parameters
----------
subjs : int
The number of subjects.
voxels : list of int
A list with the number of voxels per subject.
TRs : int
The number of timepoints in the data.
... | 5.644478 | 4.345129 | 1.299036 |
subjs = len(X)
TRs = X[0].shape[1]
R = np.zeros((features, TRs))
# Project the subject data with the individual component removed into
# the shared subspace and average over all subjects.
for i in range(subjs):
R += W[i].T.dot(X[i]-S[i])
R /= ... | def _update_shared_response(X, S, W, features) | Update the shared response `R`.
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data for alignment of
one subject.
S : list of array, element i has shape=[voxels_i, timepoints]
... | 6.525561 | 5.181515 | 1.259392 |
A = Xi.dot(R.T)
A -= Si.dot(R.T)
# Solve the Procrustes problem
U, _, V = np.linalg.svd(A, full_matrices=False)
return U.dot(V) | def _update_transform_subject(Xi, Si, R) | Updates the mappings `W_i` for one subject.
Parameters
----------
Xi : array, shape=[voxels, timepoints]
The fMRI data :math:`X_i` for aligning the subject.
Si : array, shape=[voxels, timepoints]
The individual component :math:`S_i` for the subject.
R ... | 3.485839 | 4.19272 | 0.831403 |
subjs = len(X)
W = []
for i in range(subjs):
W.append(RSRM._update_transform_subject(X[i], S[i], R))
return W | def _update_transforms(X, S, R) | Updates the mappings `W_i` for each subject.
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, timepoints]
Each element in the list contains the fMRI data for alignment of
one subject.ß
S : list of array, element i has shape=[voxels_i,... | 5.833858 | 5.593774 | 1.04292 |
pos = v > gamma
neg = v < -gamma
v[pos] -= gamma
v[neg] += gamma
v[np.logical_and(~pos, ~neg)] = .0
return v | def _shrink(v, gamma) | Soft-shrinkage of an array with parameter gamma.
Parameters
----------
v : array
Array containing the values to be applied to the shrinkage operator
gamma : float
Shrinkage parameter.
Returns
-------
v : array
The same inpu... | 3.573369 | 4.209385 | 0.848905 |
import matplotlib.pyplot as plt
import math
plt.figure()
subjects = len(cm)
root_subjects = math.sqrt(subjects)
cols = math.ceil(root_subjects)
rows = math.ceil(subjects/cols)
classes = cm[0].shape[0]
for subject in range(subjects):
plt.subplot(rows, cols, subject+1)
... | def plot_confusion_matrix(cm, title="Confusion Matrix") | Plots a confusion matrix for each subject | 2.122406 | 2.025687 | 1.047746 |
image_data = image.get_data()
if image_data.shape[:3] != mask.shape:
raise ValueError("Image data and mask have different shapes.")
if data_type is not None:
cast_data = image_data.astype(data_type)
else:
cast_data = image_data
return cast_data[mask] | def mask_image(image: SpatialImage, mask: np.ndarray, data_type: type = None
) -> np.ndarray | Mask image after optionally casting its type.
Parameters
----------
image
Image to mask. Can include time as the last dimension.
mask
Mask to apply. Must have the same shape as the image data.
data_type
Type to cast image to.
Returns
-------
np.ndarray
M... | 2.580355 | 2.721519 | 0.94813 |
for image in images:
yield [mask_image(image, mask, image_type) for mask in masks] | def multimask_images(images: Iterable[SpatialImage],
masks: Sequence[np.ndarray], image_type: type = None
) -> Iterable[Sequence[np.ndarray]] | Mask images with multiple masks.
Parameters
----------
images:
Images to mask.
masks:
Masks to apply.
image_type:
Type to cast images to.
Yields
------
Sequence[np.ndarray]
For each mask, a masked image. | 3.522394 | 4.730463 | 0.744619 |
for images in multimask_images(images, (mask,), image_type):
yield images[0] | def mask_images(images: Iterable[SpatialImage], mask: np.ndarray,
image_type: type = None) -> Iterable[np.ndarray] | Mask images.
Parameters
----------
images:
Images to mask.
mask:
Mask to apply.
image_type:
Type to cast images to.
Yields
------
np.ndarray
Masked image. | 10.208649 | 13.025961 | 0.783716 |
images_iterator = iter(masked_images)
first_image = next(images_iterator)
first_image_shape = first_image.T.shape
result = np.empty((first_image_shape[0], first_image_shape[1],
n_subjects))
for n_images, image in enumerate(itertools.chain([firs... | def from_masked_images(cls: Type[T], masked_images: Iterable[np.ndarray],
n_subjects: int) -> T | Create a new instance of MaskedMultiSubjecData from masked images.
Parameters
----------
masked_images : iterator
Images from multiple subjects to stack along 3rd dimension
n_subjects : int
Number of subjects; must match the number of images
Returns
... | 2.237546 | 2.440391 | 0.91688 |
condition_idxs, epoch_idxs, _ = np.where(self)
_, unique_epoch_idxs = np.unique(epoch_idxs, return_index=True)
return condition_idxs[unique_epoch_idxs] | def extract_labels(self) -> np.ndarray | Extract condition labels.
Returns
-------
np.ndarray
The condition label of each epoch. | 5.093973 | 4.101325 | 1.242031 |
w = []
subjects = len(data)
voxels = np.empty(subjects, dtype=int)
# Set Wi to a random orthogonal voxels by features matrix
for subject in range(subjects):
if data[subject] is not None:
voxels[subject] = data[subject].shape[0]
rnd_matrix = random_states[subject... | def _init_w_transforms(data, features, random_states, comm=MPI.COMM_SELF) | Initialize the mappings (Wi) for the SRM with random orthogonal matrices.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
features : int
The number of features in the model.
ra... | 3.641288 | 2.986872 | 1.219097 |
logger.info('Starting Probabilistic SRM')
# Check the number of subjects
if len(X) <= 1:
raise ValueError("There are not enough subjects "
"({0:d}) to train the model.".format(len(X)))
# Check for input data sizes
number_subject... | def fit(self, X, y=None) | Compute the probabilistic Shared Response Model
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
y : not used | 3.114107 | 2.987892 | 1.042242 |
# Check if the model exist
if hasattr(self, 'w_') is False:
raise NotFittedError("The model fit has not been run yet.")
# Check the number of subjects
if len(X) != len(self.w_):
raise ValueError("The number of subjects does not match the one"
... | def transform(self, X, y=None) | Use the model to transform matrix to Shared Response space
Parameters
----------
X : list of 2D arrays, element i has shape=[voxels_i, samples_i]
Each element in the list contains the fMRI data of one subject
note that number of voxels and samples can vary across subject... | 3.186861 | 2.809292 | 1.1344 |
A = Xi.dot(S.T)
# Solve the Procrustes problem
U, _, V = np.linalg.svd(A, full_matrices=False)
return U.dot(V) | def _update_transform_subject(Xi, S) | Updates the mappings `W_i` for one subject.
Parameters
----------
Xi : array, shape=[voxels, timepoints]
The fMRI data :math:`X_i` for aligning the subject.
S : array, shape=[features, timepoints]
The shared response.
Returns
-------
W... | 3.751317 | 4.576279 | 0.819731 |
# Check if the model exist
if hasattr(self, 'w_') is False:
raise NotFittedError("The model fit has not been run yet.")
# Check the number of TRs in the subject
if X.shape[1] != self.s_.shape[1]:
raise ValueError("The number of timepoints(TRs) does not m... | def transform_subject(self, X) | Transform a new subject using the existing model.
The subject is assumed to have recieved equivalent stimulation
Parameters
----------
X : 2D array, shape=[voxels, timepoints]
The fMRI data of the new subject.
Returns
-------
w : 2D array, shape=[v... | 5.400873 | 4.850527 | 1.113461 |
subjects = len(data)
self.random_state_ = np.random.RandomState(self.rand_seed)
random_states = [
np.random.RandomState(self.random_state_.randint(2 ** 32))
for i in range(len(data))]
# Initialization step: initialize the outputs with initial values,
... | def _srm(self, data) | Expectation-Maximization algorithm for fitting the probabilistic SRM.
Parameters
----------
data : list of 2D arrays, element i has shape=[voxels_i, samples]
Each element in the list contains the fMRI data of one subject.
Returns
-------
w : list of array... | 3.125122 | 2.763078 | 1.131029 |
X = copy.deepcopy(X)
if type(X) is not list:
X = check_array(X)
X = [X]
n_train = len(X)
for i in range(n_train):
X[i] = X[i].T
self.classes_ = np.arange(self.n_events)
n_dim = X[0].shape[0]
for i in range(n_train):
... | def fit(self, X, y=None) | Learn a segmentation on training data
Fits event patterns and a segmentation to training data. After
running this function, the learned event patterns can be used to
segment other datasets using find_events
Parameters
----------
X: time by voxel ndarray, or a list of su... | 2.871782 | 2.816127 | 1.019763 |
n_vox = data.shape[0]
t = data.shape[1]
# z-score both data and mean patterns in space, so that Gaussians
# are measuring Pearson correlations and are insensitive to overall
# activity changes
data_z = stats.zscore(data, axis=0, ddof=1)
mean_pat_z = sta... | def _logprob_obs(self, data, mean_pat, var) | Log probability of observing each timepoint under each event model
Computes the log probability of each observed timepoint being
generated by the Gaussian distribution for each event pattern
Parameters
----------
data: voxel by time ndarray
fMRI data on which to com... | 3.178005 | 2.800354 | 1.134858 |
logprob = copy.copy(logprob)
t = logprob.shape[0]
logprob = np.hstack((logprob, float("-inf") * np.ones((t, 1))))
# Initialize variables
log_scale = np.zeros(t)
log_alpha = np.zeros((t, self.n_events + 1))
log_beta = np.zeros((t, self.n_events + 1))
... | def _forward_backward(self, logprob) | Runs forward-backward algorithm on observation log probs
Given the log probability of each timepoint being generated by
each event, run the HMM forward-backward algorithm to find the
probability that each timepoint belongs to each event (based on the
transition priors in p_start, p_end,... | 2.225715 | 2.12108 | 1.049331 |
xshape = x.shape
_x = x.flatten()
y = utils.masked_log(_x)
return y.reshape(xshape) | def _log(self, x) | Modified version of np.log that manually sets values <=0 to -inf
Parameters
----------
x: ndarray of floats
Input to the log function
Returns
-------
log_ma: ndarray of floats
log of x, with x<=0 values replaced with -inf | 7.410101 | 7.695527 | 0.96291 |
if event_pat.shape[1] != self.n_events:
raise ValueError(("Number of columns of event_pat must match "
"number of events"))
self.event_pat_ = event_pat.copy() | def set_event_patterns(self, event_pat) | Set HMM event patterns manually
Rather than fitting the event patterns automatically using fit(), this
function allows them to be set explicitly. They can then be used to
find corresponding events in a new dataset, using find_events().
Parameters
----------
event_pat: v... | 3.741298 | 4.02105 | 0.930428 |
if var is None:
if not hasattr(self, 'event_var_'):
raise NotFittedError(("Event variance must be provided, if "
"not previously set by fit()"))
else:
var = self.event_var_
if not hasattr(self, 'even... | def find_events(self, testing_data, var=None, scramble=False) | Applies learned event segmentation to new testing dataset
After fitting an event segmentation using fit() or setting event
patterns directly using set_event_patterns(), this function finds the
same sequence of event patterns in a new testing dataset.
Parameters
----------
... | 3.954244 | 3.125794 | 1.265037 |
check_is_fitted(self, ["event_pat_", "event_var_"])
X = check_array(X)
segments, test_ll = self.find_events(X)
return np.argmax(segments, axis=1) | def predict(self, X) | Applies learned event segmentation to new testing dataset
Alternative function for segmenting a new dataset after using
fit() to learn a sequence of events, to comply with the sklearn
Classifier interface
Parameters
----------
X: timepoint by voxel ndarray
f... | 6.450968 | 8.547134 | 0.754752 |
Dz = stats.zscore(D, axis=1, ddof=1)
ev_var = np.empty(event_pat.shape[1])
for e in range(event_pat.shape[1]):
# Only compute variances for weights > 0.1% of max weight
nz = weights[:, e] > np.max(weights[:, e])/1000
sumsq = np.dot(weights[nz, e],
... | def calc_weighted_event_var(self, D, weights, event_pat) | Computes normalized weighted variance around event pattern
Utility function for computing variance in a training set of weighted
event examples. For each event, the sum of squared differences for all
timepoints from the event pattern is computed, and then the weights
specify how much ea... | 3.085838 | 2.874753 | 1.073427 |
lg, test_ll = self._forward_backward(np.zeros((t, self.n_events)))
segments = np.exp(lg)
return segments, test_ll | def model_prior(self, t) | Returns the prior probability of the HMM
Runs forward-backward without any data, showing the prior distribution
of the model (for comparison with a posterior).
Parameters
----------
t: int
Number of timepoints
Returns
-------
segments : time... | 13.940866 | 6.086598 | 2.29042 |
try:
return _resolve_value(safe_chain_getattr(obj, attr))
except AttributeError:
return value | def chain_getattr(obj, attr, value=None) | Get chain attribute for an object. | 6.212589 | 6.629694 | 0.937085 |
if split is None:
sl = 0
join = False
else:
sl = len(split)
join = True
result = []
rl = 0
for element in iterable:
element = prefix + element + postfix
el = len(element)
if len(result) > 0:
el += sl
rl += el
if... | def trim_iterable(iterable, limit, *, split=None, prefix='', postfix='') | trim the list to make total length no more than limit.If split specified,a string is return.
:return: | 2.907312 | 2.990264 | 0.972259 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.