Dimensionality reduction

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 reduce function reduces the dimensionality of an array or list of arrays. The default model is IncrementalPCA, but a variety of models are supported. Note that ndims defaults to None, which means no dimensionality reduction is performed unless you explicitly request a target number of dimensions via ndims.

Supported models include: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS, UMAP, NMF, LatentDirichletAllocation, and six torch autoencoders (Autoencoder, DeepAutoencoder, SparseAutoencoder, ConvolutionalAutoencoder, SequenceAutoencoder, VariationalAutoencoder).

Import Hypertools

[1]:
import hypertools as hyp

%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')

Reduce one array

Let’s look at one array from the dataset above.

[3]:
print('Array shape: (%d, %d)' % weights[0].shape)
Array shape: (100, 100)

To reduce this array, pass the array to hyp.reduce along with the desired number of dimensions via ndims. Below we reduce from 100 features to 3 features by setting ndims=3 (if ndims is omitted, no reduction is performed).

[4]:
reduced_array = hyp.reduce(weights[0], ndims=3)
print('Reduced array shape: (%d, %d)' % reduced_array.shape)
Reduced array shape: (100, 3)

Reduce list of arrays

A list or numpy array of multiple arrays can also be reduced into a common space. That is, the data can be combined, reduced as a whole, then split back into individual elements and outputted via hyp.reduce.

Here we show this with the two arrays in the weights dataset. The first was printed above as a 100 x 100 array (timepoints by components); the second has the same shape.

[5]:
reduced_arrays = hyp.reduce(weights, ndims=3)
print('Shape of first reduced array: ', reduced_arrays[0].shape)
print('Shape of second reduced array: ', reduced_arrays[1].shape)
Shape of first reduced array:  (100, 3)
Shape of second reduced array:  (100, 3)

We can see that each array has been reduced from 100 features to 3 features (since we set ndims=3), with the number of datapoints unchanged. Reduced data can be drawn directly with hyp.plot(..., reduce=None): the coordinates are already three-dimensional, so nothing further is reduced.

[6]:
fig = hyp.plot(reduced_arrays, reduce=None, names=['group 1', 'group 2'], title='IncrementalPCA, 3 components')
../_images/tutorials_reduce_13_0.png

Reduce to a specified number of dimensions

You may prefer to reduce to a specific number of features other than three. To achieve this, simply pass the number of desired features (as an int) to the ndims argument, as below.

[7]:
reduced_4 = hyp.reduce(weights, ndims=4)
print('Shape of first reduced array: ', reduced_4[0].shape)
print('Shape of second reduced array: ', reduced_4[1].shape)
Shape of first reduced array:  (100, 4)
Shape of second reduced array:  (100, 4)

Reduce list of arrays with specific parameters

For finer control of parameters, pass the reduce argument a dictionary with the keys model (the desired reduction method) and kwargs (a dictionary of model parameters). See scikit-learn model docs for details on parameters supported for each model.

Below, whiten=True rescales each component to unit variance, so the returned features have equal spread rather than the first principal component dominating the range. The shape of the data is preserved; the relative scale of the components is not.

[8]:
reduced_params = hyp.reduce(weights, reduce={'model': 'PCA', 'kwargs': {'whiten': True}}, ndims=3)
fig = hyp.plot(reduced_params, reduce=None, names=['group 1', 'group 2'], title='PCA, whiten=True')
../_images/tutorials_reduce_17_0.png

Nonlinear methods: TSNE and UMAP

You can also opt to use different reduction methods. TSNE and UMAP are nonlinear neighbor embeddings: they preserve each point’s local neighborhood rather than the directions of greatest variance, so distances between far-apart points in the embedding are not meaningful. TSNE provides no reusable projection (scikit-learn’s TSNE has no transform method), so a new dataset cannot be mapped into an existing TSNE embedding; UMAP does. Both depend on their random initialization, so we fix random_state for a reproducible figure. Below we pass hyp.plot a list of reducers via reduce=[...], together with panels=True, so it draws the two embeddings side by side – one panel per reducer, each fitting its own full pipeline on weights – in a single call.

[9]:
fig = hyp.plot(
    weights, '.', panels=True, ndims=3, names=['group 1', 'group 2'],
    reduce=[{'model': 'TSNE', 'kwargs': {'random_state': 0}},
            {'model': 'UMAP', 'kwargs': {'random_state': 0, 'n_jobs': 1}}],
    title=['TSNE', 'UMAP'])
../_images/tutorials_reduce_19_0.png

Autoencoders

reduce also accepts torch autoencoders ('Autoencoder', 'DeepAutoencoder', 'SparseAutoencoder', 'ConvolutionalAutoencoder', 'SequenceAutoencoder', 'VariationalAutoencoder'; the [torch] extra installs itself on first use). They are trained networks, so the model kwargs are training settings: epochs, batch_size, random_state. A shallow Autoencoder with a small budget is enough for these two 100 x 100 arrays; the learned 3-D bottleneck plays the role of the principal components, but the encoder is nonlinear.

[10]:
reduced_AE = hyp.reduce(weights, reduce={'model': 'Autoencoder',
                                         'kwargs': {'epochs': 40, 'batch_size': 20, 'random_state': 0}},
                        ndims=3)
print('Autoencoder:', reduced_AE[0].shape)
fig = hyp.plot(reduced_AE, reduce=None, names=['group 1', 'group 2'], title='Autoencoder, 3-D bottleneck')
Autoencoder: (100, 3)
../_images/tutorials_reduce_21_1.png

How many dimensions do you actually need?

hyp.describe is the companion to hyp.reduce: for each candidate number of dimensions it reduces the data and correlates the pairwise distances of the reduced data with those of the full data, so you can see how much structure each extra dimension buys. It returns a dict of scores – 'individual' (one curve per dataset), 'average' (the mean of those curves, drawn as the dashed line), and 'pooled' (the curve for all datasets stacked into one point cloud, which is not drawn) – plus the figure under 'fig'. Called with the defaults it draws and shows the figure; with show=False it still returns the figure, without displaying it. For these data the curve starts around 0.8 at two dimensions, passes 0.9 by five, and keeps creeping toward 1 – so three dimensions carry most of the pairwise-distance structure, and each further dimension buys a little less.

[11]:
scores = hyp.describe(weights, max_dims=20)
print('average correlation with the full data at 2..6 dimensions:',
      [round(float(v), 3) for v in scores['average'][:5]])
../_images/tutorials_reduce_23_0.png
average correlation with the full data at 2..6 dimensions: [0.781, 0.852, 0.888, 0.914, 0.928]

Reusing a fitted reducer with return_model

return_model=True also returns the fitted reducer. Passing it back as reduce= applies the same projection to new data (via .transform) instead of refitting – so two datasets reduced separately land in one shared coordinate system, exactly as if the model had seen both. Here we fit the default reducer (IncrementalPCA) on the first array only, then project the second through it.

[12]:
reduced_first, reducer = hyp.reduce(weights[0], ndims=3, return_model=True)
print('fitted reducer:', type(reducer).__name__)

reduced_second = hyp.reduce(weights[1], reduce=reducer)   # transform only, no refit
fig = hyp.plot([reduced_first, reduced_second], reduce=None, names=['group 1 (fit)', 'group 2 (projected)'],
               title='group 2 projected through the reducer fit on group 1')
fitted reducer: Reducer
../_images/tutorials_reduce_25_1.png

Next steps

  • `hyp.plot <plot.ipynb>`__ accepts the same reduce= / ndims= arguments and reduces before drawing.

  • The plot_autoencoders and plot_describe gallery examples go deeper on the autoencoders and on describe.

  • The analyze tutorial chains reduction with normalization, alignment and clustering.