torchtsetlin.data¶
Encoders, splits and wrappers for your own data. The datasets themselves are in
torchtsetlin.datasets.
Encoders¶
torchtsetlin.data.encoders ¶
Booleanization: turning continuous, categorical and image data into Boolean features.
All encoders are torch.nn.Module objects so they can be moved to a device, saved in a
state_dict and composed with :class:torchtsetlin.data.Compose. They follow the
scikit-learn fit / transform protocol on top of forward (transform is an
alias of forward; fit_transform chains both).
BooleanEncoder ¶
Bases: Module
Base class for encoders. Subclasses implement :meth:forward (and optionally
:meth:fit). transform is an alias of forward.
Binarizer ¶
Bases: BooleanEncoder
x > threshold (or >=) per element. threshold may be a scalar or a tensor
broadcastable to the input (e.g. one threshold per feature).
Source code in src/torchtsetlin/data/encoders.py
ThermometerEncoder ¶
ThermometerEncoder(n_bits: int = 8, strategy: str = 'quantile', thresholds: Optional[Tensor] = None, value_range: Optional[Sequence[float]] = None, flatten: bool = True)
Bases: BooleanEncoder
Thermometer (ordinal) encoding of continuous features.
Each feature v becomes n_bits Booleans [v >= t_1, ..., v >= t_n] for
increasing thresholds t_k. Clauses can then express ranges with two literals
(x>=t_a AND NOT x>=t_b). Thresholds are learned by :meth:fit (quantiles by default)
or given explicitly.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_bits
|
int
|
thresholds per feature. |
8
|
strategy
|
str
|
threshold strategy (see :func: |
'quantile'
|
thresholds
|
Optional[Tensor]
|
explicit |
None
|
value_range
|
Optional[Sequence[float]]
|
|
None
|
flatten
|
bool
|
return |
True
|
Source code in src/torchtsetlin/data/encoders.py
feature_names ¶
Names of the Boolean outputs, e.g. "age>=30.0".
Source code in src/torchtsetlin/data/encoders.py
decode_range ¶
Range (lo, hi) implied by included positive/negated bits of one feature.
Source code in src/torchtsetlin/data/encoders.py
OneHotEncoder ¶
Bases: BooleanEncoder
One Boolean per category value per column. Categories are integers (fit records the
number of categories per column, or pass n_categories).
Source code in src/torchtsetlin/data/encoders.py
QuantileOneHotEncoder ¶
QuantileOneHotEncoder(n_bins: int = 10, categorical: Optional[Union[Sequence[bool], Sequence[int], Tensor]] = None, n_categories: Optional[Sequence[int]] = None)
Bases: BooleanEncoder
Equal-frequency bins, one-hot encoded: each numeric column becomes one Boolean per bin (exactly one is true), each categorical column one Boolean per category.
The bins are those of scikit-learn's KBinsDiscretizer(n_bins, strategy="quantile")
with linear quantiles: :meth:fit computes the edges at the training quantiles
k / n_bins (k = 0..n_bins), drops edges closer than 1e-8 to the previous one
(so a column with few distinct values gets fewer bins), and a value v falls into bin
#{inner edges <= v}. Values outside the training range go to the first or last bin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_bins
|
int
|
bins per numeric column. |
10
|
categorical
|
Optional[Union[Sequence[bool], Sequence[int], Tensor]]
|
Boolean mask (or column indices) of the columns that hold integer category codes; they are one-hot encoded without binning. |
None
|
n_categories
|
Optional[Sequence[int]]
|
categories per categorical column (in column order); by default
|
None
|
Input: (N, F) floats (categorical columns as codes, no NaN).
Output: (N, sum of bins per column) Boolean.
Source code in src/torchtsetlin/data/encoders.py
bins ¶
Bin (or category) index of every value, (N, F) long.
Source code in src/torchtsetlin/data/encoders.py
feature_groups ¶
Input column of every output bit, (output_size,) long.
feature_names ¶
feature_names(names: Sequence[str], categories: Optional[Sequence[Optional[Sequence[str]]]] = None) -> List[str]
Names of the Boolean outputs: "age in [30, 41)" for bins, "day=Mon" for
categories (categories[j] names the codes of column j).
Source code in src/torchtsetlin/data/encoders.py
BitPlaneEncoder ¶
Bases: BooleanEncoder
Plain binary (place-value) encoding of non-negative integers with n_bits bits,
most significant bit first.
Values must lie in [0, 2**n_bits): higher bits are dropped. Float inputs are rounded.
A tensor is encoded on its own device; arrays and lists on the CPU.
- 2-D input
(N, F)is tabular and becomes(N, F*n_bits)(channel_dimis ignored). - Input with 3 or more dimensions has its
n_bitsplanes stacked into the channel dimensionchannel_dim, channel by channel:(N, C, H, W)becomes(N, C*n_bits, H, W)with the defaultchannel_dim=1, and channel-last(N, H, W, C)becomes(N, H, W, C*n_bits)withchannel_dim=-1. A 3-D input is read as(N, C, L); add a channel axis to a greyscale batch(N, H, W)first.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_bits
|
int
|
Number of bit planes per value. |
8
|
channel_dim
|
int
|
Dimension holding the channels (negative values count from the end). It may not be the batch dimension 0. |
1
|
Source code in src/torchtsetlin/data/encoders.py
AdaptiveThresholdEncoder ¶
Bases: BooleanEncoder
Adaptive (local) thresholding for grayscale / multi-channel images, as used to booleanize MNIST/CIFAR for convolutional Tsetlin machines.
bit = pixel > local_mean(pixel) - C where the local mean is computed over a
block_size x block_size window, either uniformly (method="mean") or with a
Gaussian kernel (method="gaussian", OpenCV ADAPTIVE_THRESH_GAUSSIAN_C).
Input (N, C, H, W) (or (N, H, W)) -> Boolean of the same shape.
Source code in src/torchtsetlin/data/encoders.py
ColorThermometerEncoder ¶
Bases: BooleanEncoder
Per-channel thermometer encoding of images: each pixel channel becomes n_bits
planes [v >= k * 255/(n_bits+1)]. (N, C, H, W) -> (N, C*n_bits, H, W).
value_range defaults to (0, 255); use (0, 1) for float images.
Source code in src/torchtsetlin/data/encoders.py
HypervectorEncoder ¶
HypervectorEncoder(vocab_size: int, dim: int = 1024, n_bits: int = 8, bind_position: bool = False, seed: int = 0)
Bases: BooleanEncoder
Sparse binary hypervector encoding of discrete tokens (Halenka et al., 2024).
Every token id t < vocab_size owns a fixed random hypervector with n_bits ones
among dim positions. A sample (a set / sequence of token ids) is bundled with
bitwise OR. Optionally each position p is bound by cyclically shifting the token's
hypervector by p (bind_position=True), so word order is preserved.
Input: (N, L) long tensor of token ids (padding id -1 is ignored).
Output: (N, dim) Boolean.
Source code in src/torchtsetlin/data/encoders.py
PyramidEncoder ¶
Bases: BooleanEncoder
Stack each pixel's neighbourhood at several resolutions into extra Boolean planes.
A k x k patch is all a dense Tsetlin machine sees of a pixel, and some classes simply
are not decidable from it — a patch of building interior and a patch of road look alike
once illumination varies; telling them apart needs to know where the horizon is. This is
the gap an encoder-decoder closes in a CNN, and it can be closed natively here: OR-pool
the Boolean planes to build a pyramid, take the same k x k patch at each level, and
resample every level back to full resolution. A clause then reads a pixel's immediate
neighbourhood and the coarse structure around it, with no float parameter and no
gradient anywhere.
Feed the result to a model with patch_size=1: the neighbourhood is already in the
planes, and asking for a second one on top multiplies the feature count for nothing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scales
|
Sequence[int]
|
downsampling factors, ascending. |
(1, 2, 4)
|
patch
|
int
|
neighbourhood side length taken at each level. An odd patch is centred on the
pixel; an even one is padded like PyTorch's |
3
|
mode
|
str
|
pooling mode for the pyramid (see :func: |
'or'
|
Shape
- input:
(B, Z, H, W)Boolean. - output:
(B, Z * patch * patch * len(scales), H, W)Boolean.
Example
enc = PyramidEncoder(scales=(1, 2, 4), patch=3) planes = enc(x) # (B, Z93, H, W) model = SegmentationTsetlinMachine(4, 300, T=60, patch_size=1)
Source code in src/torchtsetlin/data/encoders.py
Flatten ¶
Compose ¶
Bases: BooleanEncoder
Chain encoders / callables. fit fits each stage on the output of the previous.
Source code in src/torchtsetlin/data/encoders.py
thermometer_thresholds ¶
thermometer_thresholds(x: Tensor, n_bits: int, strategy: str = 'quantile', value_range: Optional[Sequence[float]] = None) -> Tensor
Per-feature thresholds (F, n_bits) for thermometer encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
Tensor
|
|
required |
n_bits
|
int
|
thresholds per feature. |
required |
strategy
|
str
|
|
'quantile'
|
value_range
|
Optional[Sequence[float]]
|
optional global |
None
|
Source code in src/torchtsetlin/data/encoders.py
Splits and class balance¶
torchtsetlin.data.splits ¶
Train/test splitting and class balancing.
stratified_split ¶
Seeded stratified train/test split: round(test_size * n_c) samples of every class
c go to the test split. Returns sorted (train_idx, test_idx).
Source code in src/torchtsetlin/data/splits.py
random_oversample ¶
Random oversampling (imbalanced-learn's RandomOverSampler): every class of
y[idx] is topped up with samples drawn with replacement until it is as large as
the largest class. Returns the original indices followed by the drawn ones.
Source code in src/torchtsetlin/data/splits.py
Dataset wrappers¶
torchtsetlin.data.datasets ¶
Helpers to wrap your own data as Boolean datasets.
The ready-made datasets (generators, loaders, downloadable benchmarks) live in
:mod:torchtsetlin.datasets; their names are re-exported here for backward compatibility.
BooleanTensorDataset ¶
Bases: TensorDataset
TensorDataset that coerces features to torch.bool and targets to long
(or float for regression). Keeps everything on one device for fast GPU epochs.
Source code in src/torchtsetlin/data/datasets.py
TransformDataset ¶
TransformDataset(base: Dataset, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None)
Bases: Dataset
Apply a (booleanizing) transform lazily to the samples of another dataset.
Source code in src/torchtsetlin/data/datasets.py
to_boolean_tensors ¶
Coerce x to a Boolean tensor and y to a long tensor on device.
Source code in src/torchtsetlin/data/datasets.py
balanced_class_probabilities ¶
balanced_class_probabilities(labels: Tensor, n_classes: Optional[int] = None, ignore_index: Optional[int] = None, floor: float = 0.0) -> Tensor
Per-class feedback probabilities that equalise how often each class is learned from.
Dense targets are dominated by whichever class covers the most pixels, and a Tsetlin
machine has no loss to reweight — the only lever is which pixels produce feedback.
This returns p_k = min_j freq_j / freq_k (so the rarest class keeps probability 1),
ready to pass as class_feedback_p to
:class:~torchtsetlin.models.SegmentationTsetlinMachine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Tensor
|
any tensor of integer labels (a label map or a flat vector). |
required |
n_classes
|
Optional[int]
|
number of classes (inferred from the maximum label if omitted). |
None
|
ignore_index
|
Optional[int]
|
label to exclude from the frequency count. |
None
|
floor
|
float
|
lower bound on the returned probabilities; raising it (e.g. |
0.0
|
Source code in src/torchtsetlin/data/datasets.py
Graphs¶
torchtsetlin.data.graphs ¶
Graph-structured input for :class:~torchtsetlin.models.GraphTsetlinMachine.
A :class:GraphBatch holds a batch of directed multigraphs whose nodes carry Boolean feature
vectors and whose edges carry an integer type. Node features are usually sparse
hypervectors of symbols, built by a :class:SymbolTable (Halenka et al., 2024; Granmo et al.,
2025, arXiv:2507.14874), but any Boolean vector works: an image patch with its position bits
is a node, so a graph without edges is the input of a convolutional Tsetlin machine.
Storage is padded: features (B, P, F) with P the largest node count of the batch and a
(B, P) node mask. Edges are kept per graph, sorted by graph, with local node indices,
so that slicing a batch (batch[idx]) is cheap and keeps every edge inside its graph.
:meth:GraphBatch.pad gives the fixed-shape layout: a fixed node count P and edges as a
(B, E, 2) array with an edge mask. Slicing it never looks at the data (no host
synchronisation, and the shape of a slice depends only on how many graphs it holds), which is
what the CUDA fast paths of :class:~torchtsetlin.models.GraphTsetlinMachine need.
SymbolTable ¶
SymbolTable(symbols: Iterable, dim: int = 128, bits: int = 2, encoding: str = 'random', seed: int = 0)
Map symbol names to sparse hypervector positions (the node properties of a graph).
Every symbol owns bits positions out of dim. A node's feature vector is the OR
(bundle) of its symbols' positions. The three encodings follow the reference
GraphTsetlinMachine (Graphs in graphs.py):
"random":bitsdistinct random positions per symbol (seeded);"double_hashing": positionsi mod dimandp - (i mod p)withpthe largest prime belowdim(always 2 bits);"one_hot":dim = len(symbols)and symboliowns positioni. This is a plain Boolean feature per symbol, and it makes decoding exact.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
Iterable
|
the symbol names (any hashable values). |
required |
dim
|
int
|
hypervector size (ignored for |
128
|
bits
|
int
|
positions per symbol (ignored for |
2
|
encoding
|
str
|
|
'random'
|
seed
|
int
|
seed of the random positions. |
0
|
Source code in src/torchtsetlin/data/graphs.py
vector ¶
(dim,) Boolean hypervector of a set of symbols (their bundle).
Source code in src/torchtsetlin/data/graphs.py
encode ¶
(n, dim) Boolean feature matrix, one row per node's symbol set.
Source code in src/torchtsetlin/data/graphs.py
decode ¶
Symbols whose positions are all set in vector ((dim,) Boolean).
Source code in src/torchtsetlin/data/graphs.py
feature_names ¶
Names of the dim positions: the symbol for one-hot tables, else hv[k].
Source code in src/torchtsetlin/data/graphs.py
GraphBatch ¶
GraphBatch(node_features: Tensor, n_nodes: Tensor, edges: Optional[Tensor] = None, edge_type: Optional[Tensor] = None, edges_per_graph: Optional[Tensor] = None, node_type: Optional[Tensor] = None, n_edge_types: Optional[int] = None, n_node_types: Optional[int] = None, edge_type_names: Optional[Sequence[str]] = None)
A padded batch of directed multigraphs with typed edges.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_features
|
Tensor
|
|
required |
n_nodes
|
Tensor
|
|
required |
edges
|
Optional[Tensor]
|
|
None
|
edge_type
|
Optional[Tensor]
|
|
None
|
edges_per_graph
|
Optional[Tensor]
|
|
None
|
node_type
|
Optional[Tensor]
|
optional |
None
|
n_edge_types
|
Optional[int]
|
number of edge types of the dataset (kept by slices, so a batch that
happens to lack a type still declares it). Defaults to |
None
|
n_node_types
|
Optional[int]
|
number of node types of the dataset. Defaults to |
None
|
edge_type_names
|
Optional[Sequence[str]]
|
optional names of the edge types, for printing clauses. |
None
|
Messages travel along an edge from its source to its destination, so a node learns about the nodes that have an edge into it. Undirected relations need an edge each way, usually with two types (as in the sequence demo: "left" and "right").
Build batches with :meth:from_graphs, :meth:from_sequences or :meth:from_images;
index them like tensors along the graph axis (batch[3], batch[2:10],
batch[torch.tensor([4, 1])]) and concatenate them with :meth:cat.
Source code in src/torchtsetlin/data/graphs.py
edge_slots
property
¶
Stored edges: E (flat layout) or B * max_edges (padded layout). No sync.
edges
property
¶
(E, 2) local (source, destination) pairs, grouped by graph (for a padded
batch, derived from the padded layout).
pad ¶
The fixed-shape layout: nodes padded to max_nodes, edges stored as a
(B, max_edges, 2) array with an edge mask (defaults: this batch's maxima).
Slicing a padded batch keeps max_nodes and max_edges and never inspects the
data, so it is free of host synchronisation and its shape depends only on the number
of graphs. That is what lets :class:~torchtsetlin.models.GraphTsetlinMachine use the
CUDA fast paths (events mode, fused sequential commits, CUDA graphs). Pad a whole
dataset to one size: every distinct (max_nodes, max_edges) is compiled and captured
separately. Results are the same as with the flat layout.
Source code in src/torchtsetlin/data/graphs.py
unpad ¶
The flat layout (trimmed to the largest graph); a flat batch is returned as is.
Source code in src/torchtsetlin/data/graphs.py
copy_ ¶
Copy a padded batch of the same shape into this one, in place (CUDA-graph inputs).
Source code in src/torchtsetlin/data/graphs.py
clone ¶
A copy with its own storage (same layout).
Source code in src/torchtsetlin/data/graphs.py
cat
staticmethod
¶
Concatenate batches along the graph axis (padding to the largest node count).
Padded batches give a padded batch (to the largest max_nodes and max_edges).
Source code in src/torchtsetlin/data/graphs.py
flat_edges ¶
(src, dst, type) with node indices into the flattened B * P node axis. For a
padded batch these include the unused edge slots; :meth:flat_edge_mask tells them
apart.
Source code in src/torchtsetlin/data/graphs.py
flat_edge_mask ¶
(B * max_edges,) Boolean mask of the real edges of a padded batch (in the order
of :meth:flat_edges), None for the flat layout, where every edge is real.
Source code in src/torchtsetlin/data/graphs.py
from_graphs
classmethod
¶
from_graphs(node_features: Sequence, edges: Optional[Sequence] = None, edge_types: Optional[Sequence] = None, node_types: Optional[Sequence] = None, n_edge_types: Optional[int] = None, n_node_types: Optional[int] = None, edge_type_names: Optional[Sequence[str]] = None) -> GraphBatch
Build a batch from per-graph lists.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node_features
|
Sequence
|
per graph, an |
required |
edges
|
Optional[Sequence]
|
per graph, an |
None
|
edge_types
|
Optional[Sequence]
|
per graph, an |
None
|
node_types
|
Optional[Sequence]
|
per graph, an |
None
|
Source code in src/torchtsetlin/data/graphs.py
from_sequences
classmethod
¶
from_sequences(sequences: Sequence[Sequence], symbols: SymbolTable, edge_types: Tuple[str, str] = ('left', 'right'), unknown: str = 'ignore') -> GraphBatch
One node per sequence element, chained in both directions.
Node k sends to k - 1 over edge type 0 (named edge_types[0]) and to
k + 1 over type 1, as in the reference SequenceClassificationDemo. An element
may be a single symbol or a set of symbols. Symbols missing from the table are
ignored (unknown="ignore") or rejected ("error").
Source code in src/torchtsetlin/data/graphs.py
from_images
classmethod
¶
from_images(images: Any, patch_size: Union[int, Tuple[int, int]], stride: Union[int, Tuple[int, int]] = 1, position_encoding: bool = True) -> GraphBatch
One node per image patch and no edges (paper Sec. 3.2, "disconnected nodes").
Node features are the Z * kh * kw patch pixels followed by thermometer-coded
patch coordinates, exactly the patch features of
:class:~torchtsetlin.models.ConvTsetlinMachine with the same arguments. A depth-1
graph machine on these graphs is therefore the convolutional coalesced machine.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Any
|
Boolean |
required |