Sodoku_Puzzle_Generator / MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py
MartialTerran's picture
Upload 2 files
1bd97e4 verified
# MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py
"""
What This Script Demonstrates
The script proves that a very simple, 2-layer neural network can achieve 100% accuracy on this task with zero "violations."
This result is important because it provides a baseline for evaluating more sophisticated models on more complex problems like Sudoku. It shows that the ability to avoid predicting one value that is already present in the immediate context is a trivial task for an NN.
MLP Anti-Target Avoidance Demo
This Python script serves as a "control experiment" to demonstrate a fundamental capability of neural networks in constraint satisfaction problems.
The Core Concept: Anti-Target Avoidance
Imagine a simple puzzle: you are shown 8 unique digits from 1-9, and you must identify the single missing digit.
[1, 2, 3, 4, 5, 6, 7, 8] -> ?
"By process of elimination", the answer is obviously 9. The 8 digits you can SEE are "anti-targets"—they are guaranteed to be incorrect answers.
This script tests whether a simple Multi-Layer Perceptron (MLP) can learn this rule.
What This Script Demonstrates
The script proves that a very simple, 2-layer neural network can achieve 100% accuracy on this task with near-zero "anti-target violations."
This result is important because it provides a baseline for evaluating more sophisticated models on more complex problems like Sudoku. It shows that the ability to avoid predicting a value that is already present in the immediate context is a trivial task for an NN.
How It Works
The script is broken down into five clear steps:
Synthetic Data Generation: It creates a dataset of 50,000 samples. Each sample is a permutation of digits 1-9, with one randomly chosen to be the "empty" cell (the label) and the other 8 to be the input. The 8 input digits are one-hot encoded into a flat vector of size 8 * 9 = 72.
The Model: A simple SimpleMLP class defines a 2-layer neural network with a single 128-unit hidden layer. This intentionally minimalist architecture highlights how little capacity is needed to solve the problem.
Training: The model is trained for 5 epochs using a standard Adam optimizer and Cross-Entropy Loss.
Evaluation: After training, the model is evaluated against a validation set. The script calculates two key metrics:
Validation Accuracy: The percentage of times the model correctly predicted the missing digit.
Anti-Target Avoidance Rate: The percentage of times the model's prediction was not one of the 8 input digits. This should be 100%.
Visualization: The script generates a summary image (MLP_Report.png) showing 5 examples from the validation set, visualizing the input clues, the correct answer, and the model's prediction with clear color-coding (green for correct, red for incorrect).
Run the script:
python mlp_anti_target_demo.py
Expected Output
You will see a final report printed to your console:
>python MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py
load libraries
done loading libraries
Generating synthetic 1x9 data...
Generated 50000 samples.
Input shape: torch.Size([50000, 72])
--- Training MLP ---
--- Evaluating MLP ---
--- Generating Visual Report ---
=====================================================
MLP Anti-Target Avoidance Experiment
=====================================================
Model: 2-Layer MLP (128 hidden units)
Training Samples: 40,000
Validation Samples: 10,000
Epochs: 5
-----------------------------------------------------
Validation Accuracy: 100.0000%
Anti-Target Violations: 0
Total Validation Predictions: 10,000
Anti-Target Avoidance Rate: 100.0000%
=====================================================
Visual report saved to: mlp_demo_images\MLP_Report.png
"""
print("load libraries")
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import TensorDataset, DataLoader
import numpy as np
import matplotlib.pyplot as plt
import os
import itertools
from tqdm import tqdm
print("done loading libraries")
# --- Configuration ---
NUM_SAMPLES = 50000
BATCH_SIZE = 256
EPOCHS = 5
LR = 0.001
IMG_DIR = "mlp_demo_images"
os.makedirs(IMG_DIR, exist_ok=True)
# --- 1. Generate Synthetic Data ---
print("Generating synthetic 1x9 data...")
digits = np.arange(1, 10)
all_permutations = list(itertools.permutations(digits))
chosen_perms = [all_permutations[i] for i in np.random.choice(len(all_permutations), NUM_SAMPLES, replace=True)]
inputs = []
labels = []
anti_targets_list = []
for p in chosen_perms:
p = np.array(p)
empty_idx = np.random.randint(0, 9)
label = p[empty_idx] - 1 # 0-8 for classes
input_digits = np.delete(p, empty_idx)
anti_targets_list.append(input_digits) # Store the actual digits 1-9
# One-hot encode the 8 input digits and flatten
one_hot_input = np.zeros((8, 9))
one_hot_input[np.arange(8), input_digits - 1] = 1
inputs.append(one_hot_input.flatten())
labels.append(label)
X = torch.FloatTensor(np.array(inputs))
y = torch.LongTensor(np.array(labels))
anti_targets_tensor = torch.LongTensor(np.array(anti_targets_list))
dataset = TensorDataset(X, y, anti_targets_tensor)
train_size = int(0.8 * len(dataset))
val_size = len(dataset) - train_size
train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE)
print(f"Generated {len(dataset)} samples.")
print(f"Input shape: {X.shape}")
# --- 2. Define Simple MLP ---
class SimpleMLP(nn.Module):
def __init__(self):
super(SimpleMLP, self).__init__()
self.layer1 = nn.Linear(8 * 9, 128) # 8 positions * 9 one-hot digits
self.relu = nn.ReLU()
self.layer2 = nn.Linear(128, 9) # 9 possible output digits
def forward(self, x):
return self.layer2(self.relu(self.layer1(x)))
model = SimpleMLP()
# --- 3. Train the Model ---
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LR)
print("\n--- Training MLP ---")
for epoch in range(EPOCHS):
model.train()
for batch_X, batch_y, _ in tqdm(train_loader, desc=f"Epoch {epoch+1}/{EPOCHS}", leave=False):
optimizer.zero_grad()
outputs = model(batch_X)
loss = criterion(outputs, batch_y)
loss.backward()
optimizer.step()
# --- 4. Evaluate the Model ---
print("\n--- Evaluating MLP ---")
model.eval()
total = 0
correct = 0
anti_target_violations = 0
with torch.no_grad():
for batch_X, batch_y, batch_ats in val_loader:
outputs = model(batch_X)
_, predicted = torch.max(outputs.data, 1)
total += batch_y.size(0)
correct += (predicted == batch_y).sum().item()
# Check for anti-target violations
for i in range(len(predicted)):
prediction_val = predicted[i].item() + 1 # Convert back to 1-9
anti_targets = batch_ats[i].tolist()
if prediction_val in anti_targets:
anti_target_violations += 1
accuracy = 100 * correct / total
at_avoidance_rate = 100 * (total - anti_target_violations) / total
# --- 5. Generate Visuals ---
print("\n--- Generating Visual Report ---")
(sample_X, sample_y, sample_ats) = val_dataset[0:5]
outputs = model(sample_X)
_, predicted = torch.max(outputs.data, 1)
fig, axes = plt.subplots(5, 1, figsize=(10, 8))
fig.suptitle("MLP Performance on 1x9 Anti-Target Avoidance", fontsize=16)
for i in range(5):
input_digits = sample_ats[i].numpy()
target_digit = sample_y[i].item() + 1
predicted_digit = predicted[i].item() + 1
is_correct = (target_digit == predicted_digit)
is_violation = predicted_digit in input_digits
full_puzzle = np.zeros(9, dtype=int)
empty_idx = np.where(~np.isin(np.arange(1, 10), input_digits))[0][0]
ax = axes[i]
ax.set_xlim(-0.5, 8.5)
ax.set_ylim(-0.5, 1.5)
ax.set_yticks([])
ax.set_xticks(range(9))
ax.set_xticklabels([])
ax.grid(True)
idx_ptr = 0
for j in range(9):
if j == empty_idx:
# Draw predicted digit
color = 'green' if is_correct else 'red'
if is_violation: color = 'orange' # Overrides red
ax.text(j, 0.5, str(predicted_digit), ha='center', va='center', fontsize=18, fontweight='bold', color='white',
bbox=dict(boxstyle="round,pad=0.3", fc=color, ec="black", lw=2))
else:
# Draw clue digit
ax.text(j, 0.5, str(input_digits[idx_ptr]), ha='center', va='center', fontsize=16,
bbox=dict(boxstyle="round,pad=0.3", fc='lightgray', ec="gray"))
idx_ptr += 1
title_text = f"Sample {i+1}: Correct: {target_digit}, Predicted: {predicted_digit} -> {'CORRECT' if is_correct else 'INCORRECT'}"
if is_violation:
title_text += " [ANTI-TARGET VIOLATION!]"
ax.set_title(title_text)
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
report_img_path = os.path.join(IMG_DIR, "MLP_Report.png")
plt.savefig(report_img_path)
plt.close()
# --- Final Report ---
report = f"""
=====================================================
MLP Anti-Target Avoidance Experiment
=====================================================
Model: 2-Layer MLP (128 hidden units)
Training Samples: {train_size:,}
Validation Samples: {val_size:,}
Epochs: {EPOCHS}
-----------------------------------------------------
Validation Accuracy: {accuracy:.4f}%
Anti-Target Violations: {anti_target_violations}
Total Validation Predictions: {total:,}
Anti-Target Avoidance Rate: {at_avoidance_rate:.4f}%
=====================================================
Visual report saved to: {report_img_path}
"""
print(report)