API reference¶
This page lists every public entry point exported from hypertools
(see hypertools/__init__.py), organized roughly in the
canonical pipeline order (GH #153): load/impute,
manip, normalize, reduce, align, cluster, predict, plot/analyze, plus the
model-application core, I/O helpers, and the text/reducer model families
used by manip=/reduce=.
Load¶
|
Load data from a built-in example dataset, a scikit-learn or seaborn named dataset, a built-in synthetic dataset, a web source (Wikipedia/Yahoo Finance/SEC), a local file, a Hugging Face dataset, Google Drive, Dropbox, or any URL |
Save¶
|
Save obj to fname, choosing the output format from the file extension. |
Impute¶
|
Fill missing (NaN) values in data, preserving its shape. |
Manip¶
|
Apply a manipulation (or chain of manipulations) to data. |
Normalize¶
|
Z-transform the columns or rows of an array, or list of arrays |
Reduce¶
|
Reduces dimensionality of an array, or list of arrays |
Autoencoder reducers (GH #162) – the optional torch extra, installed
on demand (see Optional dependencies); pass by name (e.g.
reduce='Autoencoder') or by class to hypertools.reduce:
A single-hidden-layer (shallow) autoencoder reducer. |
|
A single-hidden-layer autoencoder with an L1 penalty on the hidden activation (sparse coding), encouraging a sparser, more interpretable intermediate representation. |
|
A multi-layer autoencoder reducer with configurable depth. |
|
A 1-D convolutional autoencoder reducer: two Conv1d layers slide across the feature axis (treating each row as a length-n_features, 1-channel signal), exploiting local structure among adjacent features rather than treating every feature independently. |
|
A GRU seq2seq autoencoder reducer for genuine timeseries/trajectory data: the ROWS of x are treated as one time-ordered sequence, and a latent vector is produced PER TIMEPOINT (transform(x) still returns (n_rows, n_components), one row per input row). |
|
A variational autoencoder (VAE) reducer: a probabilistic encoder (mean + log-variance heads) trained with a KL-divergence term toward a standard normal prior, via the reparameterization trick. |
Align¶
|
Aligns a list of datasets into a shared coordinate space. |
|
Function to project from one space to another using Procrustean transformation (shift + scaling + rotation + reflection). |
|
Score how well a list of equal-shape datasets agree with each other, optionally comparing before vs. after alignment. |
Cluster¶
|
Performs clustering analysis and returns a list of cluster labels |
Predict¶
|
Forecast t new rows continuing each input dataset. |
A bare DataFrame carrying a MultiIndex on one axis is split into groups and forecast one group at a time: a column MultiIndex groups by every level above the innermost one (the innermost level is the feature axis, so every group keeps all of the frame’s observations), while a row MultiIndex also groups by the outer levels but treats the innermost one as the time axis, which survives as each group’s index. The result is a list of forecasts, one per group – see Hierarchical DataFrames.
Observation times and future steps¶
Forecasting uses each dataset’s own observation times. Datetime, timedelta, period and unique numeric indexes are sorted together with their values before fitting. Periods are fitted on their start timestamps and forecast as periods of the same frequency. Duplicate time stamps are rejected; repeated numeric row IDs retain their positional meaning (for example, stacked runs). Arrays and categorical row labels use observation order. Shuffling timed rows therefore does not change the fitted forecast.
A datetime index with a calendar frequency – stored in index.freq,
inferable with pd.infer_freq (business days, month starts, weeks, quarters,
hours, tz-aware days across DST), or a PeriodIndex’s own – steps on that
calendar, so it is regular: it is fitted on its own rows and forecast onto the
next business days, month starts or periods. Weekday-only sessions that skip a
few weekdays (exchange holidays) step in business days. Otherwise one future
step is the median positive gap between sorted timestamps.
Override it with hyp.predict(data, step='1h') for datetime/duration indexes
(or a calendar frequency such as step='B' for datetime indexes),
or step=0.5 for numeric coordinates. Each dataset gets its own inferred
interval. A fitted model keeps its training interval when applied to new data,
so a learned one-hour transition never silently becomes a three-hour transition;
reused on a different kind of index (fit on an array, applied to dated rows, or
the reverse) it steps in the new data’s own units.
GaussianProcess fits the actual times, expressed as elapsed multiples of the model’s step. Kalman, ARIMA, AutoRegressor, Laplace and Chronos assume regular steps: irregular data are linearly interpolated column by column onto a regular grid ending at the latest observation, with a warning. The grid stays inside the observed time span; training values are never extrapolated. Existing missing values are not imputed by this operation. Interpolation can smooth short-lived changes; choose the interval for your data, or use GaussianProcess to retain the original observation times without interpolation. Models retain their existing univariate/multivariate behavior.
hyp.plot(..., predict=...) follows the same policy. In ndims=1 mode,
the time index supplies predictor coordinates rather than becoming another
signal column to forecast. The columns of each dataset are forecast together,
then split into lines for drawing. For a step override in a plot, use
predict={'model': 'Kalman', 'kwargs': {'step': '1h'}}. Animated forecasts
use only the observations revealed so far and wait until the model has enough
history, including enough interpolated grid points. If preprocessing changes
the row count and discards the corresponding timestamps, pass the analyzed
data with its updated index explicitly instead of guessing its times.
Backtesting at observation times¶
hyp.predict(..., holdout=...) sorts timed observations before holding out
the last rows. The model and its interval are fitted on the remaining training
rows only. GaussianProcess evaluates predictions at the actual held-out times.
Regular-grid models forecast far enough to cover those times, then select
matching grid points or linearly interpolate predictions between them.
For a held-out time before the first full forecast step, interpolation starts
at the last observed training value. Missing endpoints remain missing;
held-out values are never used in fitting or interpolation.
Returned forecasts, the naive baseline and 'truth' share the held-out
index. horizon in the scores table counts held-out observations, which can
differ from the number of regular forecast steps. Arrays, categorical row
labels and repeated numeric row IDs are scored by observation position.
Choosing trading-day positions instead of calendar dates is therefore an
explicit modeling choice; the stock-forecasting tutorial demonstrates both.
For example, these observations are scored at times 12 and 20, rather than being compared with the model’s next two regular steps at times 9 and 10:
>>> import pandas as pd
>>> import hypertools as hyp
>>> from sklearn.gaussian_process.kernels import DotProduct
>>> timed = pd.DataFrame({'value': [0., 1., 2., 4., 7., 8., 12., 20.]},
... index=[0., 1., 2., 4., 7., 8., 12., 20.])
>>> scores, evaluated = hyp.predict(
... timed, model='GaussianProcess', holdout=2, return_forecasts=True,
... kernel=DotProduct(sigma_0=1, sigma_0_bounds='fixed'))
>>> evaluated['GaussianProcess'].index.tolist()
[12.0, 20.0]
>>> evaluated['GaussianProcess'].index.equals(evaluated['truth'].index)
True
Plot¶
|
Plots dimensionality reduced data and parses plot arguments |
|
Create a figure and a FLAT array of hypertools-ready axes (GH #285). |
|
A |
|
State of one drawn animation frame. |
Hierarchical (MultiIndex) frames are expanded into one trace per group plus
a derived mean at every level above the leaves. The two axes are read
differently – a row MultiIndex draws one trace per unique full index
tuple, whereas a column MultiIndex makes its innermost level the feature
axis and groups by everything above it – and predict= then forecasts
every final trace, leaves and means alike. See Hierarchical DataFrames for the
comparison table, the feature-correspondence rule and the return shapes.
Colors¶
- hypertools.plot.colors.image_palette(image, n_colors=6, resize=200, random_state=0, max_luminance=None, min_luminance=None, sort=None)[source]¶
Extract a color palette from an image, most VISUALLY SALIENT first (or in the order
sort=asks for).- Parameters:
- imagestr, pathlib.Path, PIL.Image.Image, or numpy array
A LOCAL image file, an already-open PIL image, or an (H, W, 3) array (uint8 0-255, or float 0-1). URLs are deliberately not accepted: hypertools does not fetch images, so download and cache the file yourself and pass the cached path.
- n_colorsint
UPPER bound on how many colors to return (default 6). Fewer come back when the image has fewer distinct colors, or when two cluster centers coincide to 3 decimal places.
- sortsee sort_colors, or None (default)
None keeps the salience order (most visually salient first: the color the image is ABOUT, used as a dataset’s lead color). A key reorders the extracted colors;
palette='image:...'uses'value'unless the spec says otherwise (?sort=hue,?sort=original), so an image palette reads as a gradient.- resizeint
Longest edge the image is thumbnailed to before clustering (default 200). Clustering cost is linear in pixel count.
- random_stateint
Seed for the k-means fit, so repeated calls return the same palette (to within ~1e-15 per channel: k-means’ threaded reductions sum in whatever order the threads finish, so the centers are reproducible but not bit-identical – compare extracted colors with
np.allclose, never==).- max_luminancefloat or None
Drop extracted colors BRIGHTER than this (default None: keep all). Luminance is
0.2126 R + 0.7152 G + 0.0722 Bover RGB in [0, 1] (luminance / LUMINANCE_WEIGHTS). Filtering happens AFTER the salience ordering, soimage_palette(path, max_luminance=0.6)[0]is “the most salient color that is still legible on a white page”: The Great Wave’s two most salient clusters are its cream sky and foam (luminance 0.88 and 0.94), and this is what steps past them to its Prussian blue.- min_luminancefloat or None
Drop extracted colors DARKER than this (default None: keep all) – the same filter from the other end, for artwork whose salient colors are near-black on a dark page.
- Returns:
- palettenumpy.ndarray
(k, 3) float RGB in [0, 1], k <= n_colors, ordered most salient first.
- Raises:
- ValueError
If a luminance bound excludes EVERY extracted color. The message reports the luminances actually measured, because the fix (widen the bound, raise n_colors so more clusters are extracted, or use a different image) depends on which of them it was.
Notes
Salience is
pixel_fraction * chroma, wherechroma = max(r, g, b) - min(r, g, b)measures distance from gray. Ordering by pixel fraction ALONE returns a painting’s background – which is exactly the bug this function exists to avoid. When every cluster is achromatic (max chroma < 0.02, i.e. a grayscale image) the ordering falls back to pixel fraction, because a gray image has no vivid color and “largest” is then the right answer.Examples
>>> from hypertools.plot.colors import image_palette >>> image_palette('starry_night.jpg')[0] array([0.16, 0.24, 0.55])
The same extraction is reachable declaratively from any plotting call that takes a palette, luminance bounds included:
hyp.plot(x, hue=values, palette='image:starry_night.jpg') hyp.plot(x, hue=values, palette='image:great_wave.jpg?max_luminance=0.6')
- hypertools.plot.colors.get_palette_colors(palette, n_colors)[source]¶
Resolve n_colors RGB colors from a palette (name, list of colors, or matplotlib Colormap).
Public wrapper around _get_palette so callers outside this module (e.g. colorbar construction in plot.py/plotly_backend.py) can build a color mapping that is GUARANTEED to match what mat2colors / sns.set_palette would produce for the same palette/n_colors – the single source of truth for “what color is group i / value v”. Returns a (n_colors, 3) float array; n_colors=0 returns an empty (0, 3) array.
- hypertools.plot.colors.continuous_colormap(palette, n_bins=100)[source]¶
Build a matplotlib ListedColormap matching mat2colors’s continuous path (same palette, same default n_bins, same cyclic-palette trimming), so a colorbar built from this colormap shows EXACTLY the colors used for continuously-hued lines/markers.
Colors extracted from an image are put in a deterministic order before they
become a plot palette – by value, dark to bright, unless palette_sort=
(or ?sort= in an 'image:<path>' spec) asks for another key – while
image_palette itself, and the lead color of a dataset an image stands
for, keep the most-salient-first order.
- hypertools.plot.colors.sort_colors(colors, key='value')[source]¶
Put colors in a deterministic order.
- Parameters:
- colorssequence of RGB triples (values in [0, 1])
- key{‘value’, ‘hue’, ‘lightness’, ‘columns’, ‘original’} or None
'value': HSV value (dark to bright), then hue, then saturation – the default for a palette extracted from an image, so it reads as a gradient instead of the extraction order.'hue': hue (red, yellow, green, cyan, blue, magenta), then value, then saturation.'lightness': relative luminance (luminance), then hue, then saturation.'columns': lexicographic by the color’s own columns, first column first – the default for a palette built from a data matrix, whose first column is its first component, the axis of most variance.'original'or None: unchanged.
Every key is a sequence of tie-breakers in decreasing priority, compared after rounding to six decimals so equal colors never reorder between runs.
- Returns:
- numpy.ndarray of shape (n, 3)
A t x k data matrix is a palette too. matrix_palette reduces it to three
dimensions with hypertools.reduce (palette_reduce= in plot,
default 'PCA', with palette_manip=/palette_normalize=/
palette_align= passed through), scales each reduced column to [0, 1] as
an RGB channel, sorts the rows (default 'columns': along the first
component) and returns a colormap that a plot resamples by interpolation to
as many colors as it needs.
- hypertools.plot.colors.matrix_palette(data, reduce='PCA', sort='columns', normalize=None, manip=None, align=None, random_state=0, n_colors=256, name='hypertools-matrix')[source]¶
Build a palette from a t x k data matrix.
The rows are reduced to three dimensions with hypertools.reduce (
reduce=names the reducer,normalize=/manip=/align=are handed to it as they would be to any reduce call), each reduced column is scaled to [0, 1] and read as an RGB channel, the rows are put in order with sort_colors, and the result is returned as a matplotlib Colormap, which every palette path samples by interpolation to however many colors a plot needs (one per dataset, one per category, or a gradient along a continuous hue=).How smooth the palette looks depends on the matrix: with the default sort the rows are ordered along the first component, so the other two channels vary smoothly only where the matrix’s other components are themselves ordered along the first (a trend with oscillations gives a clean gradient; an unstructured random walk gives a striped one).
- Parameters:
- dataarray-like or pandas.DataFrame of shape (t, k)
At least two rows of finite numbers. A matrix with three or fewer columns is not reduced (its columns are the channels; missing channels are filled with 0.5), but
normalize/manip/alignstill apply when given.- reducereducer spec (default ‘PCA’)
Any form hypertools.reduce accepts.
- sortsee sort_colors (default ‘columns’: along the first component)
- normalize, manip, alignpassed to hypertools.reduce
- random_stateint (default 0)
Seeds the reducer, so the same matrix always gives the same palette.
- n_colorsint (default 256)
Resolution of the returned colormap.
- namestr
The colormap’s name.
- Returns:
- MatrixColormap
A LinearSegmentedColormap subclass that samples the ordered rows by exact linear interpolation.
- class hypertools.plot.colors.MatrixColormap(name, anchors, N=256)[source]¶
A LinearSegmentedColormap built from ordered anchor colors that samples by EXACT linear interpolation between them (a plain LinearSegmentedColormap quantizes to its lookup table, so a plot asking for as many colors as there are anchors would not get the anchors back). Everything else – colorbars, resampled, reversed – is inherited.
Set interactive backend¶
|
Set the plotting backend hypertools uses. |
Set autoinstall¶
|
Turn the on-demand installation of optional extras on or off. |
The optional features (the plotly backend, text embeddings, Laplace and
Chronos forecasting, the torch autoencoders, gensim models, Kaggle and
Hugging Face loading, LSL streaming, 3-D density iso-surfaces, .xlsx
files) are pip extras that install themselves on demand: the first call
that needs one installs that extra’s requirements, prints a one-line
hypertools: notice and carries on. set_autoinstall(False) turns
this off (for the session, or for one block as a context manager); a
missing extra then raises ImportError naming the manual pip install
"hypertools[<extra>]" command. See Optional dependencies for the
extras, the Chrome step behind static plotly export, and how to
pre-install everything.
Analyze¶
|
Wrapper function for manip -> normalize -> reduce -> align -> cluster transformations (the canonical 1.0 pipeline order, GH #153): each requested stage is applied to the previous stage's output, in that order (e.g. normalize= output feeds reduce=, whose output feeds align=). |
Apply model¶
|
Apply a model (or pipeline of models) to one or more datasets. |
Names accepted as string model specifications. |
Pipeline¶
hypertools.Pipeline chains fitted pipeline stages for reuse (GH #227
#161). Standalone dispatchers (hypertools.reduce, hypertools.manip,
…) called with return_model=True return a hypertools.Pipeline when
more than one stage ran (and the single fitted wrapper when only one stage
ran); hypertools.plot’s return_model=True bundle always carries a
hypertools.Pipeline under its 'pipeline' key, even for a single
stage. A hypertools.Pipeline can be applied to new data via
.transform() and passed back in via pipeline= to
hypertools.plot/hypertools.analyze.
|
Chain hypertools model specs into one fit/transform-able object. |
Describe¶
|
Describe how well reduced data preserves the raw data's pairwise-distance structure, as a function of the number of dimensions |
Text vectorization¶
|
Turns a list of text samples into a matrix using a vectorizer and a text model |
Gensim text models (GH #198) – the optional gensim extra, installed
on demand (see Optional dependencies); pass by name (e.g.
vectorizer='Word2Vec') to hypertools.tools.text2mat:
Vectorizer-stage model: a document's vector is the mean of its tokens' trained gensim Word2Vec word vectors (out-of-vocabulary tokens at transform time are skipped; a document with no known tokens gets the zero vector). |
|
Vectorizer-stage model: a document's vector is either its trained gensim Doc2Vec tag vector (for documents seen during fit) or an inferred vector (Doc2Vec.infer_vector) for new documents at transform time. |
|
Vectorizer-stage model: a document's vector is the mean of its tokens' trained gensim FastText word vectors. |
|
Semantic-stage model: gensim's LdaModel (Latent Dirichlet Allocation) trained over a bag-of-words corpus built internally from a dense document-term matrix (e.g. the output of a vectorizer-stage model). |
|
Semantic-stage model: gensim's LsiModel (Latent Semantic Indexing) trained over a bag-of-words corpus built internally from a dense document-term matrix. |
|
Semantic-stage model: gensim's HdpModel (Hierarchical Dirichlet Process), which discovers its own number of topics from the data rather than taking a fixed num_topics (unlike LdaVectorizer/ LsiVectorizer). |
I/O¶
|
Resolve a live Lab Streaming Layer (LSL) stream and return it as a plain Python iterator of per-sample numeric vectors, compatible with hypertools.io.streaming.is_stream/row_to_vector -- so the result can be passed directly to hyp.plot(..., stream_init=..., stream_chunk= ...). |
|
Iterator of per-sample vectors from a pylsl.StreamInlet, with deterministic teardown. |
|
Start a REAL pylsl.StreamOutlet on a background daemon thread, continuously pushing synthetic samples -- for exercising |
Exceptions¶
HyperTools’ I/O and backend errors derive from hypertools.HypertoolsError.
HypertoolsOfflineError (hyp.load(..., offline=True) with no cached copy
to read) is a HypertoolsIOError, importable from hypertools and
hypertools.io. HypertoolsTrustError is raised by load when a remote
payload would have to be unpickled (a pickle, or an object-array .npy/.npz)
and trust=True was not passed; it subclasses ValueError, not
HypertoolsError, and is importable from hypertools (it is defined in
hypertools.io.sources). Input-validation
errors (invalid parameters or data shapes) raise standard
ValueError/TypeError with actionable messages.
Base class for all hypertools-specific exceptions. |
|
|
Raised when a plotting backend (matplotlib/plotly) cannot satisfy a request. |
|
Raised for hypertools-specific I/O failures (e.g. loading/streaming data). |
|
Raised when |
Raised when a remote payload can only be loaded by relaxing a security policy (currently: |
Tools¶
|
Cut text into sliding windows: one observation per window. |
|
Set a fraction of cells (and/or whole rows) to NaN, reproducibly. |
|
Stack datasets side by side into a column-hierarchical DataFrame. |
|
Formats data into a list of numpy arrays |
|
Returns indices of missing data |
|
Transforms a Pandas DataFrame into a Numpy array with binarized text columns |