Chapter 6: Neuro-Symbolic AI — Implementation
A small neuro-symbolic system: a Sudoku whose clues are handwritten digits. Perception (a classifier, Chapter 8) reads the clues; constraints (Chapter 1’s search over valid grids) solve the puzzle. We compare reading first and reasoning second with deciding both jointly.
import ast, json, itertools, math, operator, os, re, urllib.request
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_digits, load_breast_cancer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
np.set_printoptions(precision=3, suppress=True)A Sudoku with Handwritten Clues¶
A 4×4 Sudoku uses the digits 1–4: each row, column and 2×2 box contains each digit once. Its clues are images of handwritten digits, slightly noisy, as if photographed. A classifier reads them; then we solve.
digits = load_digits()
keep = np.isin(digits.target, [1, 2, 3, 4])
X, y = digits.data[keep] / 16, digits.target[keep]
X_train, X_pool, y_train, y_pool = train_test_split(X, y, test_size=0.5, stratify=y, random_state=0)
reader = LogisticRegression(max_iter=2000).fit(X_train, y_train) # perception: image -> probabilities of 1..4
def valid(grid):
g = np.asarray(grid).reshape(4, 4)
return (all(len(set(r)) == 4 for r in g) and all(len(set(c)) == 4 for c in g.T)
and all(len(set(g[r:r + 2, c:c + 2].ravel())) == 4 for r in (0, 2) for c in (0, 2)))
rows = list(itertools.permutations([1, 2, 3, 4]))
GRIDS = np.array([np.ravel(g) for g in itertools.product(rows, repeat=4) if valid(g)])
print(f'{len(GRIDS)} valid 4x4 Sudoku grids')288 valid 4x4 Sudoku grids
Two ways to solve:
Perception, then reasoning: take the most likely digit of each clue, then find the grid consistent with those digits. One misread clue and the puzzle is wrong or impossible.
Joint: keep the reader’s probabilities, and choose the valid grid that maximises the product of the probabilities of its clue digits: . The constraints can then overrule an uncertain reading.
def make_puzzle(rng, n_clues=8, noise=0.3):
while True: # keep only puzzles with a unique solution
solution = GRIDS[rng.integers(len(GRIDS))]
cells = rng.choice(16, n_clues, replace=False)
if (GRIDS[:, cells] == solution[cells]).all(axis=1).sum() == 1:
break
images = np.array([np.clip(X_pool[rng.choice(np.where(y_pool == solution[c])[0])] + rng.normal(0, noise, 64), 0, 1) for c in cells])
return solution, cells, images
def solve_perception_first(cells, images):
read = reader.classes_[reader.predict_proba(images).argmax(axis=1)]
matches = GRIDS[(GRIDS[:, cells] == read).all(axis=1)]
return matches[0] if len(matches) == 1 else None
def solve_jointly(cells, images):
log_p = np.log(reader.predict_proba(images) + 1e-12) # columns: digits 1..4
scores = log_p[np.arange(len(cells)), GRIDS[:, cells] - 1].sum(axis=1) # one score per valid grid
return GRIDS[scores.argmax()]
rng = np.random.default_rng(0)
solution, cells, images = make_puzzle(rng)
fig, axes = plt.subplots(1, len(cells), figsize=(10, 1.5))
probs = reader.predict_proba(images)
for ax, img, p, c in zip(axes, images, probs, cells):
ax.imshow(img.reshape(8, 8), cmap='gray_r'); ax.axis('off')
ax.set_title(f'cell {c}: true {solution[c]}\nread {reader.classes_[p.argmax()]} ({p.max():.0%})', fontsize=8)
plt.suptitle('The clues as the reader sees them'); plt.tight_layout(); plt.show()
print('solution:\n', solution.reshape(4, 4))
solution:
[[3 2 4 1]
[1 4 2 3]
[4 1 3 2]
[2 3 1 4]]
results = {'clues all read correctly': 0, 'perception, then reasoning': 0, 'joint (probabilities + constraints)': 0}
accuracy = []
rng = np.random.default_rng(1)
N = 300
for _ in range(N):
solution, cells, images = make_puzzle(rng)
read = reader.classes_[reader.predict_proba(images).argmax(axis=1)]
accuracy.append(np.mean(read == solution[cells]))
results['clues all read correctly'] += np.all(read == solution[cells])
s1 = solve_perception_first(cells, images)
results['perception, then reasoning'] += s1 is not None and np.array_equal(s1, solution)
results['joint (probabilities + constraints)'] += np.array_equal(solve_jointly(cells, images), solution)
print(f'digit reading accuracy: {np.mean(accuracy):.1%}')
for k, v in results.items():
print(f'{k:38} {v / N:.0%} of {N} puzzles')digit reading accuracy: 93.5%
clues all read correctly 59% of 300 puzzles
perception, then reasoning 59% of 300 puzzles
joint (probabilities + constraints) 95% of 300 puzzles
Each clue is read correctly about 93% of the time, but with 8 clues per puzzle about 4 puzzles in 10 contain at least one misread clue, and perception-then-reasoning fails on every one of them. Keeping the uncertainty and letting the constraints decide solves the large majority. This is the core neuro-symbolic lesson: neither part alone does as well as the two together.
Summary¶
Reading each clue on its own and then reasoning fails whenever a single clue is misread.
Keeping the classifier’s probabilities and choosing the valid grid that maximises them lets the constraints correct uncertain readings.