Plotting streaming data¶
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.')
HyperTools treats data streams as just another supported data type: pass any Python iterator/generator, or a Hugging Face streaming dataset (hyp.load('<owner>/<dataset>', streaming=True)), directly to hyp.plot – no special flag needed.
How it works (see issue #101):
the first
stream_initsamples (default 10,000) are used to estimate the normalization and dimensionality-reduction parameters;those fitted models are then applied to every subsequent sample, which is added to the plot dynamically as it arrives;
streaming continues until the stream is exhausted,
stream_maxsamples have been consumed, or you interrupt with Ctrl-C. Infinite streams render continually – and if you’re saving an animation withsave_path, the file is finalized whenever streaming stops (including on interrupt).
Because new samples are projected with models fitted on the head of the stream, the reduction model must support transform() (e.g. the default IncrementalPCA, or PCA/UMAP – but not TSNE).
[1]:
import numpy as np
import hypertools as hyp
%matplotlib inline
Streaming from a generator¶
Here’s a simulated live data feed: a Lorenz attractor unfolding in a 10-dimensional embedding, written as an infinite generator. hyp.plot detects that it’s a stream, fits IncrementalPCA on the first 500 samples, then projects each new chunk of 100 samples through that fitted model and adds it to the plot. stream_max cuts the (infinite) stream off so the animation can be saved.
[2]:
def live_feed(dt=0.01, dim=10, seed=42):
"""An infinite stream: Lorenz dynamics embedded in `dim` dimensions."""
rng = np.random.default_rng(seed)
W = rng.standard_normal((3, dim))
xyz = np.array([1., 1., 1.])
while True:
x, y, z = xyz
xyz = xyz + dt * np.array([10 * (y - x),
x * (28 - z) - y,
x * y - 8 / 3 * z])
yield xyz @ W + 0.05 * rng.standard_normal(dim)
fig = hyp.plot(live_feed(), stream_init=500, stream_chunk=100,
stream_max=3000, save_path='streaming_data.mp4', frame_rate=5,
show=False)
print('samples:', fig.stream_info['n_samples'], ' projected shape:', fig.stream_info['xform_data'][0].shape)
# Colab serves output frames separately from kernel files; embed movie bytes.
try:
from google import colab as colab
except ImportError:
pass # Local Jupyter/Sphinx uses the relative video below.
else:
from IPython.display import Video, display
display(Video('streaming_data.mp4', embed=True))
samples: 3000 projected shape: (3000, 3)
Each animation frame corresponds to one fetched chunk, so stream_chunk sets both the download batch size and the temporal resolution of the saved animation; frame_rate sets how fast those frames play back (5 per second here, so the 26 chunks make a five-second clip).
The returned figure retains everything that was consumed via fig.stream_info: fig.stream_info['data'] holds the raw samples, fig.stream_info['xform_data'] the projected trajectory, and fig.stream_info['n_samples'] / ['reduce_model'] / ['truncated'] record the number of samples seen, the fitted reduction model, and whether the stream was cut off (truncated=True means streaming stopped – via stream_max, an interrupt, or an error – before the stream was observed to
end; it is True even when the stream held exactly stream_max samples).
[3]:
{k: (type(v).__name__ if k == 'reduce_model' else
(v[0].shape if k in ('data', 'xform_data') else v))
for k, v in fig.stream_info.items()}
[3]:
{'data': (3000, 10),
'xform_data': (3000, 3),
'n_samples': 3000,
'reduce_model': 'IncrementalPCA',
'truncated': True,
'error': None}
Comet-style display with stream_window¶
For long (or infinite) streams the accumulated trajectory can get dense. Passing stream_window displays only the most recent samples – older points scroll off comet-style – while everything consumed is still retained on the returned figure’s stream_info.
[4]:
fig = hyp.plot(live_feed(seed=7), stream_init=500, stream_chunk=100,
stream_max=3000, stream_window=750,
save_path='streaming_data_window.mp4', frame_rate=5, show=False)
print('points on screen:', len(fig.axes[0].lines[0].get_data_3d()[0]),
' samples retained:', fig.stream_info['xform_data'][0].shape[0])
# Colab serves output frames separately from kernel files; embed movie bytes.
try:
from google import colab as colab
except ImportError:
pass # Local Jupyter/Sphinx uses the relative video below.
else:
from IPython.display import Video, display
display(Video('streaming_data_window.mp4', embed=True))
points on screen: 750 samples retained: 3000
Streaming a Hugging Face dataset¶
Any datasets.IterableDataset streams straight into hyp.plot without downloading the full dataset first. hyp.load('<owner>/<dataset>', split=..., streaming=True) returns exactly that object (a non-streaming load would return a DataFrame instead). Rows arrive as dicts; numeric fields are extracted (in order) and concatenated into one vector per sample, and non-numeric fields are ignored – use .select_columns(...) to control exactly which features are used.
The projection is fitted on the first stream_init samples, so those should be representative of what follows. The iris file lists the three species in blocks, which would fit the model on setosa alone and leave every later flower outside the fitted display box (hypertools warns when that happens); shuffling the stream with a fixed seed mixes the species before the head of the stream is consumed.
[5]:
ds = hyp.load('scikit-learn/iris', split='train', streaming=True)
ds = ds.select_columns(['SepalLengthCm', 'SepalWidthCm',
'PetalLengthCm', 'PetalWidthCm'])
ds = ds.shuffle(seed=0, buffer_size=150) # the file lists the species in blocks
fig = hyp.plot(ds, '.', markersize=6, stream_init=50, stream_chunk=25)
fig.stream_info['n_samples'], fig.stream_info['data'][0].shape
[5]:
(150, (150, 4))
The four numeric iris measurements stream through the model fitted on the first 50 flowers and land in a 3-dimensional embedding, 50 → 150 samples, without the dataset ever being materialized locally.
A few practical notes:
with the default
stream_max=None, plotting an infinite stream runs until you interrupt it (Ctrl-C) – the plot keeps updating live, and anysave_pathanimation is finalized on interrupt;when
stream_maxis set, exactly that many samples are consumed and never one more – the stream is not peeked past the limit, so costly or stateful sources (paid APIs, hardware acquisition) are never read beyond it;alignandclusteraren’t yet supported for streams (a stream is a single dataset, and clustering streams is planned for a future release);everything consumed is kept in memory on the returned figure’s
stream_info, so very long-running streams should budget accordingly.