The user wants a "neural network implementation from scratch using linear algebra."
1. Analyze the Request:
- Core Task: Implement a neural network.
- Constraint: "From scratch" (no TensorFlow, PyTorch, Keras, etc.).
- Method: "Using linear algebra" (implies using
numpy for matrix operations).
- Goal: Demonstrate the fundamental mechanics of forward propagation, loss calculation, backpropagation, and parameter updates.
2. Determine the Scope:
- Architecture: A simple Multi-Layer Perceptron (MLP) is best for demonstration. I should probably do an input layer, one hidden layer, and an output layer.
- Activation Functions:
- Hidden layer: ReLU or Sigmoid/Tanh. Let's go with Sigmoid or Tanh for simplicity in derivatives, or ReLU for modern relevance. Let's stick to Sigmoid for the educational clarity of the derivative (σ(1−σ)), or maybe Tanh. Let's actually use ReLU for the hidden layer and Softmax for the output layer if it's classification, or just Sigmoid for both if it's binary classification. Let's stick to a binary classification example (e.g., XOR or simple logic) with Sigmoid activation. It's the classic "Hello World" of NN.
- Output: Sigmoid (for binary classification).
- Loss Function: Mean Squared Error (MSE) or Binary Cross-Entropy (BCE). MSE is often easier to explain mathematically for beginners (y−y^), though BCE is better for classification. I'll use MSE for simplicity in the code unless I want to be strictly rigorous. Actually, let's do MSE. The derivative is straightforward.
- Language: Python.
- Library:
numpy is the standard for linear algebra in Python.
3. Mathematical Formulation (The "Linear Algebra" part):
-
Forward Pass:
- Z1=X⋅W1+b
4. Drafting the Code Structure:
- Imports: Just
numpy.
- Initialization: Random weights, zeros for biases. Important to manage dimensions.
- Input size n, Hidden size h, Output size o.
- Activation Functions: Define them and their derivatives.
- Class Structure: A class
NeuralNetwork makes it cleaner.
5. Refining the Implementation Details:
-
Dimensions Check:
- If X is (m,nfeatures).
- is .
6. Creating a Test Case:
The XOR problem is the classic non-linear problem.
Input: [[0,0], [0,1], [1,0], [1,1]]
Output: [[0], [1], [1], [0]]
7. Writing the Code (Mental Draft & Iteration):
8. Adding Explanations:
The user asked for "using linear algebra". It is crucial to explain where the linear algebra fits in. I need to annotate the code with comments like # Matrix Multiplication and explain the dimensions.
9. Review and Polish:
- Is it truly from scratch? Yes, only numpy.
- Is the linear algebra clear? Yes, using dot products.
- Is it runnable? Yes.
Let's assemble the final response. I will provide:
- The mathematical concept (briefly).
- The Python implementation using NumPy.
- An example usage (XOR).
(Self-Correction during drafting): Should I use ReLU?
ReLU is max(0,x). Derivative is 1 if x>0 else 0.
Sigmoid derivative is .
Sigmoid is often easier for beginners to grasp intuitively as "squashing" values between 0 and 1, matching the XOR output. I'll stick with Sigmoid for this demonstration to keep the code purely mathematical without conditional logic logic inside the derivative function.
Final Code Structure Plan:
- Import numpy.
- Define activation helpers.
- Create
SimpleNeuralNetwork class.
- Init weights (randn) and biases (zeros).
- Forward method: Z=XW+b, A=σ(Z).
- Backward method: Calculate gradients using transposes (, ) and update.
Let's write it out.
Here is a complete implementation of a Neural Network from scratch using Python and NumPy (for linear algebra operations).
This implementation creates a simple Multi-Layer Perceptron (MLP) to solve the classic XOR problem. It demonstrates the core "forward pass" (matrix multiplications) and the "backward pass" (calculus/chain rule) used to train the network.
The Linear Algebra Concepts
There are two main linear algebra operations at work here:
- Forward Propagation: Input data is transformed by weights using Matrix Multiplication (Dot Products) and shifted by biases (Vector Addition).
- Backpropagation: Errors are propagated backward using the Transpose of the weight matrices to align dimensions.
The Implementation
import numpy as np
class NeuralNetwork:
def __init__(self, input_size, hidden_size, output_size):
"""
Initialize weights and biases.
We use random values to break symmetry.
Dimensions:
- W1: (input_size x hidden_size)
- b1: (1 x hidden_size)
- W2: (hidden_size x output_size)
- b2: (1 x output_size)
"""
self.W1 = np.random.randn(input_size, hidden_size)
self.b1 = np.zeros((1, hidden_size))
self.W2 = np.random.randn(hidden_size, output_size)
self.b2 = np.zeros((1, output_size))
def sigmoid(self, x):
"""Activation function: squashes values between 0 and 1."""
return 1 / (1 + np.exp(-x))
def sigmoid_derivative(self, x):
"""Derivative of sigmoid for backpropagation."""
return x * (1 - x)
def feedforward(self, X):
"""
Linear Algebra Forward Pass:
1. Z1 = X · W1 + b1 (Linear transformation)
2. A1 = sigmoid(Z1) (Non-linear activation)
3. Z2 = A1 · W2 + b2 (Linear transformation)
4. A2 = sigmoid(Z2) (Output prediction)
"""
# Layer 1
self.Z1 = np.dot(X, self.W1) + self.b1
self.A1 = self.sigmoid(self.Z1)
# Layer 2 (Output)
self.Z2 = np.dot(self.A1, self.W2) + self.b2
self.A2 = self.sigmoid(self.Z2)
return self.A2
def backpropagate(self, X, y, learning_rate):
"""
Linear Algebra Backward Pass:
Calculates gradients using the Chain Rule and updates weights.
"""
m = X.shape[0] # Number of samples
# --- Calculate Error at Output ---
# Error = Prediction - Actual
output_error = self.A2 - y
# Delta for Output Layer: Error * derivative of activation
# Dimensions: (m x output_size)
dZ2 = output_error * self.sigmoid_derivative(self.A2)
# --- Gradients for Weights 2 ---
# Linear Algebra: Transpose A1 to align dimensions for multiplication
# dW2 = A1.T · dZ2
dW2 = np.dot(self.A1.T, dZ2) / m
# Gradient for Bias 2 (Sum of deltas across samples)
db2 = np.sum(dZ2, axis=0, keepdims=True) / m
# --- Propagate Error to Hidden Layer ---
# Linear Algebra: Project error back using W2 Transpose
# hidden_error = dZ2 · W2.T
hidden_error = np.dot(dZ2, self.W2.T)
# Delta for Hidden Layer: Error * derivative of activation
dZ1 = hidden_error * self.sigmoid_derivative(self.A1)
# --- Gradients for Weights 1 ---
# dW1 = X.T · dZ1
dW1 = np.dot(X.T, dZ1) / m
# Gradient for Bias 1
db1 = np.sum(dZ1, axis=0, keepdims=True) / m
# --- Update Weights and Biases (Gradient Descent) ---
# W_new = W_old - (learning_rate * gradient)
self.W2 -= learning_rate * dW2
self.b2 -= learning_rate * db2
self.W1 -= learning_rate * dW1
self.b1 -= learning_rate * db1
def train(self, X, y, epochs, learning_rate):
for epoch in range(epochs):
self.feedforward(X)
self.backpropagate(X, y, learning_rate)
if epoch % 1000 == 0:
loss = np.mean(np.square(y - self.A2))
print(f"Epoch {epoch} | Loss: {loss:.4f}")
# --- Execution ---
# 1. Define the Dataset (XOR problem)
# Inputs: [0,0], [0,1], [1,0], [1,1]
X = np.array([[0,0], [0,1], [1,0], [1,1]])
# Outputs: 0, 1, 1, 0
y = np.array([[0], [1], [1], [0]])
# 2. Initialize Network
# Input size: 2 features
# Hidden size: 4 neurons (arbitrary choice)
# Output size: 1 value (0 or 1)
nn = NeuralNetwork(input_size=2, hidden_size=4, output_size=1)
# 3. Train
print("Training started...")
nn.train(X, y, epochs=10000, learning_rate=0.5)
# 4. Test
print("\nFinal Predictions:")
predictions = nn.feedforward(X)
for i, input_val in enumerate(X):
print(f"Input: {input_val} -> Predicted: {predictions[i][0]:.4f} (Actual: {y[i][0]})")
How it works (The Math)
- Input Matrix (X): We treat our data as a matrix of size m×n (samples × features).
- Weight Matrices (W): The "knowledge" of the network. They transform the input space.
- Forward: We calculate Z. This is a dot product where every neuron in the input layer connects to every neuron in the next layer.