Introduction
Gradient descent helps a model learn by slowly improving its guesses to make fewer mistakes.
for each step: calculate gradient of loss with respect to parameters update parameters by moving opposite to gradient scaled by learning rate
weights = weights - learning_rate * gradient
for epoch in range(100): predictions = model(inputs) loss = loss_function(predictions, targets) gradient = compute_gradient(loss, weights) weights -= learning_rate * gradient
import numpy as np # Simple linear regression using gradient descent # Data: y = 2x + 1 x = np.array([1, 2, 3, 4, 5], dtype=float) y = 2 * x + 1 # Initialize parameters weight = 0.0 bias = 0.0 learning_rate = 0.1 for epoch in range(20): # Predictions y_pred = weight * x + bias # Calculate error error = y_pred - y # Calculate gradients dweight = (2/len(x)) * np.dot(error, x) dbias = (2/len(x)) * np.sum(error) # Update parameters weight -= learning_rate * dweight bias -= learning_rate * dbias # Calculate loss (mean squared error) loss = np.mean(error ** 2) print(f"Epoch {epoch+1}: loss={loss:.4f}, weight={weight:.4f}, bias={bias:.4f}")
theta = 2.0 learning_rate = 0.1 gradient = 3.0 theta = theta - learning_rate * gradient print(round(theta, 2))
theta = 5.0 learning_rate = 0.01 gradient = -4.0 theta = theta + learning_rate * gradient print(theta)
Pass the test and this pattern moves unknown