Fuzzy clauses: MNIST with 20 clauses per class¶
An ordinary Tsetlin machine clause is an AND: one included literal that is False switches the clause off. On images that forces a trade. A clause with many literals describes a pattern well but almost never matches a new image, and a clause with few literals matches often but says little. The usual way out is thousands of clauses.
The Fuzzy-Pattern Tsetlin machine (Hnilov, arXiv:2508.08350,
implemented in Tsetlin.jl) changes the clause instead: it
votes max(0, max_failed_literals - failed), where failed counts its included literals that are
False. A long clause then still votes, with less weight, when a few of its literals fail.
This notebook
- shows the clause output on a toy clause,
- trains
FuzzyTsetlinMachinewith 20 clauses per class on MNIST next to the ordinary machine, - looks at what a fuzzy clause contains and how it votes on one image,
- varies
max_failed_literalsand the batch size.
# Setup: on Google Colab this installs torchtsetlin from PyPI (torch, torchvision, matplotlib and
# pandas are already there). Elsewhere: `pip install torchtsetlin`, or `pip install -e ".[dev]"`
# in a checkout of the repository. FuzzyTsetlinMachine needs torchtsetlin 0.8 or newer.
import sys
IN_COLAB = "google.colab" in sys.modules
if IN_COLAB:
%pip install -q "torchtsetlin>=0.8.1"
import time
import matplotlib.pyplot as plt
import pandas as pd
import torch
import torchtsetlin as tt
from torchtsetlin import functional as F
SEED = 0
tt.seed_everything(SEED)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
DATA_ROOT = "data" if IN_COLAB else "../../data" # torchvision downloads here on first run
print("torchtsetlin", tt.__version__, "| torch", torch.__version__, "| device", device)
1. The clause output¶
One clause that includes four literals, x0 AND x1 AND x2 AND x3, and five inputs in which 0 to 4
of those literals are False. The ordinary clause only fires for the first input. The fuzzy clause
with max_failed_literals=3 votes 3, 2, 1 and then 0.
include = torch.zeros(1, 8) # one clause over 4 features: literals [x0..x3 | NOT x0..NOT x3]
include[0, :4] = 1
x = torch.tensor([[1, 1, 1, 1], [1, 1, 1, 0], [1, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 0]]).bool()
literals = F.to_literals(x)
pd.DataFrame({
"literals that fail": (~x).sum(1).tolist(),
"ordinary clause": F.clause_outputs(literals, include).int().view(-1).tolist(),
"fuzzy clause (max_failed_literals=3)": F.fuzzy_clause_outputs(literals, include, 3).int().view(-1).tolist(),
})
2. MNIST: 20 clauses per class¶
MNIST as flat Boolean pixels (pixel > 0.3), resident on the device.
x_train, y_train = tt.data.load_mnist_boolean(DATA_ROOT, train=True, threshold=0.3, device=device, flatten=True)
x_test, y_test = tt.data.load_mnist_boolean(DATA_ROOT, train=False, threshold=0.3, device=device, flatten=True)
print(tuple(x_train.shape), tuple(x_test.shape))
def train(model, epochs, batch_size=50, sequential=False, seed=SEED):
"""Train with plain update() calls; returns the test accuracy after every epoch and the time."""
tt.seed_everything(seed)
model.to(device)
history, t0 = [], time.time()
for _ in range(epochs):
model.train()
perm = torch.randperm(len(y_train), device=device)
for i in range(0, len(perm), batch_size):
idx = perm[i:i + batch_size]
model.update(x_train[idx], y_train[idx], sequential=sequential)
model.eval() # empty clauses do not vote when predicting
history.append(float((model.predict(x_test) == y_test).float().mean()))
return history, time.time() - t0
Three models, the same 15 epochs and batch size:
- the fuzzy machine with 20 clauses per class, at the settings of Tsetlin.jl's MNIST example,
- the ordinary machine with the same 20 clauses per class,
- the ordinary machine with 2 000 clauses per class.
Note the fuzzy machine's s=800. It is only used to forget in clauses that do not match, so
useful values are far larger than the 4 to 10 of the ordinary machine.
EPOCHS = 15
models = {
"fuzzy, 20 clauses per class": tt.FuzzyTsetlinMachine(
784, 10, n_clauses=20, T=16, s=800, max_failed_literals=75, max_included_literals=150),
"ordinary, 20 clauses per class": tt.TsetlinMachine(784, 10, n_clauses=20, T=10, s=10.0),
"ordinary, 2000 clauses per class": tt.TsetlinMachine(784, 10, n_clauses=2000, T=50, s=10.0),
}
rows, curves = [], {}
for name, model in models.items():
curves[name], seconds = train(model, EPOCHS)
rows.append({"model": name, "clauses in total": model.n_clauses_total,
"test accuracy": round(curves[name][-1], 4),
"literals per clause": round(float(model.include_count.float().mean()), 1),
"seconds": round(seconds, 1)})
pd.DataFrame(rows)
fig, ax = plt.subplots(figsize=(6, 3.5))
for name, curve in curves.items():
ax.plot(range(1, EPOCHS + 1), curve, marker="o", ms=3, label=name)
ax.set(xlabel="epoch", ylabel="test accuracy", ylim=(0.4, 1.0))
ax.legend(loc="lower right")
ax.grid(alpha=0.3)
plt.show()
With the same 20 clauses per class the ordinary machine stays far behind: its clauses are strict conjunctions of hundreds of literals and rarely match. The fuzzy machine gets within about one percentage point of the ordinary machine that has a hundred times as many clauses, in a third of the time.
Fifteen epochs are not the end of the curve for the fuzzy model. Trained for 100 epochs at batch 50, the same setting reached 97.5 % against 97.6 % for the ordinary machine with 2 000 clauses per class, and 200 fuzzy clauses per class reached 98.4 % (one seed; see the concept page).
3. What a fuzzy clause contains¶
A clause of the fuzzy model has many more literals than an ordinary one. Below are four
positive clauses of digit 3: green pixels are x literals (the pixel must be inked), red pixels
are NOT x literals (it must be blank).
fuzzy = models["fuzzy, 20 clauses per class"]
mask = fuzzy.included_mask().cpu() # (clauses, 2 * 784)
digit = 3
first = digit * fuzzy.n_clauses # the positive clauses of a class come first
fig, axes = plt.subplots(1, 4, figsize=(9, 2.6))
for ax, j in zip(axes, range(first, first + 4)):
pos, neg = mask[j, :784].view(28, 28).float(), mask[j, 784:].view(28, 28).float()
ax.imshow(torch.stack([neg, pos, torch.zeros(28, 28)], dim=2))
ax.set_title(f"clause {j}: {int(mask[j].sum())} literals", fontsize=9)
ax.axis("off")
plt.show()
explain_clause says what one clause does for one input: which of its literals hold, which fail,
and its vote. The cell below takes a test image of a 3 and lists the positive clauses of class 3.
A clause votes 75 minus the number of its literals that fail, and 0 once 75 or more fail.
i = int((y_test == digit).nonzero()[0])
image = x_test[i]
table = []
for j in range(first, first + fuzzy.n_clauses // 2):
info = fuzzy.explain_clause(image, j)
table.append({"clause": j, "literals that hold": len(info["satisfied"]),
"literals that fail": len(info["failed"]), "vote": info["vote"]})
print("votes per class:", [int(v) for v in fuzzy(image.view(1, -1))[0].tolist()], "| label", int(y_test[i]))
pd.DataFrame(table)
The rules are printed with the tolerance, because a fuzzy clause is not a strict conjunction:
rule = fuzzy.rules(class_index=digit)[0]
print(rule[:160], "...")
4. How much tolerance?¶
max_failed_literals is the new hyper-parameter. With 1 the clause output is the ordinary 0/1
value. Everything else is kept at the setting above, 8 epochs each.
rows = []
for lf in (1, 8, 25, 75, 150):
model = tt.FuzzyTsetlinMachine(784, 10, n_clauses=20, T=16, s=800,
max_failed_literals=lf, max_included_literals=150)
history, _ = train(model, epochs=8)
rows.append({"max_failed_literals": lf, "test accuracy": round(history[-1], 4),
"literals per clause": round(float(model.include_count.float().mean()), 1)})
pd.DataFrame(rows)
With max_failed_literals=1 the model is poor: a strict clause that is allowed up to 150 literals
almost never matches. A small tolerance already recovers most of the accuracy, and from about 25
on the value matters little here. Larger values let the clauses keep more literals.
5. Batch size¶
A batch computes all its feedback from the automata at its start and applies it once. The fuzzy rules move every True literal of a matching clause on every event, so one could expect large batches to overshoot. Three batch sizes with the same number of epochs:
rows = []
for batch_size in (10, 50, 500):
model = tt.FuzzyTsetlinMachine(784, 10, n_clauses=20, T=16, s=800,
max_failed_literals=75, max_included_literals=150)
history, seconds = train(model, epochs=8, batch_size=batch_size)
rows.append({"batch size": batch_size, "updates per epoch": len(y_train) // batch_size,
"test accuracy": round(history[-1], 4), "seconds": round(seconds, 1)})
pd.DataFrame(rows)
After the same number of epochs the larger batches are behind, most clearly at 500: they have made far fewer updates. This is the usual trade between updates and throughput, not a failure of the batched rules. Trained to the end (100 epochs), batch sizes from 10 to 1 000 finished within 0.6 percentage points of the per-example algorithm on MNIST and Fashion-MNIST.
Summary¶
- A fuzzy clause votes
max(0, max_failed_literals - failed). That lets a clause be long and still match inputs that resemble its pattern. - The feedback is changed to fit: on a matching clause Type I moves every True literal towards
inclusion and every excluded False literal away from it with probability 1;
sis only used to forget in clauses that do not match;max_included_literalsis a gate on the inclusion steps. - Few clauses want many literals and a large tolerance (20 clauses: 150 and 75). More clauses
want short, strict ones (200 clauses per class:
T=28, s=200, max_failed_literals=8, max_included_literals=16). - The model is for flat inputs and multi-class classification. Background and measured results: the Fuzzy clauses concept page of the documentation.