Skip to content

Preparing data

A Tsetlin machine reads Boolean features, so most of the data work is turning your values into bits. Two namespaces cover it:

Namespace What it holds Use it when
tt.datasets the data itself: generators, torchvision loaders, benchmark datasets that download on first use you want a ready-made dataset
tt.data operations on data: Booleanization encoders, splits, dataset wrappers you bring your own data

Whatever the source, the result is the same pair that every model accepts:

Shape dtype
x for flat models (N, n_features) torch.bool
x for convolutional models (N, C, H, W) torch.bool
y for classification (N,) integers 0..n_classes-1

Models coerce their input: 0/1 integers, NumPy arrays and floats are accepted, and a float counts as True when it is above 0.5. Raw measurements therefore need an explicit encoding (steps 2 and 3 below), because the coercion would keep only one bit of each value.

1. Ready-made datasets: tt.datasets

Generators return Boolean tensors directly and are the fastest way to try a model:

import torch, torchtsetlin as tt

x, y = tt.datasets.make_noisy_xor(5000, noise=0.4, seed=0)   # (5000, 12) bool, (5000,) long
xi, yi = tt.datasets.make_2d_noisy_xor(2000, size=4)         # (2000, 1, 4, 4) images

Benchmark datasets follow the torchvision pattern: download=True fetches the files once, later uses read the local cache.

train = tt.datasets.MagicTelescope(root="./data", train=True, download=True)
test = tt.datasets.MagicTelescope(root="./data", train=False)

x_train, y_train = train.tensors()        # (15216, 100) bool, (15216,) long
train.n_features, train.n_classes         # 100, 2

These two lines already Booleanize. The raw table has 10 numeric columns (train.data, (15216, 10) floats), and the loader applies the encoding of the paper the benchmark comes from: every column is cut into 10 equal-frequency bins and each bin becomes one Boolean, so 10 columns give 100 features.

train.feature_names[:2]     # ['fLength in [-inf, 19.16)', 'fLength in [19.16, 22.32)']
train.encoder               # the fitted QuantileOneHotEncoder

The bin edges are computed on the training split and reused for train=False, so a bit means the same thing in both splits. Every benchmark dataset works this way, each with its own default (thresholded pixels for the image datasets, word-presence bits for the text ones); the benchmark datasets guide lists them.

Default encoding or your own?

You have three options, from least to most control:

D = tt.datasets.MagicTelescope

D(root)                                              # 1. default: 10 quantile bins, one-hot
D(root, n_bins=20)                                   #    same encoding, finer: (15216, 200)
D(root, encoder=tt.data.ThermometerEncoder(8))       # 2. your encoder:     (15216, 80)
D(root, booleanize=False)                            # 3. raw floats:       (15216, 10)
Default (encoder=None) Your own (encoder=...) Raw (booleanize=False)
What x holds the published encoding the output of your encoder the unencoded values
Who fits it the loader, on the training split the loader fits a copy of your encoder on the training split you, on train.x
Feature names "fLength in [19.16, 22.32)" from your encoder, e.g. "fLength>=19.56" the column names
Same input as the published benchmark yes (the paper's preprocessing) no, the representation changed no
Use it for reproducing a benchmark, a first baseline testing whether another encoding learns better or reads better encodings a single encoder cannot express, e.g. a different one per column

The encoding changes what a clause can say. With the default one-hot bins, a literal is one interval (fLength in [19.16, 22.32)), and a wider range needs several negated literals. With a thermometer, a literal is an inequality (fLength>=19.56), and any range is two literals. Neither is better in general: it is a modelling decision, which is why it is exposed.

With encoder=, pass the same encoder to both splits. The loader fits its own copy on the training split each time, so both splits get identical thresholds and your object stays unfitted:

enc = tt.data.ThermometerEncoder(8)
train = D(root, encoder=enc)
test = D(root, train=False, encoder=enc)      # thresholds from the training split
train.encoder.is_fitted, enc.is_fitted        # (True, False)

With booleanize=False nothing is fitted for you: fit your encoder on the training split's x and apply it to both, exactly as in step 2 below.

Image loaders Booleanize a torchvision dataset into memory (they need the vision extra):

x_train, y_train = tt.datasets.load_mnist_boolean("./data", train=True)                 # (60000, 1, 28, 28)
x_flat, _ = tt.datasets.load_mnist_boolean("./data", train=True, flatten=True)          # (60000, 784)

load_mnist_boolean thresholds at pixel > 0.3 by default and takes encoder= or threshold= in the same way.

2. Your own data: encode it with tt.data

Encoders follow the scikit-learn protocol (fit, transform, or call the encoder). The usual choices are:

Your values Encoder Bits per input
continuous columns ThermometerEncoder(n_bits) n_bits (v >= t_1, ..., v >= t_n)
continuous columns, as bins QuantileOneHotEncoder(n_bins) n_bins
categories (integer codes) OneHotEncoder() one per category
grayscale images Binarizer(threshold) or AdaptiveThresholdEncoder() 1 per pixel
colour images ColorThermometerEncoder(n_bits) n_bits per channel
token ids (text) HypervectorEncoder(vocab_size, dim) dim per document

A complete tabular example with a stratified split:

x_raw = torch.randn(1000, 5)                   # your float features, (N, F)
labels = (x_raw[:, 0] + x_raw[:, 1] > 0).long()
columns = ["age", "bmi", "pulse", "sys", "dia"]

train_idx, test_idx = tt.data.stratified_split(labels, test_size=0.2, seed=0)

enc = tt.data.ThermometerEncoder(n_bits=8).fit(x_raw[train_idx])   # thresholds from train only
x_train, y_train = enc(x_raw[train_idx]), labels[train_idx]        # (800, 40) bool
x_test, y_test = enc(x_raw[test_idx]), labels[test_idx]            # same thresholds

model = tt.TsetlinMachine(n_features=x_train.shape[1], n_classes=2, n_clauses=40, T=15, s=3.9)
model.feature_names = enc.feature_names(columns)                   # rules read "age>=0.31"

Fit on the training split only

Fit the encoder on the training rows and reuse it for validation and test data. Fitting on everything leaks the test distribution into the thresholds, and fitting a second encoder on the test split gives the same bit a different meaning in each split.

Encoders are nn.Modules: save the fitted thresholds with enc.state_dict() next to the model, and chain several with tt.data.Compose. Images work the same way:

images = torch.rand(100, 3, 32, 32) * 255                   # (N, 3, H, W), values 0..255
xb = tt.data.ColorThermometerEncoder(n_bits=4)(images)      # (100, 12, 32, 32) bool

Booleanization explains each encoder and how to choose one.

3. Hand the data to a model

Tensors that fit in memory are the simplest and the fastest input. The Trainer shuffles and batches them itself:

trainer = tt.Trainer(model, batch_size=10)
trainer.fit((x_train, y_train), epochs=20, val_data=(x_test, y_test))

tt.data.BooleanTensorDataset wraps arrays as a Dataset with the right dtypes, on one device (pass regression=True for float targets):

ds = tt.data.BooleanTensorDataset(x_train, y_train, device=model.ta_state.device)
trainer.fit(ds, epochs=20)

For data that does not fit in memory, keep any PyTorch Dataset and encode each sample as it is read with tt.data.TransformDataset, optionally behind your own DataLoader:

from torch.utils.data import DataLoader, TensorDataset

raw = TensorDataset(x_raw[train_idx], labels[train_idx])            # any Dataset of (x, y)
lazy = tt.data.TransformDataset(raw, transform=lambda v: enc(v[None])[0])
trainer.fit(DataLoader(lazy, batch_size=10, shuffle=True), epochs=20)

The transform receives one sample without a batch dimension, hence v[None] and [0].

Encode on the CPU, train on the GPU

Encoders keep their thresholds on the device they were fitted on. Encode first, then move the Boolean result: x_train = enc(x_raw).to("cuda"). A Boolean dataset is small (1 byte per feature), so it usually fits on the GPU whole. See Choosing a device.

Checklist

  • x is Boolean with the shape the model expects, and y holds integers 0..n_classes-1.
  • The encoder was fitted on the training split and reused for every other split.
  • n_features of the model equals x.shape[1] after encoding (or pass n_features=None to infer it from the first batch).
  • model.feature_names is set, so rules print in your own units.

Other targets have their own guides: regression and multi-label, semantic segmentation and graph input.