Introduction
Backpropagation helps a computer learn by fixing its mistakes step-by-step, making its guesses better over time.
1. Forward pass: Calculate output from input through the network. 2. Calculate error: Find difference between predicted and actual output. 3. Backward pass: Compute gradients of error with respect to weights. 4. Update weights: Adjust weights to reduce error using gradients.
Forward pass: output = activation(weights * input + bias) Error = predicted_output - actual_output Backward pass: gradient = error * derivative_of_activation Update weights: weights = weights - learning_rate * gradient
For each layer:
Calculate error gradient
Propagate error to previous layer
Update weights using gradients and learning rateimport numpy as np # Simple neural network with one input, one neuron, one output # Activation function: sigmoid and its derivative def sigmoid(x): return 1 / (1 + np.exp(-x)) def sigmoid_derivative(x): return x * (1 - x) # Input data (4 samples, 1 feature) inputs = np.array([[0], [1], [2], [3]]) # Actual outputs actual_output = np.array([[0], [0], [1], [1]]) # Initialize weights randomly weights = np.random.uniform(size=(1,1)) bias = np.random.uniform() learning_rate = 0.1 for epoch in range(1000): # Forward pass linear_output = np.dot(inputs, weights) + bias predicted_output = sigmoid(linear_output) # Calculate error error = actual_output - predicted_output # Backward pass d_predicted_output = error * sigmoid_derivative(predicted_output) # Update weights and bias weights += learning_rate * np.dot(inputs.T, d_predicted_output) bias += learning_rate * np.sum(d_predicted_output) # Final predictions after training final_output = sigmoid(np.dot(inputs, weights) + bias) print("Weights after training:", weights.flatten()) print("Bias after training:", bias) print("Predictions after training:", final_output.flatten())
w given learning rate η and error gradient ∂E/∂w?weight = 0.5 learning_rate = 0.1 error_gradient = 0.4 weight = weight - learning_rate * error_gradient print(round(weight, 2))
weight = 0.3 learning_rate = 0.05 error_gradient = 0.2 weight = weight + learning_rate * error_gradient print(weight)
Pass the test and this pattern moves unknown