Upload PARITY-calculatingNN_Schmidhuber_V2.0.py
Browse files# Filename: PARITY-calculatingNN_Supercoded_V2.0.py
# Description: An advanced, highly configurable PyTorch script to train a neural network on the N-bit parity problem.
#
# Supercoding LLM Recode of PARITY-calculatingNN_Schmidhuber_V1.0.py
#
# This version introduces significant enhancements for robust experimentation and analysis:
# - Full Hyperparameterization: All key parameters are exposed via command-line arguments for easy tuning.
# - Flexible Problem Definition: The concept of "parity" can be switched between 'even', 'odd', or 'majority' rule,
# allowing the network to be tested on different but related logical problems.
# - Advanced Visualization: Generates a suite of high-quality plots (saved to disk and shown in popups) inspired
# by analytical scientific scripts, including:
# - Detailed Training History (Loss & Accuracy)
# - Confusion Matrix Heatmap
# - Prediction Margin Distribution Histogram
# - Raw Output vs. True Label Scatter Plot
# - Comprehensive Reporting: Automatically generates a run-specific folder containing the plots, a detailed text report,
# the trained model weights, and a log of hard-to-learn data samples.
# - Interactive Mode: Allows the user to test the trained model with custom binary inputs.
# ==============================================================================
@@ -0,0 +1,478 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Filename: PARITY-calculatingNN_Supercoded_V2.0.py
|
2 |
+
# Description: An advanced, highly configurable PyTorch script to train a neural network on the N-bit parity problem.
|
3 |
+
#
|
4 |
+
# Supercoding LLM Recode of PARITY-calculatingNN_Schmidhuber_V1.0.py
|
5 |
+
#
|
6 |
+
# This version introduces significant enhancements for robust experimentation and analysis:
|
7 |
+
# - Full Hyperparameterization: All key parameters are exposed via command-line arguments for easy tuning.
|
8 |
+
# - Flexible Problem Definition: The concept of "parity" can be switched between 'even', 'odd', or 'majority' rule,
|
9 |
+
# allowing the network to be tested on different but related logical problems.
|
10 |
+
# - Advanced Visualization: Generates a suite of high-quality plots (saved to disk and shown in popups) inspired
|
11 |
+
# by analytical scientific scripts, including:
|
12 |
+
# - Detailed Training History (Loss & Accuracy)
|
13 |
+
# - Confusion Matrix Heatmap
|
14 |
+
# - Prediction Margin Distribution Histogram
|
15 |
+
# - Raw Output vs. True Label Scatter Plot
|
16 |
+
# - Comprehensive Reporting: Automatically generates a run-specific folder containing the plots, a detailed text report,
|
17 |
+
# the trained model weights, and a log of hard-to-learn data samples.
|
18 |
+
# - Interactive Mode: Allows the user to test the trained model with custom binary inputs.
|
19 |
+
|
20 |
+
# ==============================================================================
|
21 |
+
# === LIBRARY IMPORTS ===
|
22 |
+
# ==============================================================================
|
23 |
+
print("Initializing... Loading libraries.")
|
24 |
+
import torch
|
25 |
+
import torch.nn as nn
|
26 |
+
import numpy as np
|
27 |
+
import matplotlib.pyplot as plt
|
28 |
+
import seaborn as sns
|
29 |
+
from sklearn.metrics import confusion_matrix, classification_report
|
30 |
+
import random
|
31 |
+
import os
|
32 |
+
import argparse
|
33 |
+
import datetime
|
34 |
+
import json
|
35 |
+
|
36 |
+
print("Libraries loaded successfully.\n")
|
37 |
+
|
38 |
+
# ==============================================================================
|
39 |
+
# === CORE FUNCTIONS ===
|
40 |
+
# ==============================================================================
|
41 |
+
|
42 |
+
def setup_directories(args):
|
43 |
+
"""Creates a unique, timestamped directory for the current run to store all outputs."""
|
44 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
|
45 |
+
run_name = f"run_{timestamp}_N{args.n_bits}_L{args.l_layers}_H{args.hidden_size}_{args.parity_type}"
|
46 |
+
base_dir = "parity_nn_results"
|
47 |
+
run_dir = os.path.join(base_dir, run_name)
|
48 |
+
plots_dir = os.path.join(run_dir, "plots")
|
49 |
+
os.makedirs(plots_dir, exist_ok=True)
|
50 |
+
print(f"Created output directory: {run_dir}")
|
51 |
+
return run_dir, plots_dir
|
52 |
+
|
53 |
+
def generate_data(num_samples, num_bits, parity_type='even'):
|
54 |
+
"""
|
55 |
+
Generates input data and corresponding labels based on the specified parity rule.
|
56 |
+
|
57 |
+
Args:
|
58 |
+
num_samples (int): The number of data samples to generate.
|
59 |
+
num_bits (int): The bit-width of each data sample.
|
60 |
+
parity_type (str): The rule for calculating the label.
|
61 |
+
'even': Standard even parity bit (1 if odd number of 1s, 0 if even).
|
62 |
+
'odd': Standard odd parity bit (1 if even number of 1s, 0 if odd).
|
63 |
+
'majority': Label is 1 if the count of 1s > N/2, else 0.
|
64 |
+
|
65 |
+
Returns:
|
66 |
+
tuple: A tuple containing torch tensors for data and labels.
|
67 |
+
"""
|
68 |
+
data = []
|
69 |
+
labels = []
|
70 |
+
for _ in range(num_samples):
|
71 |
+
bits = [random.randint(0, 1) for _ in range(num_bits)]
|
72 |
+
sum_of_bits = sum(bits)
|
73 |
+
|
74 |
+
if parity_type == 'even':
|
75 |
+
label = sum_of_bits % 2
|
76 |
+
elif parity_type == 'odd':
|
77 |
+
label = (sum_of_bits + 1) % 2
|
78 |
+
elif parity_type == 'majority':
|
79 |
+
label = 1 if sum_of_bits > num_bits / 2 else 0
|
80 |
+
else:
|
81 |
+
raise ValueError(f"Unknown parity_type: {parity_type}")
|
82 |
+
|
83 |
+
data.append(bits)
|
84 |
+
labels.append(label)
|
85 |
+
|
86 |
+
return torch.tensor(data, dtype=torch.float32), torch.tensor(labels, dtype=torch.float32).reshape(-1, 1)
|
87 |
+
|
88 |
+
class ParityNet(nn.Module):
|
89 |
+
"""A flexible feed-forward neural network model."""
|
90 |
+
def __init__(self, input_size, hidden_size, num_hidden_layers, output_size, activation_func='relu'):
|
91 |
+
super(ParityNet, self).__init__()
|
92 |
+
|
93 |
+
if activation_func.lower() == 'relu':
|
94 |
+
activation = nn.ReLU()
|
95 |
+
elif activation_func.lower() == 'tanh':
|
96 |
+
activation = nn.Tanh()
|
97 |
+
elif activation_func.lower() == 'leakyrelu':
|
98 |
+
activation = nn.LeakyReLU()
|
99 |
+
else:
|
100 |
+
raise ValueError("Unsupported activation function. Choose 'relu', 'tanh', or 'leakyrelu'.")
|
101 |
+
|
102 |
+
layers = []
|
103 |
+
# Input layer
|
104 |
+
layers.append(nn.Linear(input_size, hidden_size))
|
105 |
+
layers.append(activation)
|
106 |
+
# Hidden layers
|
107 |
+
for _ in range(num_hidden_layers - 1):
|
108 |
+
layers.append(nn.Linear(hidden_size, hidden_size))
|
109 |
+
layers.append(activation)
|
110 |
+
# Output layer
|
111 |
+
layers.append(nn.Linear(hidden_size, output_size))
|
112 |
+
layers.append(nn.Sigmoid()) # For binary classification
|
113 |
+
|
114 |
+
self.layers = nn.Sequential(*layers)
|
115 |
+
|
116 |
+
def forward(self, x):
|
117 |
+
return self.layers(x)
|
118 |
+
|
119 |
+
def train_model(model, train_data, train_labels, test_data, test_labels, args, run_dir):
|
120 |
+
"""Trains the model and logs performance and difficult samples."""
|
121 |
+
criterion = nn.BCELoss()
|
122 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=args.learning_rate)
|
123 |
+
|
124 |
+
history = {'epoch': [], 'train_loss': [], 'val_acc': []}
|
125 |
+
hard_samples = {}
|
126 |
+
|
127 |
+
print("\n" + "="*50)
|
128 |
+
print("=== STARTING TRAINING ===")
|
129 |
+
print(f"Epochs: {args.epochs}, LR: {args.learning_rate}, Stop Threshold: {args.min_loss_threshold}")
|
130 |
+
print("="*50)
|
131 |
+
|
132 |
+
# Interactive plot setup
|
133 |
+
plt.ion()
|
134 |
+
fig, ax = plt.subplots(figsize=(10, 6))
|
135 |
+
|
136 |
+
for epoch in range(args.epochs):
|
137 |
+
model.train()
|
138 |
+
outputs = model(train_data)
|
139 |
+
loss = criterion(outputs, train_labels)
|
140 |
+
|
141 |
+
optimizer.zero_grad()
|
142 |
+
loss.backward()
|
143 |
+
optimizer.step()
|
144 |
+
|
145 |
+
if (epoch + 1) % args.plot_update_freq == 0:
|
146 |
+
model.eval()
|
147 |
+
with torch.no_grad():
|
148 |
+
val_outputs = model(test_data)
|
149 |
+
predicted = (val_outputs > 0.5).float()
|
150 |
+
accuracy = (predicted == test_labels).sum().float() / len(test_labels)
|
151 |
+
|
152 |
+
# Log hard samples (misclassified during this validation check)
|
153 |
+
misclassified_mask = (predicted != test_labels).flatten()
|
154 |
+
for i, is_misclassified in enumerate(misclassified_mask):
|
155 |
+
if is_misclassified:
|
156 |
+
sample_str = ''.join(map(str, test_data[i].int().tolist()))
|
157 |
+
hard_samples[sample_str] = hard_samples.get(sample_str, 0) + 1
|
158 |
+
|
159 |
+
history['epoch'].append(epoch + 1)
|
160 |
+
history['train_loss'].append(loss.item())
|
161 |
+
history['val_acc'].append(accuracy.item())
|
162 |
+
|
163 |
+
print(f'Epoch [{epoch+1}/{args.epochs}], Loss: {loss.item():.5f}, Validation Accuracy: {accuracy.item():.4f}')
|
164 |
+
|
165 |
+
# Update real-time plot
|
166 |
+
ax.clear()
|
167 |
+
ax.plot(history['epoch'], history['train_loss'], 'r-', label='Training Loss')
|
168 |
+
ax.set_xlabel(f"Epoch (x{args.plot_update_freq})")
|
169 |
+
ax.set_ylabel("Loss", color='r')
|
170 |
+
ax.tick_params(axis='y', labelcolor='r')
|
171 |
+
|
172 |
+
ax2 = ax.twinx()
|
173 |
+
ax2.plot(history['epoch'], history['val_acc'], 'b-', label='Validation Accuracy')
|
174 |
+
ax2.set_ylabel("Accuracy", color='b')
|
175 |
+
ax2.tick_params(axis='y', labelcolor='b')
|
176 |
+
ax2.set_ylim(0, 1.05)
|
177 |
+
|
178 |
+
fig.suptitle("Live Training Progress")
|
179 |
+
fig.legend(loc="upper center", bbox_to_anchor=(0.5, 0.95), ncol=2)
|
180 |
+
plt.grid(True)
|
181 |
+
plt.draw()
|
182 |
+
plt.pause(0.01)
|
183 |
+
|
184 |
+
if loss.item() < args.min_loss_threshold:
|
185 |
+
print(f"\nReached minimum loss threshold of {args.min_loss_threshold} at epoch {epoch+1}. Stopping training.")
|
186 |
+
break
|
187 |
+
|
188 |
+
plt.ioff()
|
189 |
+
print("\n" + "="*50)
|
190 |
+
print("=== TRAINING COMPLETE ===")
|
191 |
+
print("="*50 + "\n")
|
192 |
+
|
193 |
+
# Save hard samples log
|
194 |
+
if hard_samples:
|
195 |
+
hard_samples_path = os.path.join(run_dir, "hard_samples.json")
|
196 |
+
sorted_hard_samples = sorted(hard_samples.items(), key=lambda item: item[1], reverse=True)
|
197 |
+
with open(hard_samples_path, 'w') as f:
|
198 |
+
json.dump(dict(sorted_hard_samples), f, indent=4)
|
199 |
+
print(f"Logged {len(hard_samples)} unique hard-to-learn samples to {hard_samples_path}")
|
200 |
+
|
201 |
+
return model, history
|
202 |
+
|
203 |
+
|
204 |
+
def evaluate_model(model, test_data, test_labels):
|
205 |
+
"""Evaluates the final model and returns a dictionary of metrics."""
|
206 |
+
model.eval()
|
207 |
+
with torch.no_grad():
|
208 |
+
outputs = model(test_data)
|
209 |
+
predicted = (outputs > 0.5).float()
|
210 |
+
accuracy = (predicted == test_labels).sum().float() / len(test_labels)
|
211 |
+
|
212 |
+
# Separate margins for predictions of 1 and 0
|
213 |
+
margins_ones = outputs[predicted == 1] - 0.5
|
214 |
+
margins_zeros = 0.5 - outputs[predicted == 0]
|
215 |
+
|
216 |
+
results = {
|
217 |
+
"accuracy": accuracy.item(),
|
218 |
+
"raw_outputs": outputs.flatten().numpy(),
|
219 |
+
"predictions": predicted.flatten().numpy(),
|
220 |
+
"labels": test_labels.flatten().numpy(),
|
221 |
+
"margins_ones": margins_ones.numpy(),
|
222 |
+
"margins_zeros": margins_zeros.numpy(),
|
223 |
+
"conf_matrix": confusion_matrix(test_labels.numpy(), predicted.numpy()),
|
224 |
+
"class_report": classification_report(test_labels.numpy(), predicted.numpy(), output_dict=True, zero_division=0)
|
225 |
+
}
|
226 |
+
return results
|
227 |
+
|
228 |
+
def generate_plots(history, results, args, plots_dir):
|
229 |
+
"""Generates and saves a suite of analytical plots."""
|
230 |
+
print("Generating and saving analysis plots...")
|
231 |
+
plt.style.use('seaborn-v0_8-whitegrid')
|
232 |
+
|
233 |
+
# --- 1. Training History Plot ---
|
234 |
+
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(18, 6))
|
235 |
+
fig.suptitle(f'Training History for N={args.n_bits} {args.parity_type.title()} Parity', fontsize=16)
|
236 |
+
|
237 |
+
ax1.plot(history['epoch'], history['train_loss'], label='Training Loss', color='crimson')
|
238 |
+
ax1.set_title('Training Loss over Epochs')
|
239 |
+
ax1.set_xlabel('Epoch')
|
240 |
+
ax1.set_ylabel('Binary Cross-Entropy Loss')
|
241 |
+
ax1.legend()
|
242 |
+
|
243 |
+
ax2.plot(history['epoch'], history['val_acc'], label='Validation Accuracy', color='royalblue')
|
244 |
+
ax2.set_title('Validation Accuracy over Epochs')
|
245 |
+
ax2.set_xlabel('Epoch')
|
246 |
+
ax2.set_ylabel('Accuracy')
|
247 |
+
ax2.set_ylim(0, 1.05)
|
248 |
+
ax2.legend()
|
249 |
+
|
250 |
+
plt.tight_layout(rect=[0, 0.03, 1, 0.95])
|
251 |
+
plt.savefig(os.path.join(plots_dir, "01_training_history.png"))
|
252 |
+
plt.show()
|
253 |
+
|
254 |
+
# --- 2. Confusion Matrix Heatmap ---
|
255 |
+
plt.figure(figsize=(8, 6))
|
256 |
+
sns.heatmap(results['conf_matrix'], annot=True, fmt='d', cmap='Blues',
|
257 |
+
xticklabels=['Predicted 0', 'Predicted 1'],
|
258 |
+
yticklabels=['Actual 0', 'Actual 1'])
|
259 |
+
plt.title('Confusion Matrix on Test Set', fontsize=14)
|
260 |
+
plt.ylabel('True Label')
|
261 |
+
plt.xlabel('Predicted Label')
|
262 |
+
plt.savefig(os.path.join(plots_dir, "02_confusion_matrix.png"))
|
263 |
+
plt.show()
|
264 |
+
|
265 |
+
# --- 3. Prediction Margin Distribution ---
|
266 |
+
plt.figure(figsize=(12, 6))
|
267 |
+
plt.hist(results['margins_zeros'], bins=20, alpha=0.7, color='coral', label='Margins for "0" Predictions')
|
268 |
+
plt.hist(results['margins_ones'], bins=20, alpha=0.7, color='teal', label='Margins for "1" Predictions')
|
269 |
+
plt.title('Distribution of Prediction Margins (Confidence)', fontsize=14)
|
270 |
+
plt.xlabel('Margin (Distance from 0.5 threshold)')
|
271 |
+
plt.ylabel('Frequency')
|
272 |
+
plt.legend()
|
273 |
+
plt.savefig(os.path.join(plots_dir, "03_prediction_margins.png"))
|
274 |
+
plt.show()
|
275 |
+
|
276 |
+
# --- 4. Raw Outputs vs. Labels ---
|
277 |
+
plt.figure(figsize=(10, 7))
|
278 |
+
jitter = np.random.normal(0, 0.015, size=len(results['labels'])) # For better visualization
|
279 |
+
colors = ['coral' if l == 0 else 'teal' for l in results['labels']]
|
280 |
+
plt.scatter(results['labels'] + jitter, results['raw_outputs'], c=colors, alpha=0.6)
|
281 |
+
plt.axhline(y=0.5, color='r', linestyle='--', label='Decision Boundary (0.5)')
|
282 |
+
plt.title('Model Raw Output vs. True Labels', fontsize=14)
|
283 |
+
plt.xlabel('True Label (with jitter)')
|
284 |
+
plt.ylabel('Sigmoid Output (Probability)')
|
285 |
+
plt.xticks([0, 1], ['Class 0', 'Class 1'])
|
286 |
+
plt.legend()
|
287 |
+
plt.savefig(os.path.join(plots_dir, "04_outputs_vs_labels.png"))
|
288 |
+
plt.show()
|
289 |
+
print("All plots saved.")
|
290 |
+
|
291 |
+
|
292 |
+
def generate_report(args, results, run_dir):
|
293 |
+
"""Generates and saves a comprehensive text report of the run."""
|
294 |
+
report_path = os.path.join(run_dir, "report.txt")
|
295 |
+
|
296 |
+
# Margin stats
|
297 |
+
def get_margin_stats(margins):
|
298 |
+
if len(margins) == 0: return "N/A", "N/A", "N/A"
|
299 |
+
return f"{np.min(margins):.4f}", f"{np.max(margins):.4f}", f"{np.mean(margins):.4f}"
|
300 |
+
|
301 |
+
min_m0, max_m0, avg_m0 = get_margin_stats(results['margins_zeros'])
|
302 |
+
min_m1, max_m1, avg_m1 = get_margin_stats(results['margins_ones'])
|
303 |
+
|
304 |
+
tn, fp, fn, tp = results['conf_matrix'].ravel() if results['conf_matrix'].size == 4 else (0,0,0,0)
|
305 |
+
|
306 |
+
report_content = f"""
|
307 |
+
# ==========================================================
|
308 |
+
# == PARITY NEURAL NETWORK EXPERIMENT REPORT
|
309 |
+
# ==========================================================
|
310 |
+
# Run Directory: {run_dir}
|
311 |
+
# Report Time: {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
|
312 |
+
#
|
313 |
+
# ==========================================================
|
314 |
+
# == HYPERPARAMETERS
|
315 |
+
# ==========================================================
|
316 |
+
# Problem Type: {args.parity_type.title()}
|
317 |
+
# Input Bits (N): {args.n_bits}
|
318 |
+
# Hidden Layers (L): {args.l_layers}
|
319 |
+
# Neurons per Hidden Layer: {args.hidden_size}
|
320 |
+
# Activation Function: {args.activation.upper()}
|
321 |
+
#
|
322 |
+
# --- Training Configuration ---
|
323 |
+
# Epochs: {args.epochs}
|
324 |
+
# Learning Rate: {args.learning_rate}
|
325 |
+
# Train Samples: {args.num_train_samples}
|
326 |
+
# Test Samples: {args.num_test_samples}
|
327 |
+
# Loss Stop Threshold: {args.min_loss_threshold}
|
328 |
+
#
|
329 |
+
# ==========================================================
|
330 |
+
# == EVALUATION RESULTS
|
331 |
+
# ==========================================================
|
332 |
+
# Final Test Accuracy: {results['accuracy']:.4f}
|
333 |
+
#
|
334 |
+
# --- Confusion Matrix ---
|
335 |
+
# True Positives (1->1): {tp}
|
336 |
+
# True Negatives (0->0): {tn}
|
337 |
+
# False Positives (0->1): {fp}
|
338 |
+
# False Negatives (1->0): {fn}
|
339 |
+
#
|
340 |
+
# --- Prediction Margin Analysis (Confidence) ---
|
341 |
+
# | Min | Max | Average
|
342 |
+
# ----------------------------------------------------------
|
343 |
+
# Margin (Zeros): | {min_m0:<7} | {max_m0:<7} | {avg_m0:<7}
|
344 |
+
# Margin (Ones): | {min_m1:<7} | {max_m1:<7} | {avg_m1:<7}
|
345 |
+
#
|
346 |
+
# ==========================================================
|
347 |
+
# == CONCLUSION
|
348 |
+
# ==========================================================
|
349 |
+
# The model was trained to solve the {args.n_bits}-bit '{args.parity_type}' problem.
|
350 |
+
# With a final test accuracy of {results['accuracy']:.2%}, the network has demonstrated
|
351 |
+
# {'a high degree of success' if results['accuracy'] > 0.95 else 'a moderate level of success' if results['accuracy'] > 0.7 else 'difficulty'}
|
352 |
+
# in learning the underlying logical rule.
|
353 |
+
#
|
354 |
+
# The margin analysis indicates the model's confidence. Larger average margins
|
355 |
+
# suggest a more robust and decisive model. The generated plots provide
|
356 |
+
# further visual insight into the training process and final performance.
|
357 |
+
#
|
358 |
+
# This experiment explores the capability of a simple Feed-Forward Network
|
359 |
+
# to learn complex, non-linear functions like parity, a task often cited
|
360 |
+
# as a challenge for non-recurrent architectures but clearly achievable
|
361 |
+
# with sufficient network capacity and training.
|
362 |
+
#
|
363 |
+
"""
|
364 |
+
print("\n" + report_content)
|
365 |
+
with open(report_path, "w") as f:
|
366 |
+
f.write(report_content)
|
367 |
+
print(f"Report saved to {report_path}")
|
368 |
+
|
369 |
+
def user_inference_loop(model, args):
|
370 |
+
"""An interactive loop for the user to test the model. replicate the label-calculation logic directly within the user_inference_loop. This isolates the calculation and uses the user's provided bit string, fixing the crash and ensuring the "True Label" is accurate for the given input. With this correction, the interactive mode will now function as intended, correctly comparing the model's prediction against the true calculated label for your input. System integrity restored."""
|
371 |
+
print("\n" + "="*50)
|
372 |
+
print("=== INTERACTIVE INFERENCE MODE ===")
|
373 |
+
print(f"Enter a {args.n_bits}-bit binary string (e.g., {'10101'[:args.n_bits]}) or 'q' to quit.")
|
374 |
+
print("="*50)
|
375 |
+
|
376 |
+
model.eval()
|
377 |
+
while True:
|
378 |
+
user_input = input(f"Input ({args.n_bits} bits) > ")
|
379 |
+
if user_input.lower() == 'q':
|
380 |
+
break
|
381 |
+
|
382 |
+
if len(user_input) != args.n_bits or not all(c in '01' for c in user_input):
|
383 |
+
print(f"Error: Please enter exactly {args.n_bits} bits (0s and 1s).")
|
384 |
+
continue
|
385 |
+
|
386 |
+
bits = [int(c) for c in user_input]
|
387 |
+
data_tensor = torch.tensor(bits, dtype=torch.float32).reshape(1, -1)
|
388 |
+
|
389 |
+
with torch.no_grad():
|
390 |
+
output = model(data_tensor)
|
391 |
+
prediction = (output > 0.5).int().item()
|
392 |
+
confidence = output.item()
|
393 |
+
|
394 |
+
print(f" Model Output: {confidence:.4f}")
|
395 |
+
print(f" -> Predicted Label: {prediction}")
|
396 |
+
|
397 |
+
# --- FIX START ---
|
398 |
+
# The original code incorrectly tried to pass the user's data back into
|
399 |
+
# the generate_data function. The fix is to calculate the true label
|
400 |
+
# directly here using the same logic from the data generation process.
|
401 |
+
|
402 |
+
sum_of_bits = sum(bits)
|
403 |
+
true_label = -1 # Default/error value
|
404 |
+
|
405 |
+
if args.parity_type == 'even':
|
406 |
+
true_label = sum_of_bits % 2
|
407 |
+
elif args.parity_type == 'odd':
|
408 |
+
true_label = (sum_of_bits + 1) % 2
|
409 |
+
elif args.parity_type == 'majority':
|
410 |
+
true_label = 1 if sum_of_bits > args.n_bits / 2 else 0
|
411 |
+
|
412 |
+
# --- FIX END ---
|
413 |
+
|
414 |
+
print(f" -> True Label ({args.parity_type}): {true_label} {'(Correct)' if prediction == true_label else '(Incorrect)'}\n")
|
415 |
+
|
416 |
+
# ==============================================================================
|
417 |
+
# === MAIN EXECUTION BLOCK ===
|
418 |
+
# ==============================================================================
|
419 |
+
|
420 |
+
if __name__ == '__main__':
|
421 |
+
parser = argparse.ArgumentParser(description="Train a Neural Network for the N-Bit Parity Problem.")
|
422 |
+
|
423 |
+
# --- Model Architecture ---
|
424 |
+
parser.add_argument('-n', '--n_bits', type=int, default=5, help="Number of input bits (N).")
|
425 |
+
parser.add_argument('-l', '--l_layers', type=int, default=2, help="Number of hidden layers (L).")
|
426 |
+
parser.add_argument('-hs', '--hidden_size', type=int, default=10, help="Number of neurons per hidden layer.")
|
427 |
+
parser.add_argument('-a', '--activation', type=str, default='relu', choices=['relu', 'tanh', 'leakyrelu'], help="Activation function for hidden layers.")
|
428 |
+
|
429 |
+
# --- Training Parameters ---
|
430 |
+
parser.add_argument('-e', '--epochs', type=int, default=10000, help="Maximum number of training epochs.")
|
431 |
+
parser.add_argument('-lr', '--learning_rate', type=float, default=0.003, help="Optimizer learning rate.")
|
432 |
+
parser.add_argument('-loss', '--min_loss_threshold', type=float, default=0.01, help="Loss threshold to stop training early.")
|
433 |
+
parser.add_argument('-puf', '--plot_update_freq', type=int, default=100, help="Frequency (in epochs) to update the live plot.")
|
434 |
+
|
435 |
+
# --- Data and Problem Type ---
|
436 |
+
parser.add_argument('-pt', '--parity_type', type=str, default='even', choices=['even', 'odd', 'majority'], help="The logical rule to learn.")
|
437 |
+
parser.add_argument('-nts', '--num_train_samples', type=int, default=2000, help="Number of samples for the training dataset.")
|
438 |
+
parser.add_argument('-ntests', '--num_test_samples', type=int, default=500, help="Number of samples for the test dataset.")
|
439 |
+
|
440 |
+
args = parser.parse_args()
|
441 |
+
|
442 |
+
# 1. Setup
|
443 |
+
run_dir, plots_dir = setup_directories(args)
|
444 |
+
# Save args for reproducibility
|
445 |
+
with open(os.path.join(run_dir, 'hyperparameters.json'), 'w') as f:
|
446 |
+
json.dump(vars(args), f, indent=4)
|
447 |
+
|
448 |
+
# 2. Generate Data
|
449 |
+
print(f"\nGenerating {args.num_train_samples} training and {args.num_test_samples} test samples for {args.n_bits}-bit '{args.parity_type}' parity...")
|
450 |
+
train_data, train_labels = generate_data(args.num_train_samples, args.n_bits, args.parity_type)
|
451 |
+
test_data, test_labels = generate_data(args.num_test_samples, args.n_bits, args.parity_type)
|
452 |
+
print("Data generation complete.")
|
453 |
+
|
454 |
+
# 3. Create Model
|
455 |
+
model = ParityNet(args.n_bits, args.hidden_size, args.l_layers, 1, args.activation)
|
456 |
+
print("\nModel Architecture:")
|
457 |
+
print(model)
|
458 |
+
|
459 |
+
# 4. Train Model
|
460 |
+
trained_model, history = train_model(model, train_data, train_labels, test_data, test_labels, args, run_dir)
|
461 |
+
|
462 |
+
# 5. Save Model Weights
|
463 |
+
model_path = os.path.join(run_dir, f"parity_nn_N{args.n_bits}_{args.parity_type}.pth")
|
464 |
+
torch.save(trained_model.state_dict(), model_path)
|
465 |
+
print(f"Trained model weights saved to: {model_path}")
|
466 |
+
|
467 |
+
# 6. Evaluate and Report
|
468 |
+
if len(history['epoch']) > 0: # Ensure training ran for at least one update cycle
|
469 |
+
final_results = evaluate_model(trained_model, test_data, test_labels)
|
470 |
+
generate_report(args, final_results, run_dir)
|
471 |
+
generate_plots(history, final_results, args, plots_dir)
|
472 |
+
else:
|
473 |
+
print("\nTraining was too short to generate a full report and plots.")
|
474 |
+
|
475 |
+
# 7. Interactive Mode
|
476 |
+
user_inference_loop(trained_model, args)
|
477 |
+
|
478 |
+
print("\nSupercoding LLM task complete. System returning to normal operation.")
|