Convergent Training and Inference
Train weights and bias over multiple epochs to learn logical patterns and classify new unseen inputs.
First Principles: The Culmination: From Zeroes to an Intelligent Model
You have constructed every foundational component of modern machine learning:
- The Linear Neuron: Computes weighted combinations of environmental signals.
- The Activation Function: Introduces non-linear squashing into bounded probabilities.
- The Loss Function: Quantifies prediction error with mathematical rigor.
- The Optimization Step: Shifts weights downhill along the loss slope.
- The Training Epoch: Uses the chain rule to backpropagate errors across all data samples.
In this final stage, you bring all these components together to build the complete training and inferenceThe stage where a trained model processes new input data to make classificationsView official documentation engine.
The Challenge: Teaching Boolean Logic to a Neuron
Consider the truth table for the logical AND gate:
- Inputs
- Inputs
- Inputs
- Inputs
At the beginning, we initialize all weights to () and bias to (). With these initial values, the neuron knows nothing: for any input it computes , giving a sigmoid output of (maximum uncertainty).
However, as the optimization loop runs through 200 epochs:
- During each epoch, the model compares its predictions against the truth table targets.
- Backpropagation computes the average gradients across all samples.
- The weights gradually increase while the bias becomes negative.
- By the end of training, the parameters converge such that the weighted sum only clears the threshold when both inputs are active.
You have just trained a machine to discover a boolean rule purely from examples!
Your Objective in this Stage
When standard input receives "op": "train-and-predict", process:
epochs: number of full training epochs to run (positive integer)learning_rate: learning ratesamples: training dataset containing pairs of{"x": [...], "y": 0 or 1}test_inputs: list of feature vectors to classify after training
Step-by-Step Procedure
-
Initialization:
- Determine input dimension from
len(samples[0]["x"]). - Initialize weights to zeroes:
weights = [0.0] * d. - Initialize bias to zero:
bias = 0.0. - Batch size: .
- Determine input dimension from
-
Training Loop (Repeat
epochstimes):- Initialize gradient accumulators:
grad_w = [0.0] * dandgrad_b = 0.0. - For each sample in
samples:- .
- .
- .
- Accumulate:
grad_w[j] += delta * s.x[j]andgrad_b += delta.
- Update weights and bias by subtracting the mean gradient scaled by
learning_rate:
- Initialize gradient accumulators:
-
Inference Phase:
- For each feature vector in
test_inputs:- Evaluate the neuron using the finalized weights and bias:
- Apply the standard classification threshold:
- For each feature vector in
Practical Implementation and Code Advice
- Python Pattern:
dim = len(samples[0]["x"]) w = [0.0] * dim b = 0.0 n = len(samples) # Phase 1: Training for _ in range(epochs): grad_w = [0.0] * dim grad_b = 0.0 for s in samples: x, y = s["x"], s["y"] z = sum(xi * wi for xi, wi in zip(x, w)) + b y_hat = 1.0 / (1.0 + math.exp(-z)) delta = (y_hat - y) * y_hat * (1.0 - y_hat) for j in range(dim): grad_w[j] += delta * x[j] grad_b += delta for j in range(dim): w[j] -= lr * (grad_w[j] / n) b -= lr * (grad_b / n) # Phase 2: Inference (Predictions) predictions = [] for x in test_inputs: z = sum(xi * wi for xi, wi in zip(x, w)) + b y_hat = 1.0 / (1.0 + math.exp(-z)) predictions.append(1 if y_hat >= 0.5 else 0) return {"predictions": predictions} - TypeScript Pattern:
const dim = samples[0].x.length; const n = samples.length; const w = new Array(dim).fill(0); let b = 0; // Phase 1: Training for (let ep = 0; ep < epochs; ep++) { const gradW = new Array(dim).fill(0); let gradB = 0; for (const s of samples) { let z = b; for (let i = 0; i < dim; i++) z += s.x[i] * w[i]; const yHat = 1 / (1 + Math.exp(-z)); const delta = (yHat - s.y) * yHat * (1 - yHat); for (let i = 0; i < dim; i++) gradW[i] += delta * s.x[i]; gradB += delta; } for (let i = 0; i < dim; i++) w[i] -= lr * (gradW[i] / n); b -= lr * (gradB / n); } // Phase 2: Inference const predictions = test_inputs.map((x) => { let z = b; for (let i = 0; i < dim; i++) z += x[i] * w[i]; const yHat = 1 / (1 + Math.exp(-z)); return yHat >= 0.5 ? 1 : 0; }); return { predictions };
ML Engineering Insight
Notice the sharp separation between phases:
- Training: Model weights mutate along loss gradients guided by ground-truth labels
y. - Inference: Weights are completely frozen; the network only executes the forward pass on unseen data without knowing true answers or computing gradients.
Validation and Output Rules
- If
samplesis empty orepochs <= 0, writeerrortostderrand exit with code1. - Output a JSON object containing the array of predicted integers:
{ "predictions": [0, 0, 0, 1] }