Sure, here is an example of gradient descent implemented from scratch in Python:
import numpy as np
# Function to compute the gradient of a function with respect to a vector
def gradient(f, X):
return np.array([np.gradient(f, X)[0] for i in range(X.shape[0])])
# Function to perform gradient descent
def gradient_descent(f, X, alpha, iterations):
# Initialize the weights to random values
w = np.random.randn(X.shape[1], 1)
# Perform iterations of gradient descent
for i in range(iterations):
# Compute the gradient of the function with respect to the weights
grad = gradient(f, X)
# Update the weights using the gradient and learning rate
w -= alpha * grad
return w
This code defines two functions: gradient and gradient_descent. The gradient function takes a function f and a vector X, and computes the gradient of f with respect to X. The gradient_descent function takes a function f, a vector X, a learning rate alpha, and a number of iterations iterations, and performs gradient descent on f using X and alpha for the specified number of iterations.
You can use this code to train a model by defining a function f that computes the loss of the model, and then calling gradient_descent with the appropriate parameters. For example:
# Define the function to compute the loss of the model
def loss(y_true, y_pred):
return np.mean((y_true - y_pred) ** 2)
# Define the function to compute the gradient of the loss with respect to the weights
def loss_gradient(y_true, y_pred, X):
return gradient(loss, X)
# Train the model using gradient descent
X = np.array([[1], [2], [3]])
y_true = np.array([2, 4, 6])
w = gradient_descent(loss_gradient, X, 0.1