Analyze¶
Setup: install HyperTools (run this cell first on Colab)
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
_hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
_hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
_spec = importlib.util.find_spec('hypertools')
if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
%pip install -q "hypertools[interactive]>=1.1.0"
else:
print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')
The hypertools analyze function allows you to perform complex analyses (manipulation, normalization, dimensionality reduction, alignment and clustering) in a single line of code, and returns the transformed data rather than a figure. It is the same pipeline hyp.plot runs before drawing, so anything you can pass to plot as manip=, normalize=, reduce=, align= or cluster= works here too.
The order of operations is always: manip -> normalize -> reduce -> align -> cluster. This tutorial exercises every stage, visualizing each result with hyp.plot(..., reduce=None) (the data are already low-dimensional after the pipeline, so nothing more needs to be reduced), and ends with return_model=True, which hands back a fitted Pipeline you can replay on new data.
Import packages¶
[1]:
import hypertools as hyp
import numpy as np
%matplotlib inline
Load your data¶
First, we’ll load one of the sample datasets. This dataset is a list of 2 numpy arrays, each containing average brain activity (fMRI) from 18 subjects listening to the same story, fit using Hierarchical Topographic Factor Analysis (HTFA) with 100 nodes. The rows are timepoints and the columns are fMRI components.
See the full dataset or the HTFA article for more info on the data and HTFA, respectively.
[2]:
weights = hyp.load('weights_avg')
print(weights[0].shape) # 100 timepoints and 100 components
print(weights[1].shape)
(100, 100)
(100, 100)
Each element of weights is a 100 x 100 array. Before running anything through analyze, here is what the two raw datasets look like: hyp.plot reduces the 100 components to 3 principal components and draws each dataset as a trajectory through time.
[3]:
fig = hyp.plot(weights, names=['group 1', 'group 2'], title='raw data (PCA to 3-D inside plot)')
Manipulation¶
manip is the first stage: a per-dataset transformation applied in the data’s native space, before anything is pooled. The manipulators are Smooth (kernel smoothing over time), Resample (interpolate to a new number of rows), ZScore and Normalize (per-column rescaling), and Delay (a time-delay embedding, tau=/dims=); a list of specs chains them. Below we smooth each timeseries with an 11-timepoint boxcar and resample it from 100 to 300 rows. analyze with only
manip= returns the manipulated data unchanged in dimensionality (still 100 columns, now 300 rows), so we pass it on to hyp.plot to reduce and draw.
[4]:
smoothed = hyp.analyze(weights, manip=[{'model': 'Smooth', 'kwargs': {'kernel': 'boxcar', 'kernel_width': 11}},
{'model': 'Resample', 'kwargs': {'n_samples': 300}}])
print('after manip:', [np.asarray(x).shape for x in smoothed])
fig = hyp.plot(smoothed, names=['group 1', 'group 2'], title='Smooth (boxcar, 11) -> Resample (300 rows)')
after manip: [(300, 100), (300, 100)]
Normalization¶
normalize z-scores the data. It accepts the following strings:
'across'- z-scores columns across all lists (default)'within'- z-scores columns within each list'row'- z-scores each row of data
normalize='within' z-scores each column within each array separately, so every dataset is standardized on its own (using its own column means and standard deviations) before the datasets are compared. The result is still 100-dimensional, so again hyp.plot reduces it for display.
[5]:
norm_within = hyp.analyze(weights, normalize='within')
print('column means after normalize (first 3 columns):', norm_within[0].mean(axis=0)[:3].round(6))
fig = hyp.plot(norm_within, names=['group 1', 'group 2'], title="normalize='within'")
column means after normalize (first 3 columns): [ 0. 0. -0.]
Normalize and reduce¶
To normalize and reduce the dimensionality of the data, pass the normalize, reduce, and ndims arguments together. The reduce argument specifies the reduction method and ndims (int) the number of dimensions to reduce to.
Supported dimensionality reduction models include: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS, UMAP, NMF, LatentDirichletAllocation, and the torch autoencoders.
Below, reduce='PCA' with ndims=3 finds the 3 orthogonal directions along which the data vary most, so each 100-component dataset collapses to the 3 components that explain the most variability. This output is already three-dimensional, which is exactly what hyp.plot(..., reduce=None) is for: it draws the coordinates as they are.
[6]:
norm_reduced = hyp.analyze(weights, normalize='within', reduce='PCA', ndims=3)
print('after reduce:', [x.shape for x in norm_reduced])
fig = hyp.plot(norm_reduced, '.', reduce=None, names=['group 1', 'group 2'],
title='normalize -> PCA(3)')
after reduce: [(100, 3), (100, 3)]
Finer control¶
For finer control of the model parameters, reduce can be a dictionary with the keys model and kwargs. See the scikit-learn docs for the parameters each model supports. Here whiten=True rescales each component to unit variance, so the three axes have equal spread.
[7]:
reduce_spec = {'model': 'PCA', 'kwargs': {'whiten': True}}
reduced_params = hyp.analyze(weights, normalize='within', reduce=reduce_spec, ndims=3)
fig = hyp.plot(reduced_params, '.', reduce=None, names=['group 1', 'group 2'],
title='normalize -> PCA(3, whiten=True)')
Normalize, reduce, and align¶
Next, we normalize, reduce and then align all in one step. The align argument accepts:
'HyperAlign'- the hyperalignment algorithm (Haxby et al., 2011, Neuron).'hyper'is a legacy alias for the same name; it still works (here silently –hyp.align(model='hyper')is where it warns that it is deprecated)'SRM'- the shared response model (Chen et al., 2015)'Procrustes'- a single rotation onto one reference dataset
align='SRM' learns a separate basis for each dataset that maps it into a single shared latent response space, so after alignment the datasets are comparable coordinate by coordinate rather than only in aggregate. Compare the two trajectories here with the unaligned ones above: they now trace the same path.
[8]:
norm_red_algn = hyp.analyze(weights, normalize='within', reduce='PCA', ndims=3, align='SRM')
fig = hyp.plot(norm_red_algn, reduce=None, names=['group 1', 'group 2'],
title='normalize -> PCA(3) -> SRM')
Adding clustering¶
cluster= is the last stage. analyze still returns the transformed data (never labels), so the labels live in the fitted pipeline: pass return_model=True to get it back, and recover the labels with its 'cluster' step. The labels come as one flat sequence over the row-stacked datasets, exactly as hyp.cluster returns them for a list, and hyp.plot takes that flat sequence as hue= directly (one label per stacked row). K-means starts from random centroids, so the spec
seeds it ('random_state': 0 in its kwargs) to make the cluster sizes below reproducible.
[9]:
full_pipeline_data, pipeline = hyp.analyze(
weights, manip={'model': 'Smooth', 'kwargs': {'kernel': 'boxcar', 'kernel_width': 11}},
normalize='within', reduce='PCA', ndims=3, align='HyperAlign',
cluster={'model': 'KMeans', 'kwargs': {'n_clusters': 4, 'random_state': 0}}, return_model=True)
print('pipeline steps:', [name for name, _ in pipeline.steps])
labels = pipeline.named_steps['cluster'].transform(full_pipeline_data)
print('cluster sizes:', np.bincount(labels))
fig = hyp.plot(full_pipeline_data, '.', reduce=None,
hue=[f'cluster {k}' for k in labels], legend=True,
title='manip -> normalize -> reduce -> align -> cluster')
pipeline steps: ['manip', 'normalize', 'reduce', 'align', 'cluster']
cluster sizes: [20 74 41 65]
Replaying a fitted pipeline on new data¶
The Pipeline returned above remembers every fitted parameter (the smoothing kernel, the z-scoring means and standard deviations, the PCA loadings, the per-dataset alignment rotations, the cluster centroids). Passing it back as pipeline= applies those parameters to new data with no refitting. Here we hand it two new group averages from the 36-subject weights dataset (subjects 10-18 and 28-36, first 100 timepoints) – data it has never seen – and draw the result in the space the
pipeline learned.
[10]:
subjects = hyp.load('weights')
new_groups = [np.mean(subjects[9:18], 0)[:100], np.mean(subjects[27:36], 0)[:100]]
replayed = hyp.analyze(new_groups, pipeline=pipeline)
print('replayed:', [x.shape for x in replayed])
fig = hyp.plot(replayed, reduce=None, names=['new group A', 'new group B'],
title='new data through the fitted pipeline (no refitting)')
replayed: [(100, 3), (100, 3)]
Next steps¶
Every stage has its own tutorial: normalize, reduce, align, cluster.
The pipeline order guide explains why the stages run in this order and how
hyp.plotuses the same pipeline.hyp.plot(..., return_model=True)returns the same fittedPipelinealongside the figure.