Skip to content

torchtsetlin.datasets

Ready-made datasets. Encoders, splits and wrappers for your own data are in torchtsetlin.data; the guide is Benchmark datasets.

The generators and loaders below were in torchtsetlin.data up to 0.8.6 and remain importable from there.

Benchmarks that download on first use

torchtsetlin.datasets.benchmarks

Benchmark datasets that download themselves on first use (issue #54).

The 15 benchmarks of TM-MCAF (Dumbre, Shende, Granmo and Jiao, "Pruning Redundant Literals in Tsetlin Machines via Minimal Co-Firing Clauses", arXiv 2612.01468), with the paper's Booleanization as the default:

Class Source (downloaded on first use) Booleanization
HIGGS OpenML 23512 10 quantile bins, one-hot
Electricity OpenML 151 10 quantile bins, one-hot
MagicTelescope OpenML 1120 10 quantile bins, one-hot
PhishingWebsites OpenML 4534 one-hot
BayesianNetworkDataset bnlearn pigs / hailfinder networks, sampled locally one-hot
IMDB Keras imdb.npz 5,000-word multi-hot
Reuters Keras reuters.npz (10 most frequent topics) 5,000-word multi-hot
BooleanImageDataset torchvision MNIST, Fashion-MNIST, KMNIST pixel > 75

Like torchvision datasets, the first use with download=True fetches the original files into root/<Name>/raw/ (each checked against a pinned SHA-256) and writes a processed copy to root/<Name>/processed/; later uses load the processed copy and never touch the network. root defaults to $TORCHTSETLIN_DATA or ./data.

The Booleanization is always fitted on the training split, also for train=False, so the two splits share thresholds. x/targets hold the split; :meth:tensors returns them.

BayesianNetworkDataset

BayesianNetworkDataset(network: str, target: str, root=None, train: bool = True, download: bool = False, n_samples: int = 10000, sample_seed: int = 0, booleanize: bool = True, test_size: float = 0.2, split_seed: int = 0, oversample: bool = False, device=None, encoder: Any = None)

Bases: _TableDataset

Predict one node of a bnlearn Bayesian network from all the others.

The network (BIF file) is downloaded from the bnlearn repository; n_samples forward samples are drawn with sample_seed and cached, so the same arguments always give the same data. Every other node is an input, one-hot encoded over its states.

The TM-MCAF paper uses the targets in :attr:PAPER_TARGETS and does not state how many samples it drew; 10,000 is this library's default.

Parameters:

Name Type Description Default
network str

"pigs" (441 nodes) or "hailfinder" (56 nodes).

required
target str

the node to predict, e.g. "WindFieldMt".

required
n_samples int

number of forward samples (before the split).

10000
sample_seed int

seed of the sampling.

0
encoder Any

an encoder for the state codes of all input nodes instead of the one-hot encoding (fitted on a copy, on the training split).

None
Other arguments as for

class:HIGGS.

required
Source code in src/torchtsetlin/datasets/benchmarks.py
def __init__(self, network: str, target: str, root=None, train: bool = True, download: bool = False,
             n_samples: int = 10_000, sample_seed: int = 0, booleanize: bool = True,
             test_size: float = 0.2, split_seed: int = 0, oversample: bool = False, device=None,
             encoder: Any = None) -> None:
    if network not in self.NETWORKS:
        raise ValueError(f"network must be one of {sorted(self.NETWORKS)}, got {network!r}")
    super().__init__(root, download)
    self.network, self.target = network, target
    self.folder = f"BayesianNetwork/{network}"
    url, sha = self.NETWORKS[network]
    self.resources = ((url, f"{network}.bif.gz", sha),)
    self.n_samples, self.sample_seed = int(n_samples), int(sample_seed)
    samples = self._cached(f"samples_n{self.n_samples}_seed{self.sample_seed}_v1.pt", self._build)
    variables: List[str] = samples["variables"]
    if target not in variables:
        raise ValueError(f"{target!r} is not a node of {network!r}")
    self.parents: Dict[str, List[str]] = samples["parents"]
    states: List[List[str]] = samples["states"]
    t = variables.index(target)
    keep = [j for j in range(len(variables)) if j != t]
    codes = samples["codes"].long()
    table = {
        "x": codes[:, keep].float(),
        "y": codes[:, t],
        "columns": [variables[j] for j in keep],
        "categories": [states[j] for j in keep],
        "classes": states[t],
    }
    self._setup(table, train, booleanize, 2, test_size, split_seed, oversample, device, encoder)

markov_blanket

markov_blanket(node: Optional[str] = None) -> List[str]

Markov blanket (parents, children, children's other parents) of node (default: the target), the ground truth for the paper's Table 4 analysis.

Source code in src/torchtsetlin/datasets/benchmarks.py
def markov_blanket(self, node: Optional[str] = None) -> List[str]:
    """Markov blanket (parents, children, children's other parents) of ``node``
    (default: the target), the ground truth for the paper's Table 4 analysis."""
    v = self.target if node is None else node
    if v not in self.parents:
        raise KeyError(f"unknown node {v!r}")
    kids = [c for c, ps in self.parents.items() if v in ps]
    mb = set(self.parents[v]) | set(kids)
    for c in kids:
        mb |= set(self.parents[c])
    mb.discard(v)
    return [u for u in self.parents if u in mb]

IMDB

IMDB(root=None, train: bool = True, download: bool = False, num_words: int = 5000, booleanize: bool = True, oversample: bool = False, device=None, encoder: Any = None)

Bases: _KerasText

IMDB movie reviews, positive vs negative, as Keras ships them (imdb.npz, the word-index version of Maas et al. 2011): 25,000 training and 25,000 test reviews.

x is the multi-hot vector over the num_words most frequent words (Keras indices: 0 padding, 1 start, 2 out-of-vocabulary, rank + 3 for words), as in TM-MCAF with num_words=5000. :attr:feature_names gives the word of every position.

Parameters:

Name Type Description Default
root, train, download, oversample, device

as for :class:HIGGS.

required
num_words int

vocabulary size (Keras num_words).

5000
booleanize bool

False leaves x empty; items are then word-index sequences.

True
encoder Any

an encoder instead of the multi-hot vector. It gets the word indices of a batch of documents as a (n, max_len) long tensor padded with -1 (the input of HypervectorEncoder) and must return (n, ...) Booleans; a copy is fitted on the training documents.

None
Source code in src/torchtsetlin/datasets/benchmarks.py
def __init__(self, root=None, train: bool = True, download: bool = False, num_words: int = 5000,
             booleanize: bool = True, oversample: bool = False, device=None, encoder: Any = None) -> None:
    super().__init__(root, download)
    self.train = bool(train)
    self.resources = self._resources()
    data = self._cached("imdb_v1.pt", self._build)
    part = "train" if train else "test"
    self._setup_text(data[f"{part}_tokens"], data[f"{part}_lengths"], data[f"{part}_labels"],
                     num_words, booleanize, oversample, 113, data["vocab"], device,
                     encoder, (data["train_tokens"], data["train_lengths"]))

Reuters

Reuters(root=None, train: bool = True, download: bool = False, num_words: int = 5000, top_classes: Optional[int] = 10, test_split: float = 0.2, booleanize: bool = True, oversample: bool = False, device=None, encoder: Any = None)

Bases: _KerasText

Reuters newswire topics as Keras ships them (reuters.npz: 11,228 newswires, 46 topics), split as Keras does (shuffle with seed 113, first 80 % for training).

top_classes=10 (the default, as in TM-MCAF) keeps the 10 topics most frequent in the training split and relabels them 0..9 in increasing topic id; :attr:topics gives the original Keras topic ids. top_classes=None keeps all 46.

Parameters:

Name Type Description Default
root, train, download, num_words, booleanize, oversample, device, encoder

as for :class:IMDB (the encoder is fitted on the training documents of the kept topics).

required
top_classes Optional[int]

number of most frequent topics to keep, or None.

10
test_split float

Keras test_split.

0.2
Source code in src/torchtsetlin/datasets/benchmarks.py
def __init__(self, root=None, train: bool = True, download: bool = False, num_words: int = 5000,
             top_classes: Optional[int] = 10, test_split: float = 0.2, booleanize: bool = True,
             oversample: bool = False, device=None, encoder: Any = None) -> None:
    super().__init__(root, download)
    self.train = bool(train)
    self.resources = self._resources()
    data = self._cached("reuters_v1.pt", self._build)
    tokens, lengths, labels = data["tokens"], data["lengths"], data["labels"]
    n_train = int(len(labels) * (1 - test_split))
    offsets = torch.cumsum(lengths, 0) - lengths
    if top_classes is not None:
        counts = torch.bincount(labels[:n_train])
        order = sorted(range(counts.numel()), key=lambda c: (-int(counts[c]), c))
        self.topics = sorted(order[: int(top_classes)])
    else:
        self.topics = sorted(torch.unique(labels).tolist())
    keep = torch.tensor(self.topics)

    def select(docs: Tensor) -> Tuple[Tensor, Tensor]:
        docs = docs[torch.isin(labels[docs], keep)]
        toks = [tokens[offsets[i]: offsets[i] + lengths[i]] for i in docs.tolist()]
        return (torch.cat(toks) if toks else torch.empty(0, dtype=tokens.dtype)), docs

    part = torch.arange(n_train) if train else torch.arange(n_train, len(labels))
    sel_tokens, part = select(part)
    remap = torch.full((int(labels.max()) + 1,), -1, dtype=torch.long)
    remap[keep] = torch.arange(len(self.topics))
    self.classes = [f"topic {t}" for t in self.topics]
    fit_on = None
    if encoder is not None:
        fit_tokens, fit_docs = select(torch.arange(n_train))
        fit_on = (fit_tokens, lengths[fit_docs])
    self._setup_text(sel_tokens, lengths[part], remap[labels[part]], num_words, booleanize,
                     oversample, 113, data["vocab"], device, encoder, fit_on)

BooleanImageDataset

BooleanImageDataset(name: str, root=None, train: bool = True, download: bool = False, threshold: int = 75, split: str = 'official', test_size: float = 0.2, split_seed: int = 0, oversample: bool = False, flatten: bool = False, device=None, encoder: Any = None)

Bases: _CachedDataset

MNIST, Fashion-MNIST or KMNIST, thresholded to one bit per pixel.

torchvision downloads and caches the images (root/MNIST, root/FashionMNIST, root/KMNIST); install the vision extra. A pixel is True when its 8-bit intensity is above threshold (75 in TM-MCAF).

Parameters:

Name Type Description Default
name str

"mnist", "fashion-mnist" or "kmnist".

required
split str

"official" (60,000 / 10,000) or "paper": all 70,000 images, stratified 80/20 with split_seed (TM-MCAF lists only IMDB and REUTERS as using their native split).

'official'
flatten bool

x as (N, 784) (or the encoder's output flattened per image) instead of (N, 1, 28, 28).

False
encoder Any

an encoder instead of the threshold, e.g. AdaptiveThresholdEncoder(11, 2.0) or ThermometerEncoder(8, strategy="uniform", value_range=(0, 1)). It gets float images (n, 1, 28, 28) scaled to [0, 1] and must return (n, ...) Booleans; a copy is fitted on the training images. threshold is then unused.

None
Other arguments as for

class:HIGGS.

required
Source code in src/torchtsetlin/datasets/benchmarks.py
def __init__(self, name: str, root=None, train: bool = True, download: bool = False,
             threshold: int = 75, split: str = "official", test_size: float = 0.2, split_seed: int = 0,
             oversample: bool = False, flatten: bool = False, device=None, encoder: Any = None) -> None:
    key = name.lower()
    if key not in self._CLASSES:
        raise ValueError(f"name must be one of {sorted(self._CLASSES)}, got {name!r}")
    if split not in ("official", "paper"):
        raise ValueError("split must be 'official' or 'paper'")
    super().__init__(root, download)
    self.name, self.train = key, bool(train)
    try:
        from torchvision import datasets as tvd
    except Exception as e:  # pragma: no cover - optional dependency
        # a torchvision built for another torch raises RuntimeError on import, and
        # AttributeError on a later attempt (the half-imported module stays in sys.modules)
        raise ImportError(
            "BooleanImageDataset needs a working torchvision (pip install 'torchtsetlin[vision]', "
            f"matching your torch build): {e}"
        ) from e
    cls = getattr(tvd, self._CLASSES[key])

    def part(is_train: bool):
        try:
            ds = cls(root=str(self.root), train=is_train, download=self.download)
        except RuntimeError as e:
            raise RuntimeError(f"{e} (torchvision {cls.__name__} under {self.root})") from e
        return torch.as_tensor(np.asarray(ds.data)), torch.as_tensor(np.asarray(ds.targets)).long(), ds.classes

    if split == "official":
        data, targets, classes = part(self.train)
        idx = torch.arange(targets.numel())
        y_all = targets

        def train_images() -> Tensor:
            return data if self.train else part(True)[0]
    else:
        d1, t1, classes = part(True)
        d2, t2, _ = part(False)
        data, y_all = torch.cat([d1, d2]), torch.cat([t1, t2])
        tr, te = stratified_split(y_all, test_size, split_seed)
        idx = tr if self.train else te

        def train_images() -> Tensor:
            return data[tr]
    if self.train and oversample:
        idx = random_oversample(idx, y_all, split_seed)
    self.indices = idx
    self.data = data[idx]
    self.targets = y_all[idx]
    self.classes = list(classes)
    h, w = self.data.shape[1:]
    self.encoder = None
    if encoder is None:
        x = self.data > int(threshold)
        self.x = x.reshape(x.shape[0], -1) if flatten else x.unsqueeze(1)
        self.feature_names = [f"pixel({r},{c})" for r in range(h) for c in range(w)]
    else:
        def scaled(images: Tensor) -> Tensor:
            return images.unsqueeze(1).float() / 255.0

        enc = _fitted_copy(encoder, lambda: scaled(train_images()))
        x = _encode_rows(enc, len(self.data), lambda a, b: scaled(self.data[a:b]), 10_000, self.name)
        self.x = x.reshape(x.shape[0], -1) if flatten else x
        self.encoder = enc
        self.feature_names = [f"bit{i}" for i in range(int(x[0].numel()) if len(x) else 0)]
    self._to(device)

Loaders for torchvision datasets

torchtsetlin.datasets.loaders

Loaders that booleanize torchvision datasets into in-memory tensors.

load_torchvision_boolean

load_torchvision_boolean(dataset_cls, root: str, train: bool, encoder: Optional[Callable] = None, threshold: float = 0.3, device=None, download: bool = True, max_samples: Optional[int] = None, **kwargs) -> Tuple[Tensor, Tensor]

Load a torchvision dataset fully into memory and booleanize it.

encoder receives a float tensor (N, C, H, W) scaled to [0, 1] and must return a Boolean tensor. By default pixels are thresholded at threshold (0.3, as in the original MNIST experiments). Returns (x_bool, y_long) on device.

Source code in src/torchtsetlin/datasets/loaders.py
def load_torchvision_boolean(
    dataset_cls,
    root: str,
    train: bool,
    encoder: Optional[Callable] = None,
    threshold: float = 0.3,
    device=None,
    download: bool = True,
    max_samples: Optional[int] = None,
    **kwargs,
) -> Tuple[Tensor, Tensor]:
    """Load a torchvision dataset fully into memory and booleanize it.

    ``encoder`` receives a float tensor ``(N, C, H, W)`` scaled to ``[0, 1]`` and must return
    a Boolean tensor. By default pixels are thresholded at ``threshold`` (0.3, as in the
    original MNIST experiments). Returns ``(x_bool, y_long)`` on ``device``.
    """
    ds = dataset_cls(root=root, train=train, download=download, **kwargs)
    data = ds.data
    if not isinstance(data, Tensor):
        data = torch.as_tensor(np.asarray(data))
    if data.dim() == 3:  # (N, H, W)
        data = data.unsqueeze(1)
    elif data.dim() == 4 and data.shape[-1] in (1, 3):  # (N, H, W, C) -> (N, C, H, W)
        data = data.permute(0, 3, 1, 2)
    targets = torch.as_tensor(np.asarray(ds.targets)).long()
    if max_samples is not None:
        data, targets = data[:max_samples], targets[:max_samples]
    x = data.float() / 255.0
    if device is not None:
        x, targets = x.to(device), targets.to(device)
    xb = encoder(x) if encoder is not None else (x > threshold)
    return xb, targets

load_mnist_boolean

load_mnist_boolean(root: str = './data', train: bool = True, threshold: float = 0.3, encoder: Optional[Callable] = None, device=None, flatten: bool = False, max_samples: Optional[int] = None) -> Tuple[Tensor, Tensor]

MNIST as Boolean tensors (N, 1, 28, 28) (or (N, 784) with flatten=True). Requires torchvision.

Source code in src/torchtsetlin/datasets/loaders.py
def load_mnist_boolean(
    root: str = "./data",
    train: bool = True,
    threshold: float = 0.3,
    encoder: Optional[Callable] = None,
    device=None,
    flatten: bool = False,
    max_samples: Optional[int] = None,
) -> Tuple[Tensor, Tensor]:
    """MNIST as Boolean tensors ``(N, 1, 28, 28)`` (or ``(N, 784)`` with ``flatten=True``).
    Requires ``torchvision``."""
    try:
        from torchvision.datasets import MNIST
    except ImportError as e:  # pragma: no cover
        raise ImportError("torchvision is required for load_mnist_boolean") from e
    x, y = load_torchvision_boolean(
        MNIST, root, train, encoder=encoder, threshold=threshold, device=device, max_samples=max_samples
    )
    if flatten:
        x = x.reshape(x.shape[0], -1)
    return x, y

load_segmentation_boolean

load_segmentation_boolean(dataset: Dataset, encoder: Optional[Callable] = None, size: Optional[Union[int, Tuple[int, int]]] = None, n_bits: int = 4, device: Optional[Union[str, device]] = None, max_samples: Optional[int] = None, ignore_index: int = 255, remap: Optional[dict] = None) -> Tuple[Tensor, Tensor]

Load a torchvision segmentation dataset into memory as Boolean planes + label maps.

Segmentation datasets yield (image, mask) PIL pairs rather than the packed tensors :func:load_torchvision_boolean expects, and the mask must be resized with nearest interpolation — bilinear would invent class indices that do not exist. This handles both.

Parameters:

Name Type Description Default
dataset Dataset

an instantiated torchvision segmentation dataset, e.g. VOCSegmentation(root, image_set="train", download=True) or Cityscapes(root, split="train", target_type="semantic"). Each sample is read once, so a dataset with random joint transforms yields one consistent image/mask draw per sample (the result is still a fixed in-memory set).

required
encoder Optional[Callable]

maps a float image batch (N, 3, H, W) in [0, 1] to Boolean planes. Defaults to a :class:~torchtsetlin.data.ColorThermometerEncoder with n_bits levels per channel, which keeps the ordering between intensities.

None
size Optional[Union[int, Tuple[int, int]]]

H or (H, W) to resize to. Dense Tsetlin machines evaluate one patch per pixel, so full-resolution frames are expensive — 64-128 px is a sane starting point. None keeps the native size (all images must then already match).

None
n_bits int

thermometer levels per channel for the default encoder.

4
device Optional[Union[str, device]]

device for the returned tensors.

None
max_samples Optional[int]

stop after this many images.

None
ignore_index int

mask value to keep as the void class. Pass the same value as the model's ignore_index.

255
remap Optional[dict]

optional {original_label: new_label} mapping applied to the masks, for collapsing a dataset's classes into a coarser set.

None

Returns:

Type Description
Tuple[Tensor, Tensor]

(x_bool, labels) with x_bool (N, Z, H, W) and labels (N, H, W).

Source code in src/torchtsetlin/datasets/loaders.py
def load_segmentation_boolean(
    dataset: Dataset,
    encoder: Optional[Callable] = None,
    size: Optional[Union[int, Tuple[int, int]]] = None,
    n_bits: int = 4,
    device: Optional[Union[str, torch.device]] = None,
    max_samples: Optional[int] = None,
    ignore_index: int = 255,
    remap: Optional[dict] = None,
) -> Tuple[Tensor, Tensor]:
    """Load a torchvision *segmentation* dataset into memory as Boolean planes + label maps.

    Segmentation datasets yield ``(image, mask)`` PIL pairs rather than the packed tensors
    :func:`load_torchvision_boolean` expects, and the mask must be resized with **nearest**
    interpolation — bilinear would invent class indices that do not exist. This handles both.

    Args:
        dataset: an instantiated torchvision segmentation dataset, e.g.
            ``VOCSegmentation(root, image_set="train", download=True)`` or
            ``Cityscapes(root, split="train", target_type="semantic")``. Each sample is
            read once, so a dataset with random joint transforms yields one consistent
            image/mask draw per sample (the result is still a fixed in-memory set).
        encoder: maps a float image batch ``(N, 3, H, W)`` in ``[0, 1]`` to Boolean planes.
            Defaults to a :class:`~torchtsetlin.data.ColorThermometerEncoder` with ``n_bits``
            levels per channel, which keeps the ordering between intensities.
        size: ``H`` or ``(H, W)`` to resize to. Dense Tsetlin machines evaluate one patch per
            pixel, so full-resolution frames are expensive — 64-128 px is a sane starting
            point. ``None`` keeps the native size (all images must then already match).
        n_bits: thermometer levels per channel for the default encoder.
        device: device for the returned tensors.
        max_samples: stop after this many images.
        ignore_index: mask value to keep as the void class. Pass the same value as the
            model's ``ignore_index``.
        remap: optional ``{original_label: new_label}`` mapping applied to the masks, for
            collapsing a dataset's classes into a coarser set.

    Returns:
        ``(x_bool, labels)`` with ``x_bool`` ``(N, Z, H, W)`` and ``labels`` ``(N, H, W)``.
    """
    _vf = None

    def vf():  # torchvision is needed only to resize or to convert PIL images
        nonlocal _vf
        if _vf is None:
            try:
                from torchvision.transforms import functional as VF
            except ImportError as e:  # pragma: no cover
                raise ImportError(
                    "torchvision is required by load_segmentation_boolean to resize or read PIL images"
                ) from e
            _vf = VF
        return _vf

    hw = None if size is None else ((size, size) if isinstance(size, int) else tuple(size))
    n = len(dataset) if max_samples is None else min(len(dataset), int(max_samples))
    imgs, masks = [], []
    for i in range(n):
        sample = dataset[i]  # one access: a random joint transform is drawn once per pair
        img, mask = sample[0], sample[1]
        if hw is not None:
            img = vf().resize(img, list(hw))
            mask = vf().resize(mask, list(hw), interpolation=vf().InterpolationMode.NEAREST)
        img_t = img if isinstance(img, Tensor) else vf().pil_to_tensor(img)
        mask_t = mask if isinstance(mask, Tensor) else vf().pil_to_tensor(mask)
        imgs.append(img_t.float() / 255.0)
        masks.append(mask_t.squeeze(0).long())
    x = torch.stack(imgs)
    y = torch.stack(masks)
    if remap:
        out = torch.full_like(y, int(ignore_index))
        for src, dst in remap.items():
            out[y == int(src)] = int(dst)
        y = out
    if device is not None:
        x, y = x.to(device), y.to(device)
    if encoder is None:
        from ..data.encoders import ColorThermometerEncoder

        encoder = ColorThermometerEncoder(n_bits=n_bits, value_range=(0.0, 1.0))
        if device is not None:
            encoder = encoder.to(device)
    return encoder(x), y

load_voc_segmentation_boolean

load_voc_segmentation_boolean(root: str = './data', image_set: str = 'train', size: Union[int, Tuple[int, int]] = 96, n_bits: int = 4, device=None, download: bool = True, max_samples: Optional[int] = None, **kwargs) -> Tuple[Tensor, Tensor]

Pascal VOC 2012 segmentation as Boolean planes + label maps (21 classes + void).

Void pixels keep the value 255, so pass ignore_index=255 to the model. Requires torchvision.

Source code in src/torchtsetlin/datasets/loaders.py
def load_voc_segmentation_boolean(
    root: str = "./data",
    image_set: str = "train",
    size: Union[int, Tuple[int, int]] = 96,
    n_bits: int = 4,
    device=None,
    download: bool = True,
    max_samples: Optional[int] = None,
    **kwargs,
) -> Tuple[Tensor, Tensor]:
    """Pascal VOC 2012 segmentation as Boolean planes + label maps (21 classes + void).

    Void pixels keep the value ``255``, so pass ``ignore_index=255`` to the model. Requires
    ``torchvision``.
    """
    try:
        from torchvision.datasets import VOCSegmentation
    except ImportError as e:  # pragma: no cover
        raise ImportError("torchvision is required for load_voc_segmentation_boolean") from e
    ds = VOCSegmentation(root=root, image_set=image_set, download=download, **kwargs)
    return load_segmentation_boolean(
        ds, size=size, n_bits=n_bits, device=device, max_samples=max_samples, ignore_index=255
    )

Generated data

torchtsetlin.datasets.synthetic

Generated Boolean datasets: XOR variants, shapes, volumes and segmentation scenes.

make_xor

make_xor(n: int, n_features: int = 2, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

Random Boolean vectors labelled by x0 XOR x1 (other features are distractors).

Source code in src/torchtsetlin/datasets/synthetic.py
def make_xor(n: int, n_features: int = 2, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]:
    """Random Boolean vectors labelled by ``x0 XOR x1`` (other features are distractors)."""
    return make_noisy_xor(n, n_features=n_features, noise=0.0, seed=seed, device=device)

make_noisy_xor

make_noisy_xor(n: int, n_features: int = 12, noise: float = 0.4, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

The Noisy XOR benchmark of the original Tsetlin machine paper: 12 Boolean features of which only the first two matter (y = x0 XOR x1); a fraction noise of the training labels are flipped.

Source code in src/torchtsetlin/datasets/synthetic.py
def make_noisy_xor(
    n: int, n_features: int = 12, noise: float = 0.4, seed: Optional[int] = 0, device=None
) -> Tuple[Tensor, Tensor]:
    """The *Noisy XOR* benchmark of the original Tsetlin machine paper: 12 Boolean features
    of which only the first two matter (``y = x0 XOR x1``); a fraction ``noise`` of the
    training labels are flipped."""
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    x = torch.randint(0, 2, (n, n_features), generator=g).bool()
    y = (x[:, 0] ^ x[:, 1]).long()
    if noise > 0:
        flip = torch.rand(n, generator=g) < noise
        y = torch.where(flip, 1 - y, y)
    dev = torch.device(device) if device else None
    return (x.to(dev), y.to(dev)) if dev else (x, y)

make_parity

make_parity(n: int, n_bits: int = 4, n_features: int = 8, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

Parity of the first n_bits features (harder than XOR).

Source code in src/torchtsetlin/datasets/synthetic.py
def make_parity(n: int, n_bits: int = 4, n_features: int = 8, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]:
    """Parity of the first ``n_bits`` features (harder than XOR)."""
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    x = torch.randint(0, 2, (n, n_features), generator=g).bool()
    y = (x[:, :n_bits].long().sum(dim=1) % 2).long()
    dev = torch.device(device) if device else None
    return (x.to(dev), y.to(dev)) if dev else (x, y)

make_2d_noisy_xor

make_2d_noisy_xor(n: int, size: int = 4, noise: float = 0.0, seed: Optional[int] = 0, device=None, max_tries: int = 200) -> Tuple[Tensor, Tensor]

2D Noisy XOR of the Convolutional TM paper: a size x size binary image whose pixels are random, except for one 2 x 2 patch (at a random position) that carries the class pattern.

Class 1 patterns are the diagonals [[1,0],[0,1]] / [[0,1],[1,0]], class 0 patterns are the horizontal bars [[1,1],[0,0]] / [[0,0],[1,1]]. Backgrounds are resampled so that no other window contains any of the four patterns (otherwise the label would be ambiguous). A fraction noise of the labels is flipped.

Returns images (n, 1, size, size) and labels (n,).

Source code in src/torchtsetlin/datasets/synthetic.py
def make_2d_noisy_xor(
    n: int, size: int = 4, noise: float = 0.0, seed: Optional[int] = 0, device=None, max_tries: int = 200
) -> Tuple[Tensor, Tensor]:
    """2D Noisy XOR of the Convolutional TM paper: a ``size x size`` binary image whose
    pixels are random, except for one ``2 x 2`` patch (at a random position) that carries
    the class pattern.

    Class ``1`` patterns are the diagonals ``[[1,0],[0,1]]`` / ``[[0,1],[1,0]]``, class ``0``
    patterns are the horizontal bars ``[[1,1],[0,0]]`` / ``[[0,0],[1,1]]``. Backgrounds are
    resampled so that no *other* window contains any of the four patterns (otherwise the
    label would be ambiguous). A fraction ``noise`` of the labels is flipped.

    Returns images ``(n, 1, size, size)`` and labels ``(n,)``.
    """
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    patterns = torch.tensor(
        [[[1, 1], [0, 0]], [[0, 0], [1, 1]], [[1, 0], [0, 1]], [[0, 1], [1, 0]]], dtype=torch.bool
    )  # first two -> class 0, last two -> class 1
    y = torch.randint(0, 2, (n,), generator=g)
    variant = torch.randint(0, 2, (n,), generator=g)
    which = y * 2 + variant
    py = torch.randint(0, size - 1, (n,), generator=g)
    px = torch.randint(0, size - 1, (n,), generator=g)
    x = torch.randint(0, 2, (n, 1, size, size), generator=g).bool()
    ar = torch.arange(n)

    def stamp(imgs: Tensor, idx: Tensor) -> None:
        pat = patterns[which[idx]]  # (k, 2, 2)
        for dy in range(2):
            for dx in range(2):
                imgs[idx, 0, py[idx] + dy, px[idx] + dx] = pat[:, dy, dx]

    def ambiguous(imgs: Tensor) -> Tensor:
        win = imgs[:, 0].unfold(1, 2, 1).unfold(2, 2, 1)  # (n, size-1, size-1, 2, 2)
        hit = torch.zeros(imgs.shape[0], size - 1, size - 1, dtype=torch.bool)
        for pat in patterns:
            hit |= (win == pat).all(dim=-1).all(dim=-1)
        hit[ar, py, px] = False  # the placed patch is allowed
        return hit.any(dim=(1, 2))

    stamp(x, ar)
    bad = ambiguous(x)
    tries = 0
    while bool(bad.any()) and tries < max_tries:
        idx = torch.nonzero(bad).flatten()
        x[idx] = torch.randint(0, 2, (idx.numel(), 1, size, size), generator=g).bool()
        stamp(x, idx)
        bad = ambiguous(x)
        tries += 1
    if noise > 0:
        flip = torch.rand(n, generator=g) < noise
        y = torch.where(flip, 1 - y, y)
    dev = torch.device(device) if device else None
    return (x.to(dev), y.long().to(dev)) if dev else (x, y.long())

make_shapes

make_shapes(n: int, size: int = 8, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

Toy image classification: a hollow 3x3 circle (class 0) or a 3x3 cross (class 1) at a random position in a size x size image (Chapter 4 of the Tsetlin machine book). Returns (n, 1, size, size) Boolean images and labels.

Source code in src/torchtsetlin/datasets/synthetic.py
def make_shapes(n: int, size: int = 8, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]:
    """Toy image classification: a hollow ``3x3`` circle (class 0) or a ``3x3`` cross (class 1)
    at a random position in a ``size x size`` image (Chapter 4 of the Tsetlin machine book).
    Returns ``(n, 1, size, size)`` Boolean images and labels."""
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    x = torch.zeros(n, 1, size, size, dtype=torch.bool)
    y = torch.randint(0, 2, (n,), generator=g)
    circle = torch.tensor([[0, 1, 0], [1, 0, 1], [0, 1, 0]], dtype=torch.bool)
    cross = torch.tensor([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=torch.bool)
    py = torch.randint(0, size - 2, (n,), generator=g)
    px = torch.randint(0, size - 2, (n,), generator=g)
    for i in range(n):
        x[i, 0, py[i] : py[i] + 3, px[i] : px[i] + 3] = cross if y[i] == 1 else circle
    dev = torch.device(device) if device else None
    return (x.to(dev), y.long().to(dev)) if dev else (x, y.long())

make_3d_shapes

make_3d_shapes(n: int, size: Tuple[int, int, int] = (8, 12, 12), seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

Toy volume classification that needs depth context: a 3x3x3 shape at a random position in a (D, H, W) volume.

Class 0 (spindle) stacks the 2D slices plus, dot, plus; class 1 (3D cross) stacks dot, plus, dot. Every single slice therefore looks the same in both classes (a plus or a dot) — only their order along depth tells them apart, which a 3D window with kd = 3 sees in one clause.

Returns (n, 1, D, H, W) Boolean volumes and labels.

Source code in src/torchtsetlin/datasets/synthetic.py
def make_3d_shapes(
    n: int, size: Tuple[int, int, int] = (8, 12, 12), seed: Optional[int] = 0, device=None
) -> Tuple[Tensor, Tensor]:
    """Toy volume classification that needs depth context: a ``3x3x3`` shape at a random
    position in a ``(D, H, W)`` volume.

    Class 0 (*spindle*) stacks the 2D slices ``plus, dot, plus``; class 1 (*3D cross*) stacks
    ``dot, plus, dot``. Every single slice therefore looks the same in both classes (a plus
    or a dot) — only their order along depth tells them apart, which a 3D window with
    ``kd = 3`` sees in one clause.

    Returns ``(n, 1, D, H, W)`` Boolean volumes and labels."""
    D, H, W = (int(v) for v in size)
    if min(D, H, W) < 3:
        raise ValueError("every side of the volume must be at least 3")
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    x = torch.zeros(n, 1, D, H, W, dtype=torch.bool)
    y = torch.randint(0, 2, (n,), generator=g)
    plus = torch.tensor([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=torch.bool)
    dot = torch.tensor([[0, 0, 0], [0, 1, 0], [0, 0, 0]], dtype=torch.bool)
    spindle = torch.stack([plus, dot, plus])
    cross3d = torch.stack([dot, plus, dot])
    pd = torch.randint(0, D - 2, (n,), generator=g)
    py = torch.randint(0, H - 2, (n,), generator=g)
    px = torch.randint(0, W - 2, (n,), generator=g)
    for i in range(n):
        x[i, 0, pd[i] : pd[i] + 3, py[i] : py[i] + 3, px[i] : px[i] + 3] = (
            cross3d if y[i] == 1 else spindle
        )
    dev = torch.device(device) if device else None
    return (x.to(dev), y.long().to(dev)) if dev else (x, y.long())

make_segmentation_shapes

make_segmentation_shapes(n: int, size: int = 16, seed: Optional[int] = 0, device=None) -> Tuple[Tensor, Tensor]

Toy dense-prediction task: label every pixel background / disc / ring.

Two solid discs and two rings of radius 2-3 are stamped into a size x size Boolean image. Disc interiors and ring interiors look identical on their own, so the classes are only separable from a pixel's neighbourhood — which is exactly what a dense Tsetlin machine gets to see, and what a per-pixel lookup cannot solve.

Returns (n, 1, size, size) Boolean images and (n, size, size) long label maps with classes 0 = background, 1 = disc, 2 = ring.

Source code in src/torchtsetlin/datasets/synthetic.py
def make_segmentation_shapes(
    n: int, size: int = 16, seed: Optional[int] = 0, device=None
) -> Tuple[Tensor, Tensor]:
    """Toy dense-prediction task: label every pixel ``background`` / ``disc`` / ``ring``.

    Two solid discs and two rings of radius 2-3 are stamped into a ``size x size`` Boolean
    image. Disc interiors and ring interiors look identical on their own, so the classes are
    only separable from a pixel's *neighbourhood* — which is exactly what a dense Tsetlin
    machine gets to see, and what a per-pixel lookup cannot solve.

    Returns ``(n, 1, size, size)`` Boolean images and ``(n, size, size)`` long label maps
    with classes ``0 = background, 1 = disc, 2 = ring``.
    """
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    x = torch.zeros(n, 1, size, size, dtype=torch.bool)
    y = torch.zeros(n, size, size, dtype=torch.long)
    yy, xx = torch.meshgrid(torch.arange(size), torch.arange(size), indexing="ij")
    for i in range(n):
        for cls in (1, 2):
            for _ in range(2):
                r = int(torch.randint(2, 4, (1,), generator=g))
                cy = int(torch.randint(r + 1, size - r - 1, (1,), generator=g))
                cx = int(torch.randint(r + 1, size - r - 1, (1,), generator=g))
                d2 = (yy - cy) ** 2 + (xx - cx) ** 2
                solid = d2 <= r * r
                shape = solid if cls == 1 else (solid & (d2 > (r - 1) ** 2))
                x[i, 0] |= shape
                y[i][solid] = cls
    dev = torch.device(device) if device else None
    return (x.to(dev), y.to(dev)) if dev else (x, y)

make_scenes

make_scenes(n: int, size: Union[int, Tuple[int, int]] = 32, seed: Optional[int] = 0, device: Optional[Union[str, device]] = None) -> Tuple[Tensor, Tensor]

Synthetic CamVid-like street scenes for semantic segmentation.

Generates the properties that make CamVid hard rather than the photographs themselves (which are not redistributable): a wavy horizon, a large contiguous sky, buildings standing on the horizon, trees, and a road, with per-class texture (window grids, foliage noise, lane markings) and a global illumination jitter so that the classes are not separable by colour alone. Class frequencies are heavily imbalanced, as in CamVid.

Parameters:

Name Type Description Default
n int

number of scenes.

required
size Union[int, Tuple[int, int]]

H or (H, W).

32
seed Optional[int]

RNG seed (None = unseeded).

0
device Optional[Union[str, device]]

device for the returned tensors.

None

Returns:

Type Description
Tensor

(rgb, labels) with rgb float (n, 3, H, W) in [0, 1] and labels

Tensor

long (n, H, W) indexing :data:SCENE_CLASSES

Tuple[Tensor, Tensor]

(0 = sky, 1 = building, 2 = tree, 3 = road).

Booleanize the images before handing them to a model, for example with :class:~torchtsetlin.data.ColorThermometerEncoder, which keeps the ordering between intensity levels that a plain threshold would throw away.

Source code in src/torchtsetlin/datasets/synthetic.py
def make_scenes(
    n: int,
    size: Union[int, Tuple[int, int]] = 32,
    seed: Optional[int] = 0,
    device: Optional[Union[str, torch.device]] = None,
) -> Tuple[Tensor, Tensor]:
    """Synthetic CamVid-like street scenes for semantic segmentation.

    Generates the properties that make CamVid hard rather than the photographs themselves
    (which are not redistributable): a wavy **horizon**, a large contiguous **sky**,
    **buildings** standing on the horizon, **trees**, and a **road**, with per-class texture
    (window grids, foliage noise, lane markings) and a global illumination jitter so that the
    classes are not separable by colour alone. Class frequencies are heavily imbalanced, as
    in CamVid.

    Args:
        n: number of scenes.
        size: ``H`` or ``(H, W)``.
        seed: RNG seed (``None`` = unseeded).
        device: device for the returned tensors.

    Returns:
        ``(rgb, labels)`` with ``rgb`` float ``(n, 3, H, W)`` in ``[0, 1]`` and ``labels``
        long ``(n, H, W)`` indexing :data:`SCENE_CLASSES`
        (``0 = sky, 1 = building, 2 = tree, 3 = road``).

    Booleanize the images before handing them to a model, for example with
    :class:`~torchtsetlin.data.ColorThermometerEncoder`, which keeps the ordering between
    intensity levels that a plain threshold would throw away.
    """
    SKY, BUILDING, TREE, ROAD = 0, 1, 2, 3
    H, W = (size, size) if isinstance(size, int) else (int(size[0]), int(size[1]))
    if H < 12 or W < 12:
        raise ValueError("scenes need to be at least 12x12")
    g = torch.Generator().manual_seed(seed) if seed is not None else None
    rgb = torch.zeros(n, 3, H, W)
    lab = torch.full((n, H, W), ROAD, dtype=torch.long)
    xs = torch.arange(W).float()
    rows = torch.arange(H).unsqueeze(1)
    base = {
        SKY: (120, 160, 215),
        BUILDING: (150, 145, 135),
        TREE: (70, 120, 65),
        ROAD: (95, 95, 100),
    }
    two_pi = 2 * math.pi

    def rint(lo: int, hi: int) -> int:
        return int(torch.randint(lo, max(lo + 1, hi), (1,), generator=g))

    for i in range(n):
        h0 = rint(H // 3, H // 2)
        amp = float(torch.rand(1, generator=g)) * 2.0
        phase = float(torch.rand(1, generator=g)) * two_pi
        horizon = (h0 + amp * torch.sin(xs / W * two_pi + phase)).round().long().clamp(2, H - 4)
        lab[i] = torch.where(rows < horizon.unsqueeze(0), SKY, ROAD)

        for cls, count, wlo, whi, hlo, hhi in (
            (BUILDING, rint(1, 4), 3, 9, 4, 12),
            (TREE, rint(0, 3), 3, 6, 4, 9),
        ):
            for _ in range(count):
                bw = rint(wlo, whi)
                bx = rint(0, max(1, W - bw))
                bh = rint(hlo, hhi)
                top = max(0, int(horizon[bx : bx + bw].min()) - bh)
                lab[i, top : int(horizon[bx : bx + bw].max()), bx : bx + bw] = cls

        for c, col in base.items():
            m = lab[i] == c
            for ch in range(3):
                rgb[i, ch][m] = col[ch]
        win = (torch.arange(H).view(-1, 1) % 3 == 0) & (torch.arange(W).view(1, -1) % 3 == 0)
        rgb[i][:, (lab[i] == BUILDING) & win] -= 45  # windows
        foliage = lab[i] == TREE
        if bool(foliage.any()):
            rgb[i][:, foliage] += torch.randn(3, int(foliage.sum()), generator=g) * 28
        lane = (
            (lab[i] == ROAD)
            & (torch.arange(W).view(1, -1) % 7 < 2)
            & (torch.arange(H).view(-1, 1) > H * 0.75)
        )
        rgb[i][:, lane] += 40  # lane markings
        rgb[i] += torch.randn(3, H, W, generator=g) * 10
        rgb[i] += float(torch.randn(1, generator=g)) * 18  # illumination
    rgb = rgb.clamp(0, 255) / 255.0
    dev = torch.device(device) if device else None
    return (rgb.to(dev), lab.to(dev)) if dev else (rgb, lab)