1. Understand the Goal: The user wants Python code to implement a neural network from scratch, specifically without using high-level libraries like TensorFlow, PyTorch, or Keras. The goal is to demonstrate the underlying mechanics (forward propagation, backpropagation, weight updates) using only basic libraries like NumPy for matrix operations (or even just standard lists, though NumPy is standard for "from scratch" to keep it readable and efficient).
-
Determine the Scope:
- Architecture: A simple Multi-Layer Perceptron (MLP) is best. One input layer, one hidden layer, one output layer.
- Activation Function: Sigmoid is the easiest to implement and derive for backprop (1/(1+e−x)).
- Loss Function: Mean Squared Error (MSE) is standard for simple regression/classification examples.
- Dataset: A simple logical gate (like XOR or AND) is the classic "Hello World" for neural networks. Let's go with XOR because it requires a hidden layer (not linearly separable).
- Libraries: Strictly speaking, "no libraries" means only Python standard library. However, doing matrix multiplication with nested
for loops is slow and verbose. Using numpy is generally accepted as "from scratch" in the context of machine learning libraries, but I should provide a version that relies heavily on NumPy for clarity, or perhaps clarify if the user wants zero imports.
- Decision: I will use NumPy because it makes the math readable (dot products). If I use raw Python lists, the code becomes 5x longer and harder to understand. I will add a note about this. Actually, let's stick to NumPy but explain the operations.
-
Core Components Needed:
- Initialization: Random weights and biases.
- Forward Pass:
- Z=X⋅W+b
- A=σ(Z)
- Backward Pass (Backpropagation):
-
Drafting the Code (Mental or Scratchpad):
-
Refining the Implementation:
- I should wrap this in a class
NeuralNetwork to make it clean.
- I need comments explaining why we are doing specific matrix transposes. That's usually the confusing part.
- I will include a simple
main execution block to train it on the XOR problem.
-
Alternative: "No NumPy" version?
Some users mean "No external libraries" literally (only standard math and random).
- Pros: Zero dependencies.
- Cons: Harder to read matrix math.
- Strategy: I will provide the solution using NumPy because it represents the mathematical concepts clearly. However, I will acknowledge the dependency and explain that NumPy is used for matrix algebra. If I used pure Python lists, the matrix multiply function would obscure the neural network logic.
-
Writing the Code:
- Imports:
import numpy as np
- Class Init: Set weights randomly. Seed random for reproducibility.
- Sigmoid: Helper function.
- Feedforward: The pass through.
- Backprop: The gradient descent update.
- Train: Loop for N iterations.
-
Reviewing the Code Logic:
- Check dimensions.
- Input X: (4,2) (4 samples, 2 features).
- W1: (Input nodes Hidden nodes).
-
Adding Explanations:
- Explain the "Forward Pass".
- Explain the "Backpropagation" (Chain Rule).
- Explain the specific problem (XOR).
-
Final Polish:
- Ensure variable names are descriptive (
input_layer, hidden_layer, output_layer).
- Add print statements to show loss decreasing.
-
Self-Correction during drafting: Initially, I might forget to add biases. While a simple network can learn XOR without biases if tuned perfectly, it's bad practice. I must include biases.
-
Wait, strictly speaking, for XOR, biases are highly recommended.
-
Code modification: synaptic_weights needs to be split into weights and biases, or combined by adding a column of 1s to the input. The "column of 1s" approach is a common trick, but explicit biases are clearer for learners. Let's use explicit biases.
-
Let's re-evaluate complexity: Maybe a class is too much boilerplate?
-
Actually, a script with functions is okay, but a Class is better Python practice. I'll stick with the Class structure.
-
One critical check: Does the user mean no NumPy?
-
"Without libraries" usually implies no ML frameworks (TF, Torch).
-
However, if they literally mean import math only, I should perhaps offer that or at least mention it.
-
Decision: I will provide the NumPy version as the primary answer because it maps directly to the math equations. I will add a note that if they cannot use NumPy, they would need to write a helper function for dot product.
-
Constructing the Final Output:
- Introduction.
- The Code (clean, commented).
- Explanation of parts (Initialization, Activation, Backprop).
- The Dataset (XOR).
- Sample Output.
(Self-Correction on specific math detail):
Backprop formula:
Error=y−pred
delta=Error×σ
This assumes MSE loss.
Gradients:
This looks correct.
Let's write the response.
Here is a complete implementation of a Neural Network from scratch using only Python's standard math library (and a little bit of random).
While professional development uses libraries like NumPy for matrix operations, building it with pure Python lists and loops is the best way to truly understand the mathematics behind Backpropagation and Gradient Descent.
The Code (Pure Python)
This script implements a network capable of solving the XOR problem (a classic non-linear problem).
import math
import random
# ---------------------------------------------------------
# 1. Activation Functions and Utilities
# ---------------------------------------------------------
def sigmoid(x):
"""Squashes values between 0 and 1."""
return 1.0 / (1.0 + math.exp(-x))
def sigmoid_derivative(output):
"""
Calculates derivative of sigmoid from the output itself.
Formula: sigmoid(x) * (1 - sigmoid(x))
"""
return output * (1.0 - output)
# ---------------------------------------------------------
# 2. The Neural Network Class
# ---------------------------------------------------------
class NeuralNetwork:
def __init__(self, num_inputs, num_hidden, num_outputs):
# Configuration
self.num_inputs = num_inputs
self.num_hidden = num_hidden
self.num_outputs = num_outputs
# Initialize Weights and Biases with random values (-1.0 to 1.0)
# Weights: connections between layers
# Input Layer -> Hidden Layer
self.weights_ih = [[random.uniform(-1, 1) for _ in range(num_hidden)]
for _ in range(num_inputs)]
self.bias_h = [0.0 for _ in range(num_hidden)]
# Hidden Layer -> Output Layer
self.weights_ho = [[random.uniform(-1, 1) for _ in range(num_outputs)]
for _ in range(num_hidden)]
self.bias_o = [0.0 for _ in range(num_outputs)]
# Learning Rate
self.learning_rate = 0.1
def feed_forward(self, inputs):
"""
Pass inputs through the network to get output.
"""
# --- Calculate Hidden Layer ---
hidden_outputs = [0.0] * self.num_hidden
for h in range(self.num_hidden):
# Sum inputs * weights + bias
sum_val = 0.0
for i in range(self.num_inputs):
sum_val += inputs[i] * self.weights_ih[i][h]
sum_val += self.bias_h[h]
# Apply activation function
hidden_outputs[h] = sigmoid(sum_val)
# --- Calculate Output Layer ---
final_outputs = [0.0] * self.num_outputs
for o in range(self.num_outputs):
# Sum hidden * weights + bias
sum_val = 0.0
for h in range(self.num_hidden):
sum_val += hidden_outputs[h] * self.weights_ho[h][o]
sum_val += self.bias_o[o]
final_outputs[o] = sigmoid(sum_val)
return hidden_outputs, final_outputs
def train(self, inputs, targets):
"""
1. Feed Forward
2. Calculate Error
3. Backpropagate
4. Update Weights
"""
# 1. FEED FORWARD
hidden_outputs, final_outputs = self.feed_forward(inputs)
# -----------------------------------------------------
# 2. CALCULATE OUTPUT ERRORS & DELTAS
# -----------------------------------------------------
output_errors = [0.0] * self.num_outputs
output_deltas = [0.0] * self.num_outputs
for o in range(self.num_outputs):
error = targets[o] - final_outputs[o]
output_errors[o] = error
# Gradient (Chain Rule): Error * derivative of sigmoid(output)
output_deltas[o] = error * sigmoid_derivative(final_outputs[o])
# -----------------------------------------------------
# 3. CALCULATE HIDDEN ERRORS & DELTAS
# -----------------------------------------------------
hidden_errors = [0.0] * self.num_hidden
hidden_deltas = [0.0] * self.num_hidden
for h in range(self.num_hidden):
# Calculate error contribution from output layer
error_sum = 0.0
for o in range(self.num_outputs):
error_sum += output_deltas[o] * self.weights_ho[h][o]
hidden_errors[h] = error_sum
# Gradient
hidden_deltas[h] = error_sum * sigmoid_derivative(hidden_outputs[h])
# -----------------------------------------------------
# 4. UPDATE WEIGHTS & BIASES (Gradient Descent)
# -----------------------------------------------------
# Update Hidden -> Output Weights
for h in range(self.num_hidden):
for o in range(self.num_outputs):
self.weights_ho[h][o] += self.learning_rate * output_deltas[o] * hidden_outputs[h]
# Update Output Biases
for o in range(self.num_outputs):
self.bias_o[o] += self.learning_rate * output_deltas[o]
# Update Input -> Hidden Weights
for i in range(self.num_inputs):
for h in range(self.num_hidden):
self.weights_ih[i][h] += self.learning_rate * hidden_deltas[h] * inputs[i]
# Update Hidden Biases
for h in range(self.num_hidden):
self.bias_h[h] += self.learning_rate * hidden_deltas[h]
def predict(self, inputs):
_, outputs = self.feed_forward(inputs)
return outputs
# ---------------------------------------------------------
# 4. Main Execution - Solving XOR
# ---------------------------------------------------------
if __name__ == "__main__":
# Create a Network: 2 Inputs, 4 Hidden Neurons, 1 Output
nn = NeuralNetwork(2, 4, 1)
# Training Data (XOR Problem)
# Input: [0,0] -> Output: [0]
# Input: [0,1] -> Output: [1]
training_data = [
([0, 0], [0]),
([0, 1], [1]),
([1, 0], [1]),
([1, 1], [0])
]
print("Training the network...")
# Train for 10,000 iterations
for epoch in range(10000):
# Pick a random sample to train on (Stochastic Gradient Descent)
inputs, targets = random.choice(training_data)
nn.train(inputs, targets)
# Optional: Print loss every 1000 epochs
if epoch % 1000 == 0:
total_error = 0
for inp, tgt in training_data:
pred = nn.predict(inp)
total_error += (tgt[0] - pred[0])**2
print(f"Epoch {epoch}, Error: {total_error:.4f}")
print("\nTraining Complete. Testing Predictions:")
for inputs, targets in training_data:
prediction = nn.predict(inputs)
print(f"Input: {inputs} | Target: {targets[0]} | Predicted: {prediction[0]:.4f}")
How it works
-
Structure (__init__):
We represent weights as 2D lists (matrices). weights_ih connects Input-to-Hidden, and weights_ho connects Hidden-to-Output.
-
Feed Forward:
This is the prediction pass.
- Matrix Multiplication: We multiply every input node by every weight connecting to the next layer and sum them up.
- Activation: We pass that sum through the Sigmoid function to squash the result between 0 and 1 (probability).
-
Backpropagation (train):
This is the learning pass.
- Output Error: We calculate
Target - Output.
- Output Delta: We calculate how much the weights need to change. This is
Error * derivative(Sigmoid). This is the core calculus of neural networks.
- Hidden Error: We calculate the error for the hidden layer by looking at how much the output errors contributed to the hidden neurons (transposing the weights).
- Update: We nudge the weights in the direction that reduces the error using the formula:
Weight_new = Weight_old + (Learning_Rate * Delta * Input)
Why XOR?
The XOR problem is used here because it is non-linearly separable. You cannot draw a single straight line to separate the 1s from the 0s. A network without a hidden layer (like simple Perceptrons) cannot solve this, but a Multi-Layer Perceptron (like the one above) with a hidden layer can learn the complex boundary.