hypertools.load

hypertools.load(dataset, reduce=None, ndims=None, align=None, normalize=None, *, legacy=False, split=None, streaming=False, trust=False, cache=False, offline=False, decode_labels=True, **source_kwargs)[source]

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

A string is interpreted by trying, in order:

  1. a built-in example dataset name (listed below)

  2. a scikit-learn bundled dataset name – 'iris', 'digits', 'wine', 'breast_cancer', 'diabetes', or 'linnerud' (the small datasets shipped with sklearn.datasets; the network-fetched fetch_* datasets are not included). Loaded via the corresponding sklearn.datasets.load_* function and returned as a DataFrame of the features with the target appended as a 'target' column (for multi-output targets, e.g. 'linnerud', one column per target name instead)

  3. a seaborn dataset name – any name returned by seaborn.get_dataset_names() (e.g. 'penguins', 'tips', 'titanic'), loaded via seaborn.load_dataset() and returned unchanged. The name listing is a network lookup (fetched with a timeout and cached per-process; a failed fetch is remembered for hypertools.io.sources.SEABORN_LISTING_RETRY_AFTER seconds – hypertools.io.sources.reset_seaborn_names_cache() retries sooner); if it can’t reach the seaborn-data repo, this step is skipped. The listing is never consulted for a string that cannot be a seaborn name (a URL, a path, a prefixed source) nor when offline=True. (A registered synthetic dataset name – step 6 below – is actually resolved here, ahead of this lookup, so it never pays for the network round trip; no synthetic name collides with a seaborn one)

  4. a FiveThirtyEight dataset, explicit prefix 'fivethirtyeight/<slug>' (e.g. 'fivethirtyeight/bechdel'), where <slug> is the dataset’s folder in https://github.com/fivethirtyeight/data. The folder’s CSV file(s) are downloaded from raw.githubusercontent.com: a single CSV becomes a DataFrame, multiple CSVs become a dict of {filename: DataFrame}

  5. a Kaggle dataset, explicit prefix 'kaggle/<owner>/<dataset>' (e.g. 'kaggle/uciml/iris'), downloaded anonymously via kagglehub.dataset_download (the [kaggle] extra installs itself on first use). Every CSV/TSV file in the dataset is loaded the same way as step 4

  6. a built-in synthetic dataset name – generated on the spot, never fetched, and fully reproducible given random_state= (seed= is accepted as an alias). The registered names and their keyword arguments are the single source of truth in hypertools.io.sources.SYNTHETIC_DATASETS (see also hypertools.io.sources.synthetic_dataset_docs()); as of this writing they are:

    • random_walk – Gaussian random walk (kwargs: n_samples, n_features, step, drift)

    • helix – 3D helix (kwargs: n_samples, turns, noise, radius, pitch)

    • lorenz – Lorenz attractor trajectory (kwargs: n_samples, sigma, rho, beta, dt, x0)

    • blobs, moons, swiss_roll, s_curve – thin wrappers around the matching sklearn.datasets.make_* function, returned as a DataFrame with a 'target' (or, for the manifold datasets, a position) column

    Every synthetic dataset also accepts n_datasets=<int> (default 1): when greater than 1, the result is a list of that many independently seeded datasets – one hypertools multi-dataset, the same shape hypertools.load('weights') returns

  7. a web source with an explicit prefix – 'wikipedia:<Title>' (kwargs: lang, intro, timeout), 'yahoo:<TICKER>' (kwargs: start, end, interval, timeout), or 'sec:<TICKER>' (kwargs: concept, taxonomy, unit, dedupe, timeout) – see hypertools.io.sources.web_source() for details on each

  8. a path to a local file (.geo/pickle, .npy/.npz, .csv/.tsv/.txt, .json, .parquet, .mat, .xlsx/.xls; gzip-compressed variants (.gz) are decompressed transparently). Files with no extension are parsed by content sniffing; files with any other extension raise an error unless their content matches a recognized binary format (pickle/npy/zip)

  9. a Hugging Face dataset id such as 'scikit-learn/iris' (pass streaming=True for a streaming dataset, which can be passed straight to hypertools.plot())

  10. a Google Sheets URL (docs.google.com/spreadsheets/d/<id>), loaded via its CSV export

  11. a Google Drive URL or bare file id (large files behind Drive’s “can’t scan this file for viruses” interstitial are followed automatically)

  12. a Dropbox URL or shared-link path

  13. any other URL, with or without an https:// scheme

Note

Precedence: a built-in example dataset name (step 1) always wins, even over a same-named scikit-learn/seaborn dataset. Between scikit-learn and seaborn, scikit-learn wins – e.g. 'iris' resolves to scikit-learn’s load_iris (columns like 'sepal length (cm)'), not seaborn’s 'iris' dataset (columns like 'sepal_length'), since both define an 'iris' name. Because these resolvers run before local-file resolution, a local file whose name (without an extension) matches a scikit-learn, seaborn, or synthetic dataset name is shadowed – pass a path with an extension, or an absolute/relative path containing a /, to force local-file resolution.

The 'fivethirtyeight/', 'kaggle/', 'wikipedia:', 'yahoo:' and 'sec:' prefixes (steps 4-5 and 7) are explicit: a name starting with one of them is always treated as that source, so a same-named relative local path (e.g. a local file fivethirtyeight/bechdel) is shadowed – prepend './' to force local-file resolution. For the same reason, a prefixed name that then fails (unknown slug/dataset id, no CSV/TSV files found, malformed id, unreachable web source) raises immediately instead of falling through to the remaining steps.

Any keyword argument that isn’t reduce/ndims/align/ normalize/legacy/split/streaming/trust/ cache/offline/decode_labels is collected into **source_kwargs and handed to whichever of the synthetic (step 6) or web (step 7) resolvers matches; passing one with any other kind of source – including already-loaded data – raises TypeError naming it, so a misspelled keyword can’t be silently dropped.

Parameters:
datasetstring, path-like, DataFrame, numpy array, or list of those

The name of a built-in example dataset (listed below), a dataset name resolvable per the steps above, or a file path / URL.

Data that is already loaded – a DataFrame (pandas, or a polars DataFrame/LazyFrame), a numpy array, or a list/tuple of DataFrames/arrays (one hypertools dataset per element, the same shape hypertools.load('weights') returns) – is passed through unchanged, so hypertools.load can serve as a uniform entry point over a mix of names and in-memory data:

>>> import numpy as np
>>> import hypertools
>>> arr = np.zeros((10, 3))
>>> hypertools.load(arr) is arr
True
>>> [type(d).__name__ for d in hypertools.load([arr, 'spiral'])]
['ndarray', 'list']

The reduce/ndims/align/normalize options apply to passed-through data exactly as they do to loaded data (a list of arrays is analyzed as one multi-dataset, e.g. aligned across its elements). Any other type (a dict, a number, a list mixing in such a value) raises TypeError.

weights is a list of numpy arrays, one PER SUBJECT (36 arrays, each 300 timepoints x 100 parameters, float32), containing brain activity (fMRI) from subjects listening to the same story, fit using Hierarchical Topographic Factor Analysis (HTFA) with 100 nodes; each array’s rows are timepoints and its columns are model parameters.

weights_sample is a sample of 3 subjects from that dataset.

weights_avg is a 2-array group-averaged variant of the same experiment: a list of two (100, 100) arrays, one per group.

spiral is a list of two (1000, 3) numpy arrays containing 3D spiral data, used to highlight the procrustes function.

mushrooms is a pandas DataFrame of categorical features (columns) describing 8,124 mushroom samples (rows).

sotus is a list of 29 State of the Union addresses (1989-2017), as strings, grouped by president rather than in date order.

wiki is a list of 3,136 wikipedia page texts (strings), used to fit wiki_model.

nips is a list of NIPS conference paper texts (strings, ~181 MB download), used to fit nips_model.

wiki_model, nips_model, and sotus_model are sklearn Pipelines (CountVectorizer -> LatentDirichletAllocation, 50 topics) trained on the wiki, nips, and sotus corpora, respectively; each transforms text into 50-dimensional topic vectors. (The hosted files were pickled under an older scikit-learn; hypertools backfills newer estimator attributes on load so repr()/get_params()/transform() work under the installed version.)

The “shapes zoo” datasets – bunny, cube, dragon, sphere, teapot, vase, and biplane – are 3D point clouds of the corresponding objects (numpy arrays / DataFrames of x, y, z coordinates), useful for demonstrating alignment and plotting.

datasaurus is the “Datasaurus Dozen”: a list of 2D datasets with near-identical summary statistics but wildly different shapes.

reducestr, dict, class, instance, or fitted Reducer

Decomposition/manifold learning model to use (default: ‘IncrementalPCA’). Models supported: PCA, IncrementalPCA, SparsePCA, MiniBatchSparsePCA, KernelPCA, FastICA, FactorAnalysis, TruncatedSVD, DictionaryLearning, MiniBatchDictionaryLearning, TSNE, Isomap, SpectralEmbedding, LocallyLinearEmbedding, MDS, and UMAP; the mixture models GaussianMixture, BayesianGaussianMixture, LatentDirichletAllocation and NMF (GH #174); and the torch autoencoders Autoencoder, DeepAutoencoder, SparseAutoencoder, ConvolutionalAutoencoder, SequenceAutoencoder and VariationalAutoencoder (GH #162; the [torch] extra installs itself on first use). Can be passed as a string, or for finer control as a dictionary, e.g. reduce={‘model’: ‘PCA’, ‘kwargs’: {‘whiten’: True}}. See scikit-learn model docs for details on parameters supported for each model.

ndimsint

Number of dimensions to reduce

alignstr, dict, False, or None

Alignment model to bring a list of datasets into a shared space. If str, ‘HyperAlign’ (hyperalignment) or ‘SRM’ (shared response model). You can also pass a dictionary for finer control, where ‘model’ specifies the model and ‘kwargs’ holds its parameters, e.g. align={‘model’: ‘HyperAlign’, ‘kwargs’: {‘n_iter’: 10}}. If False or None, no alignment is applied (default: None).

normalizestr or False or None

If set to ‘across’, the columns of the input data will be z-scored across lists. That is, the z-scores will be computed with respect to column n across all arrays passed in the list. If set to ‘within’, the columns will be z-scored within each list that is passed. If set to ‘row’, each row of the input data will be z-scored. If set to False or None (default), the input data will be returned with no z-scoring.

legacybool

Pass legacy=True to read a dataset saved in the old pickled DataGeometry format by hypertools<0.8.0. Its raw data is extracted and returned like any other dataset – a DataGeometry object is never returned (that class is not part of the 1.0 API).

splitstring or None

Hugging Face datasets only: which split to load (default: the ‘train’ split if present, otherwise the first available split).

streamingbool

Hugging Face datasets only: if True, return a streaming IterableDataset instead of materializing the data (see https://huggingface.co/docs/datasets/en/stream). The result can be passed directly to hypertools.plot(). Every other kind of source (built-in, scikit-learn, seaborn, synthetic, web, local file, URL, or already-loaded data) is always loaded in full, so passing streaming=True with one raises ValueError naming the source rather than silently returning the whole dataset.

trustbool

Remote (non-built-in) sources only. Unpickling a payload fetched from a URL/Drive/Dropbox/Sheets executes arbitrary code embedded in it, so by default hypertools refuses to unpickle remote data (raising HypertoolsIOError – a warning is not a security boundary). Remote .npy/.npz payloads are likewise loaded with allow_pickle=False (raising if the array actually needs pickle support, e.g. an object array). Pass trust=True – only once you have verified the source – to allow unpickling remote data and pickle-backed remote arrays. This covers every remote-pickle path (extension-based, content-sniffed, and extensionless). Non-executable remote formats (.csv/.npz numeric/.parquet) never require trust. Built-in example datasets (listed below) are downloaded from a fixed, integrity-checked set of hosts and do not require this flag. Note that trust governs REMOTE sources; a local file path is treated as trusted and unpickled without it (matching numpy.load / pandas.read_pickle), so only hyp.load() a local pickle you created or trust. Local files are never subject to this policy.

cachebool

Any Google-Sheets/Google-Drive/Dropbox/URL download (steps 10-13) only – Hugging Face datasets (step 9) are NOT cached here: when True, the downloaded bytes are stored on disk (under hypertools.io.sources.url_cache_dir(), override with the HYPERTOOLS_URL_CACHE environment variable) and reused on a later call instead of re-downloading. Default False – matching trust, hypertools does not write to disk unless asked.

offlinebool

When True, never open a connection: the sources cache covers (steps 10-13) are read ONLY from that on-disk cache, every network-only resolver (the seaborn listing, FiveThirtyEight, Kaggle, Hugging Face, the wikipedia:/yahoo:/sec: web sources) is skipped or refused outright, and anything that cannot be served from disk raises HypertoolsOfflineError (a subclass of HypertoolsIOError) – naming the cache path it looked for when the source is a cacheable URL that was never cached. scikit-learn, synthetic and local-file sources still load. A hosted built-in example dataset (step 1, the *_model pipelines included) is served from its copy in the example-data cache (~/hypertools_data) when that copy is present and passes its SHA-256 integrity check; one that was never fetched, or whose cached file fails the check, raises HypertoolsOfflineError naming the file – nothing is downloaded and the file is left in place (online, a failed check triggers a re-download). Load a URL once with cache=True, and a built-in once with any call, while online to populate the caches first.

decode_labelsbool

Hugging Face datasets only: by default (True), any top-level ClassLabel feature column is decoded from its integer codes to the string names the dataset itself defines (matching what a streaming load already exposes). Pass decode_labels=False to keep the raw integer codes.

**source_kwargs

Extra keyword arguments for a built-in synthetic dataset name (step 6, e.g. hypertools.load('random_walk', n_samples=500, random_state=0)) or an explicit web-source prefix (step 7, e.g. hypertools.load('yahoo:AAPL', start='2020-01-01')). See those steps above, hypertools.io.sources.SYNTHETIC_DATASETS and hypertools.io.sources.web_source() for the accepted names. Passing any of these with a dataset that doesn’t consume them (a built-in/scikit-learn/seaborn/fivethirtyeight/kaggle/local-file source, or already-loaded data) raises TypeError naming the unexpected keyword(s) rather than silently ignoring them.

Returns:
datanumpy array, DataFrame, list, or IterableDataset

The loaded raw data (a list of datasets when a list of strings was passed). If reduce/ndims/align/normalize are supplied, the analyzed data is returned directly.

Examples

>>> import hypertools
>>> hypertools.load('iris').columns.tolist()
['sepal length (cm)', 'sepal width (cm)', 'petal length (cm)',
 'petal width (cm)', 'target']
>>> hypertools.load('penguins').columns.tolist()
['species', 'island', 'bill_length_mm', 'bill_depth_mm',
 'flipper_length_mm', 'body_mass_g', 'sex']
>>> hypertools.load('fivethirtyeight/bechdel').shape  # 538's bechdel data
(1794, 15)
>>> hypertools.load('kaggle/uciml/iris').shape  # a Kaggle dataset
(150, 6)
>>> weights = hypertools.load('weights')  # built-in name always wins
>>> type(weights).__name__, len(weights)
('list', 36)
>>> walk = hypertools.load('random_walk', n_samples=40, n_features=5,
...                        random_state=0)  # a synthetic dataset
>>> walk.shape
(40, 5)
>>> hypertools.load('blobs', n_samples=30, centers=3,
...                 random_state=1).columns.tolist()
['dim_0', 'dim_1', 'target']

A list of strings resolves element-wise and returns a list of datasets that can be passed to any hypertools function.

Warning

Pickled payloads (.pkl/.geo) can execute arbitrary code when loaded – only load pickled data from sources you trust.