MartialTerran commited on
Commit
1bd97e4
·
verified ·
1 Parent(s): 11618f1

Upload 2 files

Browse files
MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py ADDED
@@ -0,0 +1,256 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py
2
+
3
+ """
4
+ What This Script Demonstrates
5
+ The script proves that a very simple, 2-layer neural network can achieve 100% accuracy on this task with zero "violations."
6
+
7
+ 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.
8
+
9
+ MLP Anti-Target Avoidance Demo
10
+ This Python script serves as a "control experiment" to demonstrate a fundamental capability of neural networks in constraint satisfaction problems.
11
+
12
+ The Core Concept: Anti-Target Avoidance
13
+ Imagine a simple puzzle: you are shown 8 unique digits from 1-9, and you must identify the single missing digit.
14
+ [1, 2, 3, 4, 5, 6, 7, 8] -> ?
15
+ "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.
16
+
17
+ This script tests whether a simple Multi-Layer Perceptron (MLP) can learn this rule.
18
+
19
+ What This Script Demonstrates
20
+ The script proves that a very simple, 2-layer neural network can achieve 100% accuracy on this task with near-zero "anti-target violations."
21
+ 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.
22
+
23
+
24
+ How It Works
25
+ The script is broken down into five clear steps:
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ Training: The model is trained for 5 epochs using a standard Adam optimizer and Cross-Entropy Loss.
32
+ Evaluation: After training, the model is evaluated against a validation set. The script calculates two key metrics:
33
+
34
+ Validation Accuracy: The percentage of times the model correctly predicted the missing digit.
35
+ Anti-Target Avoidance Rate: The percentage of times the model's prediction was not one of the 8 input digits. This should be 100%.
36
+
37
+ 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).
38
+
39
+ Run the script:
40
+ python mlp_anti_target_demo.py
41
+
42
+
43
+ Expected Output
44
+ You will see a final report printed to your console:
45
+
46
+ >python MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py
47
+ load libraries
48
+ done loading libraries
49
+ Generating synthetic 1x9 data...
50
+ Generated 50000 samples.
51
+ Input shape: torch.Size([50000, 72])
52
+
53
+ --- Training MLP ---
54
+
55
+ --- Evaluating MLP ---
56
+
57
+ --- Generating Visual Report ---
58
+
59
+ =====================================================
60
+ MLP Anti-Target Avoidance Experiment
61
+ =====================================================
62
+ Model: 2-Layer MLP (128 hidden units)
63
+ Training Samples: 40,000
64
+ Validation Samples: 10,000
65
+ Epochs: 5
66
+ -----------------------------------------------------
67
+ Validation Accuracy: 100.0000%
68
+ Anti-Target Violations: 0
69
+ Total Validation Predictions: 10,000
70
+ Anti-Target Avoidance Rate: 100.0000%
71
+ =====================================================
72
+ Visual report saved to: mlp_demo_images\MLP_Report.png
73
+
74
+ """
75
+
76
+ print("load libraries")
77
+ import torch
78
+ import torch.nn as nn
79
+ import torch.optim as optim
80
+ from torch.utils.data import TensorDataset, DataLoader
81
+ import numpy as np
82
+ import matplotlib.pyplot as plt
83
+ import os
84
+ import itertools
85
+ from tqdm import tqdm
86
+ print("done loading libraries")
87
+
88
+ # --- Configuration ---
89
+ NUM_SAMPLES = 50000
90
+ BATCH_SIZE = 256
91
+ EPOCHS = 5
92
+ LR = 0.001
93
+ IMG_DIR = "mlp_demo_images"
94
+ os.makedirs(IMG_DIR, exist_ok=True)
95
+
96
+ # --- 1. Generate Synthetic Data ---
97
+ print("Generating synthetic 1x9 data...")
98
+ digits = np.arange(1, 10)
99
+ all_permutations = list(itertools.permutations(digits))
100
+ chosen_perms = [all_permutations[i] for i in np.random.choice(len(all_permutations), NUM_SAMPLES, replace=True)]
101
+
102
+ inputs = []
103
+ labels = []
104
+ anti_targets_list = []
105
+
106
+ for p in chosen_perms:
107
+ p = np.array(p)
108
+ empty_idx = np.random.randint(0, 9)
109
+ label = p[empty_idx] - 1 # 0-8 for classes
110
+
111
+ input_digits = np.delete(p, empty_idx)
112
+ anti_targets_list.append(input_digits) # Store the actual digits 1-9
113
+
114
+ # One-hot encode the 8 input digits and flatten
115
+ one_hot_input = np.zeros((8, 9))
116
+ one_hot_input[np.arange(8), input_digits - 1] = 1
117
+ inputs.append(one_hot_input.flatten())
118
+ labels.append(label)
119
+
120
+ X = torch.FloatTensor(np.array(inputs))
121
+ y = torch.LongTensor(np.array(labels))
122
+ anti_targets_tensor = torch.LongTensor(np.array(anti_targets_list))
123
+
124
+ dataset = TensorDataset(X, y, anti_targets_tensor)
125
+ train_size = int(0.8 * len(dataset))
126
+ val_size = len(dataset) - train_size
127
+ train_dataset, val_dataset = torch.utils.data.random_split(dataset, [train_size, val_size])
128
+
129
+ train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
130
+ val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE)
131
+
132
+ print(f"Generated {len(dataset)} samples.")
133
+ print(f"Input shape: {X.shape}")
134
+
135
+ # --- 2. Define Simple MLP ---
136
+ class SimpleMLP(nn.Module):
137
+ def __init__(self):
138
+ super(SimpleMLP, self).__init__()
139
+ self.layer1 = nn.Linear(8 * 9, 128) # 8 positions * 9 one-hot digits
140
+ self.relu = nn.ReLU()
141
+ self.layer2 = nn.Linear(128, 9) # 9 possible output digits
142
+
143
+ def forward(self, x):
144
+ return self.layer2(self.relu(self.layer1(x)))
145
+
146
+ model = SimpleMLP()
147
+
148
+ # --- 3. Train the Model ---
149
+ criterion = nn.CrossEntropyLoss()
150
+ optimizer = optim.Adam(model.parameters(), lr=LR)
151
+
152
+ print("\n--- Training MLP ---")
153
+ for epoch in range(EPOCHS):
154
+ model.train()
155
+ for batch_X, batch_y, _ in tqdm(train_loader, desc=f"Epoch {epoch+1}/{EPOCHS}", leave=False):
156
+ optimizer.zero_grad()
157
+ outputs = model(batch_X)
158
+ loss = criterion(outputs, batch_y)
159
+ loss.backward()
160
+ optimizer.step()
161
+
162
+ # --- 4. Evaluate the Model ---
163
+ print("\n--- Evaluating MLP ---")
164
+ model.eval()
165
+ total = 0
166
+ correct = 0
167
+ anti_target_violations = 0
168
+
169
+ with torch.no_grad():
170
+ for batch_X, batch_y, batch_ats in val_loader:
171
+ outputs = model(batch_X)
172
+ _, predicted = torch.max(outputs.data, 1)
173
+
174
+ total += batch_y.size(0)
175
+ correct += (predicted == batch_y).sum().item()
176
+
177
+ # Check for anti-target violations
178
+ for i in range(len(predicted)):
179
+ prediction_val = predicted[i].item() + 1 # Convert back to 1-9
180
+ anti_targets = batch_ats[i].tolist()
181
+ if prediction_val in anti_targets:
182
+ anti_target_violations += 1
183
+
184
+ accuracy = 100 * correct / total
185
+ at_avoidance_rate = 100 * (total - anti_target_violations) / total
186
+
187
+ # --- 5. Generate Visuals ---
188
+ print("\n--- Generating Visual Report ---")
189
+ (sample_X, sample_y, sample_ats) = val_dataset[0:5]
190
+ outputs = model(sample_X)
191
+ _, predicted = torch.max(outputs.data, 1)
192
+
193
+ fig, axes = plt.subplots(5, 1, figsize=(10, 8))
194
+ fig.suptitle("MLP Performance on 1x9 Anti-Target Avoidance", fontsize=16)
195
+
196
+ for i in range(5):
197
+ input_digits = sample_ats[i].numpy()
198
+ target_digit = sample_y[i].item() + 1
199
+ predicted_digit = predicted[i].item() + 1
200
+
201
+ is_correct = (target_digit == predicted_digit)
202
+ is_violation = predicted_digit in input_digits
203
+
204
+ full_puzzle = np.zeros(9, dtype=int)
205
+ empty_idx = np.where(~np.isin(np.arange(1, 10), input_digits))[0][0]
206
+
207
+ ax = axes[i]
208
+ ax.set_xlim(-0.5, 8.5)
209
+ ax.set_ylim(-0.5, 1.5)
210
+ ax.set_yticks([])
211
+ ax.set_xticks(range(9))
212
+ ax.set_xticklabels([])
213
+ ax.grid(True)
214
+
215
+ idx_ptr = 0
216
+ for j in range(9):
217
+ if j == empty_idx:
218
+ # Draw predicted digit
219
+ color = 'green' if is_correct else 'red'
220
+ if is_violation: color = 'orange' # Overrides red
221
+ ax.text(j, 0.5, str(predicted_digit), ha='center', va='center', fontsize=18, fontweight='bold', color='white',
222
+ bbox=dict(boxstyle="round,pad=0.3", fc=color, ec="black", lw=2))
223
+ else:
224
+ # Draw clue digit
225
+ ax.text(j, 0.5, str(input_digits[idx_ptr]), ha='center', va='center', fontsize=16,
226
+ bbox=dict(boxstyle="round,pad=0.3", fc='lightgray', ec="gray"))
227
+ idx_ptr += 1
228
+
229
+ title_text = f"Sample {i+1}: Correct: {target_digit}, Predicted: {predicted_digit} -> {'CORRECT' if is_correct else 'INCORRECT'}"
230
+ if is_violation:
231
+ title_text += " [ANTI-TARGET VIOLATION!]"
232
+ ax.set_title(title_text)
233
+
234
+ plt.tight_layout(rect=[0, 0.03, 1, 0.95])
235
+ report_img_path = os.path.join(IMG_DIR, "MLP_Report.png")
236
+ plt.savefig(report_img_path)
237
+ plt.close()
238
+
239
+ # --- Final Report ---
240
+ report = f"""
241
+ =====================================================
242
+ MLP Anti-Target Avoidance Experiment
243
+ =====================================================
244
+ Model: 2-Layer MLP (128 hidden units)
245
+ Training Samples: {train_size:,}
246
+ Validation Samples: {val_size:,}
247
+ Epochs: {EPOCHS}
248
+ -----------------------------------------------------
249
+ Validation Accuracy: {accuracy:.4f}%
250
+ Anti-Target Violations: {anti_target_violations}
251
+ Total Validation Predictions: {total:,}
252
+ Anti-Target Avoidance Rate: {at_avoidance_rate:.4f}%
253
+ =====================================================
254
+ Visual report saved to: {report_img_path}
255
+ """
256
+ print(report)
MLP_Nine_Position_AntiTarget_Avoidance_Demo.V0.0.py_Report.png ADDED

Git LFS Details

  • SHA256: f450284ba356af997160c58e394578247a8e2bed4f453d60392aa8824343ede0
  • Pointer size: 130 Bytes
  • Size of remote file: 72.9 kB