Skip to content

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.

fit

fit(x, y=None) -> BooleanEncoder

Fit encoder statistics (no-op for stateless encoders).

Source code in src/torchtsetlin/data/encoders.py
def fit(self, x, y=None) -> BooleanEncoder:  # noqa: D401
    """Fit encoder statistics (no-op for stateless encoders)."""
    return self

Binarizer

Binarizer(threshold: Union[float, Tensor] = 0.5, inclusive: bool = False)

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
def __init__(self, threshold: Union[float, Tensor] = 0.5, inclusive: bool = False) -> None:
    super().__init__()
    self.register_buffer("threshold", torch.as_tensor(threshold, dtype=torch.float32))
    self.inclusive = bool(inclusive)

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:thermometer_thresholds).

'quantile'
thresholds Optional[Tensor]

explicit (F, n_bits) thresholds (skips fitting).

None
value_range Optional[Sequence[float]]

(lo, hi) for the uniform strategy (e.g. (0, 255) for images).

None
flatten bool

return (N, F*n_bits) instead of (N, F, n_bits).

True
Source code in src/torchtsetlin/data/encoders.py
def __init__(
    self,
    n_bits: int = 8,
    strategy: str = "quantile",
    thresholds: Optional[Tensor] = None,
    value_range: Optional[Sequence[float]] = None,
    flatten: bool = True,
) -> None:
    super().__init__()
    self.n_bits = int(n_bits)
    self.strategy = strategy
    self.value_range = tuple(value_range) if value_range is not None else None
    self.flatten = bool(flatten)
    if thresholds is not None:
        self.register_buffer("thresholds", torch.as_tensor(thresholds, dtype=torch.float32))
    else:
        self.register_buffer("thresholds", torch.empty(0))

feature_names

feature_names(names: Sequence[str]) -> List[str]

Names of the Boolean outputs, e.g. "age>=30.0".

Source code in src/torchtsetlin/data/encoders.py
def feature_names(self, names: Sequence[str]) -> List[str]:
    """Names of the Boolean outputs, e.g. ``"age>=30.0"``."""
    thr = self.thresholds
    if thr.shape[0] == 1:
        thr = thr.expand(len(names), -1)
    return [f"{n}>={float(thr[i, k]):.4g}" for i, n in enumerate(names) for k in range(self.n_bits)]

decode_range

decode_range(feature: int, included_pos: Iterable[int], included_neg: Iterable[int])

Range (lo, hi) implied by included positive/negated bits of one feature.

Source code in src/torchtsetlin/data/encoders.py
def decode_range(self, feature: int, included_pos: Iterable[int], included_neg: Iterable[int]):
    """Range ``(lo, hi)`` implied by included positive/negated bits of one feature."""
    thr = self.thresholds[feature if self.thresholds.shape[0] > 1 else 0]
    lo = max((float(thr[k]) for k in included_pos), default=-float("inf"))
    hi = min((float(thr[k]) for k in included_neg), default=float("inf"))
    return lo, hi

OneHotEncoder

OneHotEncoder(n_categories: Optional[Sequence[int]] = None)

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
def __init__(self, n_categories: Optional[Sequence[int]] = None) -> None:
    super().__init__()
    self.register_buffer(
        "n_categories",
        torch.as_tensor(list(n_categories), dtype=torch.long) if n_categories else torch.empty(0, dtype=torch.long),
    )

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 max + 1 of the training codes.

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
def __init__(
    self,
    n_bins: int = 10,
    categorical: Optional[Union[Sequence[bool], Sequence[int], Tensor]] = None,
    n_categories: Optional[Sequence[int]] = None,
) -> None:
    super().__init__()
    if n_bins < 2:
        raise ValueError("n_bins must be at least 2")
    self.n_bins = int(n_bins)
    self._categorical_arg = categorical
    self._n_categories_arg = list(n_categories) if n_categories is not None else None
    self.register_buffer("edges", torch.empty(0, self.n_bins - 1))
    self.register_buffer("n_out", torch.empty(0, dtype=torch.long))
    self.register_buffer("categorical", torch.empty(0, dtype=torch.bool))

bins

bins(x) -> Tensor

Bin (or category) index of every value, (N, F) long.

Source code in src/torchtsetlin/data/encoders.py
def bins(self, x) -> Tensor:
    """Bin (or category) index of every value, ``(N, F)`` long."""
    if not self.is_fitted:
        raise RuntimeError("QuantileOneHotEncoder must be fitted first (call .fit(x)).")
    x = self._as_float(x)
    b = (x.unsqueeze(2) >= self.edges.unsqueeze(0)).sum(dim=2)
    codes = x.round().long().clamp(min=0)
    codes = torch.minimum(codes, (self.n_out - 1).unsqueeze(0))
    return torch.where(self.categorical.unsqueeze(0), codes, b)

feature_groups

feature_groups() -> Tensor

Input column of every output bit, (output_size,) long.

Source code in src/torchtsetlin/data/encoders.py
def feature_groups(self) -> Tensor:
    """Input column of every output bit, ``(output_size,)`` long."""
    return torch.repeat_interleave(torch.arange(self.n_out.numel(), device=self.n_out.device), self.n_out)

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
def feature_names(self, 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``)."""
    out = []
    for j, name in enumerate(names):
        k = int(self.n_out[j])
        if bool(self.categorical[j]):
            labels = categories[j] if categories is not None and categories[j] is not None else None
            out.extend(f"{name}={labels[c] if labels is not None else c}" for c in range(k))
            continue
        e = [float(v) for v in self.edges[j, : k - 1]]
        bounds = [-float("inf")] + e + [float("inf")]
        out.extend(f"{name} in [{bounds[c]:.4g}, {bounds[c + 1]:.4g})" for c in range(k))
    return out

BitPlaneEncoder

BitPlaneEncoder(n_bits: int = 8, channel_dim: int = 1)

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_dim is ignored).
  • Input with 3 or more dimensions has its n_bits planes stacked into the channel dimension channel_dim, channel by channel: (N, C, H, W) becomes (N, C*n_bits, H, W) with the default channel_dim=1, and channel-last (N, H, W, C) becomes (N, H, W, C*n_bits) with channel_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
def __init__(self, n_bits: int = 8, channel_dim: int = 1) -> None:
    super().__init__()
    self.n_bits = int(n_bits)
    self.channel_dim = int(channel_dim)

AdaptiveThresholdEncoder

AdaptiveThresholdEncoder(block_size: int = 11, C: float = 2.0, method: str = 'gaussian')

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
def __init__(self, block_size: int = 11, C: float = 2.0, method: str = "gaussian") -> None:
    super().__init__()
    if block_size % 2 == 0 or block_size < 3:
        raise ValueError("block_size must be odd and >= 3")
    if method not in ("gaussian", "mean"):
        raise ValueError("method must be 'gaussian' or 'mean'")
    self.block_size = int(block_size)
    self.C = float(C)
    self.method = method
    if method == "gaussian":
        sigma = 0.3 * ((block_size - 1) * 0.5 - 1) + 0.8  # OpenCV's default sigma
        ax = torch.arange(block_size, dtype=torch.float32) - (block_size - 1) / 2
        g1 = torch.exp(-(ax**2) / (2 * sigma**2))
        g1 = g1 / g1.sum()
        kernel = torch.outer(g1, g1)
    else:
        kernel = torch.full((block_size, block_size), 1.0 / block_size**2)
    self.register_buffer("kernel", kernel.view(1, 1, block_size, block_size))

ColorThermometerEncoder

ColorThermometerEncoder(n_bits: int = 8, value_range: Sequence[float] = (0.0, 255.0))

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
def __init__(self, n_bits: int = 8, value_range: Sequence[float] = (0.0, 255.0)) -> None:
    super().__init__()
    lo, hi = float(value_range[0]), float(value_range[1])
    steps = torch.arange(1, n_bits + 1, dtype=torch.float32) / (n_bits + 1)
    self.register_buffer("thresholds", lo + (hi - lo) * steps)
    self.n_bits = int(n_bits)

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
def __init__(self, vocab_size: int, dim: int = 1024, n_bits: int = 8, bind_position: bool = False, seed: int = 0) -> None:
    super().__init__()
    g = torch.Generator().manual_seed(seed)
    table = torch.zeros(vocab_size, dim, dtype=torch.bool)
    for t in range(vocab_size):
        idx = torch.randperm(dim, generator=g)[:n_bits]
        table[t, idx] = True
    self.register_buffer("table", table)
    self.dim = int(dim)
    self.bind_position = bool(bind_position)

PyramidEncoder

PyramidEncoder(scales: Sequence[int] = (1, 2, 4), patch: int = 3, mode: str = 'or')

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 is the full-resolution level.

(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 padding="same", so the pixel sits at offset (patch - 1) // 2 of its window (one more neighbour after it than before).

3
mode str

pooling mode for the pyramid (see :func:torchtsetlin.functional.boolean_pool).

'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
def __init__(self, scales: Sequence[int] = (1, 2, 4), patch: int = 3, mode: str = "or") -> None:
    super().__init__()
    self.scales = tuple(int(s) for s in scales)
    self.patch = int(patch)
    self.mode = str(mode)
    if min(self.scales) < 1 or self.patch < 1:
        raise ValueError("scales and patch must be >= 1")

Flatten

Bases: BooleanEncoder

Flatten everything but the batch dimension.

Compose

Compose(*stages)

Bases: BooleanEncoder

Chain encoders / callables. fit fits each stage on the output of the previous.

Source code in src/torchtsetlin/data/encoders.py
def __init__(self, *stages) -> None:
    super().__init__()
    self.stages = nn.ModuleList([s for s in stages if isinstance(s, nn.Module)])
    self._all = list(stages)

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

(N, F) training data (only needed for "quantile"/"unique" or when value_range is None).

required
n_bits int

thresholds per feature.

required
strategy str

"quantile" (equal-frequency), "uniform" (equal-width) or "unique" (evenly spaced ranks of the unique training values).

'quantile'
value_range Optional[Sequence[float]]

optional global (lo, hi) for the uniform strategy.

None
Source code in src/torchtsetlin/data/encoders.py
def 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.

    Args:
        x: ``(N, F)`` training data (only needed for ``"quantile"``/``"unique"`` or when
            ``value_range`` is ``None``).
        n_bits: thresholds per feature.
        strategy: ``"quantile"`` (equal-frequency), ``"uniform"`` (equal-width) or
            ``"unique"`` (evenly spaced ranks of the unique training values).
        value_range: optional global ``(lo, hi)`` for the uniform strategy.
    """
    x = x.to(torch.float32)
    Fn = x.shape[1]
    if strategy == "uniform":
        if value_range is not None:
            lo = torch.full((Fn,), float(value_range[0]), device=x.device)
            hi = torch.full((Fn,), float(value_range[1]), device=x.device)
        else:
            lo, hi = x.min(dim=0).values, x.max(dim=0).values
        steps = torch.arange(1, n_bits + 1, device=x.device, dtype=torch.float32) / (n_bits + 1)
        return lo.unsqueeze(1) + (hi - lo).unsqueeze(1) * steps.unsqueeze(0)
    if strategy == "quantile":
        q = torch.arange(1, n_bits + 1, device=x.device, dtype=torch.float32) / (n_bits + 1)
        return torch.quantile(x, q, dim=0).transpose(0, 1).contiguous()
    if strategy == "unique":
        out = torch.empty(Fn, n_bits, device=x.device)
        for f in range(Fn):
            u = torch.unique(x[:, f])
            if u.numel() > 1:
                u = u[1:]  # ``x >= min`` is always True — drop it
            if u.numel() >= n_bits:
                idx = torch.linspace(0, u.numel() - 1, n_bits, device=x.device).round().long()
                out[f] = u[idx]
            else:  # pad by repeating the max (bits that are never on for training data)
                pad = u.max().repeat(n_bits - u.numel()) if u.numel() else torch.zeros(n_bits)
                out[f] = torch.cat([u, pad.to(u.device)])
        return out
    raise ValueError("strategy must be 'quantile', 'uniform' or 'unique'")

Splits and class balance

torchtsetlin.data.splits

Train/test splitting and class balancing.

stratified_split

stratified_split(y: Tensor, test_size: float = 0.2, seed: int = 0) -> Tuple[Tensor, Tensor]

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
def stratified_split(y: Tensor, test_size: float = 0.2, seed: int = 0) -> Tuple[Tensor, Tensor]:
    """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)``."""
    if not 0.0 < test_size < 1.0:
        raise ValueError("test_size must be in (0, 1)")
    y = torch.as_tensor(y).long().cpu()
    g = torch.Generator().manual_seed(int(seed))
    train, test = [], []
    for c in torch.unique(y):
        idx = torch.nonzero(y == c).flatten()
        idx = idx[torch.randperm(idx.numel(), generator=g)]
        k = int(round(test_size * idx.numel()))
        test.append(idx[:k])
        train.append(idx[k:])
    return torch.sort(torch.cat(train)).values, torch.sort(torch.cat(test)).values

random_oversample

random_oversample(idx: Tensor, y: Tensor, seed: int = 0) -> Tensor

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
def random_oversample(idx: Tensor, y: Tensor, seed: int = 0) -> Tensor:
    """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."""
    y = torch.as_tensor(y).long().cpu()
    idx = torch.as_tensor(idx).long().cpu()
    g = torch.Generator().manual_seed(int(seed))
    yi = y[idx]
    classes, counts = torch.unique(yi, return_counts=True)
    extra = [idx]
    for c, n in zip(classes.tolist(), counts.tolist()):
        need = int(counts.max()) - n
        if need:
            pool = idx[yi == c]
            extra.append(pool[torch.randint(pool.numel(), (need,), generator=g)])
    return torch.cat(extra)

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

BooleanTensorDataset(x, y, device=None, regression: bool = False)

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
def __init__(self, x, y, device=None, regression: bool = False) -> None:
    xb = as_bool_tensor(x, device=torch.device(device) if device else None)
    if regression:
        yt = as_float_tensor(y, device=xb.device)
    else:
        yt = as_long_tensor(y, device=xb.device)
    super().__init__(xb, yt)

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
def __init__(self, base: Dataset, transform: Optional[Callable] = None, target_transform: Optional[Callable] = None):
    self.base = base
    self.transform = transform
    self.target_transform = target_transform

to_boolean_tensors

to_boolean_tensors(x, y=None, device=None) -> Tuple[Tensor, Optional[Tensor]]

Coerce x to a Boolean tensor and y to a long tensor on device.

Source code in src/torchtsetlin/data/datasets.py
def to_boolean_tensors(x, y=None, device=None) -> Tuple[Tensor, Optional[Tensor]]:
    """Coerce ``x`` to a Boolean tensor and ``y`` to a long tensor on ``device``."""
    dev = torch.device(device) if device else None
    xb = as_bool_tensor(x, device=dev)
    yb = as_long_tensor(y, device=dev) if y is not None else None
    return xb, yb

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.05) keeps a very frequent class from being starved of feedback altogether.

0.0
Source code in src/torchtsetlin/data/datasets.py
def 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`.

    Args:
        labels: any tensor of integer labels (a label map or a flat vector).
        n_classes: number of classes (inferred from the maximum label if omitted).
        ignore_index: label to exclude from the frequency count.
        floor: lower bound on the returned probabilities; raising it (e.g. ``0.05``) keeps a
            very frequent class from being starved of feedback altogether.
    """
    y = labels.reshape(-1).long()
    if ignore_index is not None:
        y = y[y != int(ignore_index)]
    K = int(n_classes) if n_classes is not None else (int(y.max()) + 1 if y.numel() else 1)
    counts = torch.bincount(y, minlength=K).to(torch.float64)[:K]
    present = counts[counts > 0]
    if present.numel() == 0:
        return torch.ones(K, dtype=torch.float32, device=labels.device)
    p = torch.where(counts > 0, present.min() / counts.clamp_min(1), torch.ones_like(counts))
    return p.clamp(min=float(floor), max=1.0).to(torch.float32).to(labels.device)

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": bits distinct random positions per symbol (seeded);
  • "double_hashing": positions i mod dim and p - (i mod p) with p the largest prime below dim (always 2 bits);
  • "one_hot": dim = len(symbols) and symbol i owns position i. 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 "one_hot").

128
bits int

positions per symbol (ignored for "double_hashing" and "one_hot").

2
encoding str

"random", "double_hashing" or "one_hot".

'random'
seed int

seed of the random positions.

0
Source code in src/torchtsetlin/data/graphs.py
def __init__(
    self,
    symbols: Iterable,
    dim: int = 128,
    bits: int = 2,
    encoding: str = "random",
    seed: int = 0,
) -> None:
    self.symbols = list(symbols)
    if len(set(self.symbols)) != len(self.symbols):
        raise ValueError("symbol names must be unique")
    self.index = {s: i for i, s in enumerate(self.symbols)}
    n = len(self.symbols)
    if encoding == "one_hot":
        dim, bits = n, 1
        pos = torch.arange(n).unsqueeze(1)
    elif encoding == "double_hashing":
        bits = 2
        p = _prev_prime(dim)
        i = torch.arange(n)
        pos = torch.stack([i % dim, p - (i % p)], dim=1)
    elif encoding == "random":
        if not 1 <= bits <= dim:
            raise ValueError("bits must lie in [1, dim]")
        g = torch.Generator().manual_seed(int(seed))
        pos = torch.stack([torch.randperm(dim, generator=g)[:bits] for _ in range(n)]) if n else \
            torch.zeros(0, bits, dtype=torch.long)
    else:
        raise ValueError("encoding must be 'random', 'double_hashing' or 'one_hot'")
    self.dim = int(dim)
    self.bits = int(bits)
    self.encoding = encoding
    self.positions: Tensor = pos.long()  # (n_symbols, bits)

vector

vector(symbols: Iterable) -> Tensor

(dim,) Boolean hypervector of a set of symbols (their bundle).

Source code in src/torchtsetlin/data/graphs.py
def vector(self, symbols: Iterable) -> Tensor:
    """``(dim,)`` Boolean hypervector of a set of symbols (their bundle)."""
    out = torch.zeros(self.dim, dtype=torch.bool)
    for s in symbols:
        out[self.positions[self.index[s]]] = True
    return out

encode

encode(nodes: Sequence[Iterable]) -> Tensor

(n, dim) Boolean feature matrix, one row per node's symbol set.

Source code in src/torchtsetlin/data/graphs.py
def encode(self, nodes: Sequence[Iterable]) -> Tensor:
    """``(n, dim)`` Boolean feature matrix, one row per node's symbol set."""
    if not len(nodes):
        return torch.zeros(0, self.dim, dtype=torch.bool)
    return torch.stack([self.vector(s) for s in nodes])

decode

decode(vector: Tensor) -> List

Symbols whose positions are all set in vector ((dim,) Boolean).

Source code in src/torchtsetlin/data/graphs.py
def decode(self, vector: Tensor) -> List:
    """Symbols whose positions are all set in ``vector`` (``(dim,)`` Boolean)."""
    v = as_bool_tensor(vector).flatten()
    hit = v[self.positions].all(dim=1)
    return [self.symbols[i] for i in torch.nonzero(hit).flatten().tolist()]

feature_names

feature_names() -> List[str]

Names of the dim positions: the symbol for one-hot tables, else hv[k].

Source code in src/torchtsetlin/data/graphs.py
def feature_names(self) -> List[str]:
    """Names of the ``dim`` positions: the symbol for one-hot tables, else ``hv[k]``."""
    if self.encoding == "one_hot":
        return [str(s) for s in self.symbols]
    return [f"hv[{k}]" for k in range(self.dim)]

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

(B, P, F) Boolean node features; rows beyond a graph's node count are padding and are ignored.

required
n_nodes Tensor

(B,) node count per graph.

required
edges Optional[Tensor]

(E, 2) long (source, destination) pairs of local node indices, grouped by graph in batch order.

None
edge_type Optional[Tensor]

(E,) integer edge types in [0, n_edge_types).

None
edges_per_graph Optional[Tensor]

(B,) number of edges of each graph (they sum to E).

None
node_type Optional[Tensor]

optional (B, P) integer node types in [0, n_node_types).

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 max(edge_type) + 1.

None
n_node_types Optional[int]

number of node types of the dataset. Defaults to max(node_type) + 1.

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
def __init__(
    self,
    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,
) -> None:
    x = as_bool_tensor(node_features)
    if x.dim() != 3:
        raise ValueError("node_features must have shape (B, P, F)")
    dev = x.device
    B, P, _ = x.shape
    n_nodes = torch.as_tensor(n_nodes, dtype=torch.long, device=dev).reshape(-1)
    if n_nodes.numel() != B:
        raise ValueError("n_nodes must hold one count per graph")
    if B and (int(n_nodes.min()) < 0 or int(n_nodes.max()) > P):
        raise ValueError("node counts must lie in [0, P]")
    if edges is None:
        edges = torch.zeros(0, 2, dtype=torch.long, device=dev)
    edges = torch.as_tensor(edges, dtype=torch.long, device=dev).reshape(-1, 2)
    E = edges.shape[0]
    edge_type = (torch.zeros(E, dtype=torch.long, device=dev) if edge_type is None
                 else torch.as_tensor(edge_type, dtype=torch.long, device=dev).reshape(-1))
    if edge_type.numel() != E:
        raise ValueError("edge_type must hold one type per edge")
    if edges_per_graph is None:
        if E and B != 1:
            raise ValueError("edges_per_graph is required for a batch of several graphs")
        edges_per_graph = torch.full((B,), E, dtype=torch.long, device=dev)
    edges_per_graph = torch.as_tensor(edges_per_graph, dtype=torch.long, device=dev).reshape(-1)
    if edges_per_graph.numel() != B or int(edges_per_graph.sum()) != E:
        raise ValueError("edges_per_graph must hold one count per graph and sum to E")
    if E:
        graph = torch.repeat_interleave(torch.arange(B, device=dev), edges_per_graph)
        if int(edges.min()) < 0 or bool((edges >= n_nodes[graph].unsqueeze(1)).any()):
            raise ValueError("an edge refers to a node outside its graph")
        if int(edge_type.min()) < 0:
            raise ValueError("edge types must be non-negative")
    if node_type is not None:
        node_type = torch.as_tensor(node_type, dtype=torch.long, device=dev)
        if node_type.shape != (B, P):
            raise ValueError("node_type must have shape (B, P)")
    self.node_features = x
    self.n_nodes = n_nodes
    self._edges: Optional[Tensor] = edges
    self._edge_type: Optional[Tensor] = edge_type
    self._edges_per_graph: Optional[Tensor] = edges_per_graph
    self._padded: Optional[Tuple[Tensor, Tensor, Tensor]] = None
    #: every graph has exactly ``P`` nodes (no padding rows). Set by the builders on the
    #: host and carried by slicing; it lets depth-1 models use the bit-packed kernel.
    self.full_nodes = False
    self.node_type = node_type
    inferred_et = int(edge_type.max()) + 1 if E else 1
    self.n_edge_types = int(n_edge_types) if n_edge_types is not None else inferred_et
    if E and inferred_et > self.n_edge_types:
        raise ValueError("an edge type is >= n_edge_types")
    inferred_nt = int(node_type.max()) + 1 if node_type is not None and node_type.numel() else 1
    self.n_node_types = int(n_node_types) if n_node_types is not None else inferred_nt
    if inferred_nt > self.n_node_types:
        raise ValueError("a node type is >= n_node_types")
    self.edge_type_names = None if edge_type_names is None else [str(n) for n in edge_type_names]
    if self.edge_type_names is not None and len(self.edge_type_names) != self.n_edge_types:
        raise ValueError("edge_type_names needs one name per edge type")

is_padded property

is_padded: bool

Whether the batch has the fixed-shape layout of :meth:pad.

edge_slots property

edge_slots: int

Stored edges: E (flat layout) or B * max_edges (padded layout). No sync.

edges property

edges: Tensor

(E, 2) local (source, destination) pairs, grouped by graph (for a padded batch, derived from the padded layout).

edge_type property

edge_type: Tensor

(E,) edge types, in the order of :attr:edges.

edges_per_graph property

edges_per_graph: Tensor

(B,) edge count of every graph.

shape property

shape: Size

(B, P, F), the shape of the padded node features.

node_mask property

node_mask: Tensor

(B, P) Boolean: which rows are real nodes.

edge_graph property

edge_graph: Tensor

(E,) graph index of every edge.

pad

pad(max_nodes: Optional[int] = None, max_edges: Optional[int] = None) -> GraphBatch

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
def pad(self, max_nodes: Optional[int] = None, max_edges: Optional[int] = None) -> GraphBatch:
    """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.
    """
    if self._padded is not None and max_nodes is None and max_edges is None:
        return self
    B, P0, F_ = self.shape
    dev = self.device
    per = self.edges_per_graph
    need_p = int(self.n_nodes.max()) if B else 0
    need_e = int(per.max()) if B and per.numel() else 0
    P = need_p if max_nodes is None else int(max_nodes)
    E = need_e if max_edges is None else int(max_edges)
    if P < need_p:
        raise ValueError(f"max_nodes={P} is below the largest graph ({need_p} nodes)")
    if E < need_e:
        raise ValueError(f"max_edges={E} is below the largest graph ({need_e} edges)")
    P = max(P, 1)
    feats = torch.zeros(B, P, F_, dtype=torch.bool, device=dev)
    k = min(P, P0)
    feats[:, :k] = self.node_features[:, :k]
    ntype = None
    if self.node_type is not None:
        ntype = torch.zeros(B, P, dtype=torch.long, device=dev)
        ntype[:, :k] = self.node_type[:, :k]
    edges = torch.zeros(B, E, 2, dtype=torch.long, device=dev)
    etype = torch.zeros(B, E, dtype=torch.long, device=dev)
    mask = torch.zeros(B, E, dtype=torch.bool, device=dev)
    flat_e, flat_t = self.edges, self.edge_type
    if flat_e.shape[0]:
        graph = self.edge_graph
        start = torch.cumsum(per, 0) - per
        slot = torch.arange(flat_e.shape[0], device=dev) - start[graph]
        edges[graph, slot] = flat_e
        etype[graph, slot] = flat_t
        mask[graph, slot] = True
    return self._keep_full(GraphBatch._from_padded(feats, self.n_nodes, edges, etype, mask, ntype,
                                                   self.n_edge_types, self.n_node_types,
                                                   self.edge_type_names))

unpad

unpad() -> GraphBatch

The flat layout (trimmed to the largest graph); a flat batch is returned as is.

Source code in src/torchtsetlin/data/graphs.py
def unpad(self) -> GraphBatch:
    """The flat layout (trimmed to the largest graph); a flat batch is returned as is."""
    if self._padded is None:
        return self
    P = int(self.n_nodes.max()) if len(self) else 0
    return self._keep_full(GraphBatch(
        self.node_features[:, :P], self.n_nodes, self.edges, self.edge_type, self.edges_per_graph,
        None if self.node_type is None else self.node_type[:, :P], self.n_edge_types, self.n_node_types,
        self.edge_type_names))

copy_

copy_(other: GraphBatch) -> GraphBatch

Copy a padded batch of the same shape into this one, in place (CUDA-graph inputs).

Source code in src/torchtsetlin/data/graphs.py
def copy_(self, other: GraphBatch) -> GraphBatch:
    """Copy a padded batch of the same shape into this one, in place (CUDA-graph inputs)."""
    if self._padded is None or other._padded is None:
        raise ValueError("copy_ needs padded batches (GraphBatch.pad)")
    if (self.shape != other.shape or self._padded[0].shape != other._padded[0].shape
            or (self.node_type is None) != (other.node_type is None)):
        raise ValueError("copy_ needs batches of the same padded shape")
    self.node_features.copy_(other.node_features)
    self.n_nodes.copy_(other.n_nodes)
    for a, b in zip(self._padded, other._padded):
        a.copy_(b)
    if self.node_type is not None:
        self.node_type.copy_(other.node_type)  # type: ignore[arg-type]
    return self

clone

clone() -> GraphBatch

A copy with its own storage (same layout).

Source code in src/torchtsetlin/data/graphs.py
def clone(self) -> GraphBatch:
    """A copy with its own storage (same layout)."""
    if self._padded is not None:
        e, t, m = self._padded
        return self._keep_full(GraphBatch._from_padded(
            self.node_features.clone(), self.n_nodes.clone(), e.clone(), t.clone(), m.clone(),
            None if self.node_type is None else self.node_type.clone(), self.n_edge_types,
            self.n_node_types, self.edge_type_names))
    return self._keep_full(GraphBatch(
        self.node_features.clone(), self.n_nodes.clone(), self.edges.clone(), self.edge_type.clone(),
        self.edges_per_graph.clone(), None if self.node_type is None else self.node_type.clone(),
        self.n_edge_types, self.n_node_types, self.edge_type_names))

cat staticmethod

cat(batches: Sequence[GraphBatch]) -> GraphBatch

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
@staticmethod
def cat(batches: Sequence[GraphBatch]) -> GraphBatch:
    """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``)."""
    if not batches:
        raise ValueError("nothing to concatenate")
    out = GraphBatch._cat(batches)
    out.full_nodes = all(b.full_nodes and b.shape[1] == out.shape[1] for b in batches)
    return out

flat_edges

flat_edges() -> Tuple[Tensor, Tensor, Tensor]

(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
def flat_edges(self) -> Tuple[Tensor, Tensor, Tensor]:
    """``(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."""
    P = self.node_features.shape[1]
    if self._padded is not None:
        e, t, _ = self._padded
        base = (torch.arange(e.shape[0], device=e.device) * P).unsqueeze(1)
        return (base + e[..., 0]).reshape(-1), (base + e[..., 1]).reshape(-1), t.reshape(-1)
    base = self.edge_graph * P
    return base + self.edges[:, 0], base + self.edges[:, 1], self.edge_type

flat_edge_mask

flat_edge_mask() -> Optional[Tensor]

(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
def flat_edge_mask(self) -> Optional[Tensor]:
    """``(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."""
    return None if self._padded is None else self._padded[2].reshape(-1)

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 (n_i, F) Boolean array.

required
edges Optional[Sequence]

per graph, an (E_i, 2) array of (source, destination) local node indices (or None / empty for no edges).

None
edge_types Optional[Sequence]

per graph, an (E_i,) array of edge types (default: all 0).

None
node_types Optional[Sequence]

per graph, an (n_i,) array of node types (default: none).

None
Source code in src/torchtsetlin/data/graphs.py
@classmethod
def from_graphs(
    cls,
    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.

    Args:
        node_features: per graph, an ``(n_i, F)`` Boolean array.
        edges: per graph, an ``(E_i, 2)`` array of ``(source, destination)`` local node
            indices (or ``None`` / empty for no edges).
        edge_types: per graph, an ``(E_i,)`` array of edge types (default: all ``0``).
        node_types: per graph, an ``(n_i,)`` array of node types (default: none).
    """
    feats = [as_bool_tensor(f) for f in node_features]
    if not feats:
        raise ValueError("no graphs")
    F_ = feats[0].shape[1] if feats[0].dim() == 2 else 0
    n = torch.tensor([f.shape[0] for f in feats], dtype=torch.long)
    P = max(1, int(n.max()))
    X = torch.zeros(len(feats), P, F_, dtype=torch.bool)
    for i, f in enumerate(feats):
        if f.dim() != 2 or f.shape[1] != F_:
            raise ValueError("every graph needs (n_i, F) node features with the same F")
        X[i, : f.shape[0]] = f.cpu()
    E_list, T_list, per = [], [], []
    for i in range(len(feats)):
        e = edges[i] if edges is not None else None
        e = torch.zeros(0, 2, dtype=torch.long) if e is None else torch.as_tensor(e, dtype=torch.long).reshape(-1, 2)
        t = edge_types[i] if edge_types is not None else None
        t = torch.zeros(e.shape[0], dtype=torch.long) if t is None else torch.as_tensor(t, dtype=torch.long).reshape(-1)
        E_list.append(e)
        T_list.append(t)
        per.append(e.shape[0])
    nt = None
    if node_types is not None:
        nt = torch.zeros(len(feats), P, dtype=torch.long)
        for i, t in enumerate(node_types):
            t = torch.as_tensor(t, dtype=torch.long).reshape(-1)
            nt[i, : t.numel()] = t
    g = cls(X, n, torch.cat(E_list), torch.cat(T_list), torch.tensor(per, dtype=torch.long), nt,
            n_edge_types, n_node_types, edge_type_names)
    g.full_nodes = bool((n == P).all())  # on the host, while building
    return g

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
@classmethod
def from_sequences(
    cls,
    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"``).
    """
    if unknown not in ("ignore", "error"):
        raise ValueError("unknown must be 'ignore' or 'error'")
    feats, edges, types = [], [], []
    for seq in sequences:
        nodes = []
        for el in seq:
            group = el if isinstance(el, (set, frozenset, list, tuple)) else [el]
            kept = [s for s in group if s in symbols.index]
            if unknown == "error" and len(kept) != len(group):
                raise KeyError(f"unknown symbol in {group!r}")
            nodes.append(kept)
        feats.append(symbols.encode(nodes) if nodes else torch.zeros(0, symbols.dim, dtype=torch.bool))
        L = len(nodes)
        k = torch.arange(L)
        left = torch.stack([k[1:], k[:-1]], dim=1)   # k -> k-1, type 0
        right = torch.stack([k[:-1], k[1:]], dim=1)  # k -> k+1, type 1
        edges.append(torch.cat([left, right]))
        types.append(torch.cat([torch.zeros(max(L - 1, 0), dtype=torch.long),
                                torch.ones(max(L - 1, 0), dtype=torch.long)]))
    return cls.from_graphs(feats, edges, types, n_edge_types=2, edge_type_names=edge_types)

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 (B, Z, H, W) (or (B, H, W)) images.

required
Source code in src/torchtsetlin/data/graphs.py
@classmethod
def from_images(
    cls,
    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.

    Args:
        images: Boolean ``(B, Z, H, W)`` (or ``(B, H, W)``) images.
    """
    x = as_bool_tensor(images)
    if x.dim() == 3:
        x = x.unsqueeze(1)
    if x.dim() != 4:
        raise ValueError("images must have shape (B, Z, H, W) or (B, H, W)")
    kh, kw = (patch_size, patch_size) if isinstance(patch_size, int) else patch_size
    sh, sw = (stride, stride) if isinstance(stride, int) else stride
    B, Z, H, W = x.shape
    Py, Px = (H - kh) // sh + 1, (W - kw) // sw + 1
    if Py < 1 or Px < 1:
        raise ValueError("image smaller than the patch")
    patches = torch.nn.functional.unfold(x.float(), kernel_size=(kh, kw), stride=(sh, sw))
    patches = patches.transpose(1, 2) > 0.5  # (B, P, Z*kh*kw)
    if position_encoding:
        ys = torch.arange(Py, device=x.device).repeat_interleave(Px)
        xs = torch.arange(Px, device=x.device).repeat(Py)
        pos = torch.cat([ys.unsqueeze(1) > torch.arange(Py - 1, device=x.device).unsqueeze(0),
                         xs.unsqueeze(1) > torch.arange(Px - 1, device=x.device).unsqueeze(0)], dim=1)
        patches = torch.cat([patches, pos.unsqueeze(0).expand(B, -1, -1)], dim=2)
    P = Py * Px
    n = torch.full((B,), P, dtype=torch.long, device=x.device)
    g = cls(patches, n, None, None, torch.zeros(B, dtype=torch.long, device=x.device), None, 1, 1)
    g.full_nodes = True  # every image has the same patches
    return g