Gradient Descent is an optimisation algorithm used to minimize a model’s error by iteratively adjusting its parameters. By moving step‑by‑step in the direction of the steepest decrease in the loss function, it helps machine learning models learn the best possible weights for better predictions.
- Essential for training neural networks and regression models
- Works by updating parameters based on calculated gradients
- Variants include Batch, Stochastic and Mini‑Batch Gradient Descent
Let's see Gradient Descent in various Machine learning Algorithms:
1) Linear Regression
Linear Regression is a supervised learning algorithm used for predicting continuous numerical values. It models the relationship between inputs and outputs by fitting the best linear function to the data. The objective is to minimize prediction errors using the Mean Squared Error (MSE) loss function.
\hat{y} = wx + b
L = \frac{1}{2n}\sum_{i=1}^n (y_i - \hat{y}_i)^2
Where:
x : input featurew : weight (slope of the line)b : bias/intercept-
\hat y : predicted output -
y_i : true target value n : number of samplesL : MSE loss
Role of Gradient Descent
- Computes gradients of the MSE loss with respect to slope and intercept.
- Iteratively updates weights in the direction that reduces prediction error.
- Works efficiently when analytical solutions are slow or infeasible.
Advantages
- Scales better than the Normal Equation for large datasets.
- Allows online or mini-batch updates for streaming data.
- Works even when data is high-dimensional.
Example:
- The model predicts values using the equation
\hat{y} = wx + b . - Error is computed as the difference between predictions and actual values.
- The gradients dw and db are calculated from the MSE loss.
- Gradient descent updates the parameters using w -= lr * dw and b -= lr * db.
- The first plot shows how the loss decreases over epochs.
- The second plot visualizes the best-fit regression line learned by gradient descent.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
n = 200
X = np.linspace(-3, 3, n).reshape(-1, 1)
y = 2 * X.ravel() - 0.3 + 0.7 * np.random.randn(n)
w, b = 0.0, 0.0
lr = 0.05
epochs = 200
losses = []
for _ in range(epochs):
preds = w * X.ravel() + b
err = preds - y
loss = (err**2).mean() / 2
losses.append(loss)
dw = (X.ravel() * err).mean()
db = err.mean()
w -= lr * dw
b -= lr * db
plt.figure()
plt.plot(losses, color="green")
plt.title("Linear Regression — Loss (MSE)")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.show()
plt.figure()
plt.scatter(X, y, color="lightgreen")
idx = np.argsort(X.ravel())
plt.plot(X[idx], (w * X + b)[idx], color="green", linewidth=2)
plt.title("Linear Regression — Fitted Line")
plt.xlabel("x")
plt.ylabel("y")
plt.grid(True)
plt.show()
Output:
2) Logistic Regression (Binary Classification)
Logistic Regression is used to classify data into two categories by modeling the probability of belonging to a class. It transforms linear outputs through the sigmoid function to ensure predictions lie between 0 and 1. The model is optimized by minimizing cross-entropy loss, which penalizes incorrect confidence in predictions.
\sigma(z) = \frac{1}{1 + e^{-z}}
L = -\frac{1}{n}\sum_{i=1}^{n} \left( y_i\ln(\hat{p}_i) + (1 - y_i)\ln(1 - \hat{p}_i) \right)
Where:
𝑧=𝑤⋅𝑥+𝑏 : linear combination\sigma(z) : sigmoid output-
\hat P_i : predicted probability y_i \in \{0,1\} : actual labeln : number of samplesL : cross-entropy loss
Role of Gradient Descent
- Computes gradients of cross-entropy loss.
- Updates weights to improve probability estimates.
- Ensures convergence despite nonlinear sigmoid.
Advantages
- Works well for binary classification problems.
- Efficient and scalable for large datasets.
- Naturally outputs class probabilities.
Example:
- The model computes logits using X.dot(w) + b.
- Sigmoid activation converts logits into probabilities.
- Cross-entropy loss is calculated to measure classification error.
- Gradients dw and db come from the derivative of cross-entropy.
- Gradient descent updates weights and bias every epoch.
- The loss plot shows convergence of the model.
- The contour plot visualizes the classification boundary learned by GD.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
np.random.seed(1)
X, y = make_blobs(n_samples=300, centers=2, cluster_std=1.2)
w = np.zeros(X.shape[1])
b = 0.0
lr = 0.2
losses = []
def sigmoid(z): return 1 / (1 + np.exp(-z))
for _ in range(300):
z = X.dot(w) + b
p = sigmoid(z)
loss = -(y * np.log(p + 1e-12) + (1 - y) * np.log(1 - p + 1e-12)).mean()
losses.append(loss)
dw = X.T.dot(p - y) / len(X)
db = (p - y).mean()
w -= lr * dw
b -= lr * db
plt.figure()
plt.plot(losses, color="green")
plt.title("Logistic Regression — Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.show()
xx, yy = np.meshgrid(
np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 200),
np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 200)
)
grid = np.c_[xx.ravel(), yy.ravel()]
probs = sigmoid(grid.dot(w) + b).reshape(xx.shape)
plt.figure()
plt.contourf(xx, yy, probs, 20, cmap="Greens")
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Greens", edgecolor="black")
plt.title("Logistic Regression — Decision Boundary")
plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
Output:
3) Softmax Regression (Multiclass Classification)
Softmax Regression generalizes logistic regression to handle multiclass problems. Instead of predicting a single probability, it outputs a probability distribution across multiple categories. The optimization goal is to minimize multiclass cross-entropy loss, ensuring that predicted probabilities are well-aligned with actual class labels.
\hat{p}_{i,k} = \frac{e^{z_{i,k}}}{\sum_{j=1}^{K} e^{z_{i,j}}}
L = -\frac{1}{n}\sum_{i=1}^{n}\sum_{k=1}^{K} y_{i,k}\ln(\hat{p}_{i,k})
Where:
z_{i,k} : score(logit) for class k for sample i\hat P_{i,k} : probability that sample i belongs to class kK : number of classes-
y_{i,k} : one-hot encoded true label n : number of samplesL : multiclass cross-entropy loss
Role of Gradient Descent
- Calculates gradients for each class's weight vector.
- Updates weights to adjust class probabilities.
- Supports efficient multiclass training.
Advantages
- Works well for datasets with multiple categories.
- Can learn linear class boundaries effectively.
- Compatible with mini-batch training for scalability.
Example:
- Uses a weight matrix W because there are multiple classes.
- Softmax converts logits into class-wise probabilities.
- Multiclass cross-entropy loss is computed.
- Gradients dW and db update all classes simultaneously using GD.
- The loss curve shows decreasing error.
- The contour plot shows class regions learned by GD.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
np.random.seed(2)
X, y = make_blobs(n_samples=450, centers=3, cluster_std=1.5)
K = 3
W = np.zeros((X.shape[1], K))
b = np.zeros(K)
lr = 0.2
epochs = 300
losses = []
def softmax(z):
z -= z.max(axis=1, keepdims=True)
expz = np.exp(z)
return expz / expz.sum(axis=1, keepdims=True)
for _ in range(epochs):
logits = X.dot(W)+b
probs = softmax(logits)
Y = np.zeros_like(probs); Y[np.arange(len(y)), y] = 1
loss = -np.sum(Y*np.log(probs+1e-12))/len(X)
losses.append(loss)
dW = X.T.dot(probs-Y)/len(X)
db = (probs-Y).mean(axis=0)
W -= lr*dW
b -= lr*db
plt.figure()
plt.plot(losses, color="green")
plt.title("Softmax Regression — Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.show()
xx, yy = np.meshgrid(
np.linspace(X[:,0].min()-1, X[:,0].max()+1, 300),
np.linspace(X[:,1].min()-1, X[:,1].max()+1, 300)
)
grid = np.c_[xx.ravel(), yy.ravel()]
preds = np.argmax(softmax(grid.dot(W)+b), axis=1).reshape(xx.shape)
plt.figure()
plt.contourf(xx, yy, preds, K, cmap="Greens")
plt.scatter(X[:,0], X[:,1], c=y, cmap="Greens", edgecolor="black")
plt.title("Softmax Regression — Class Regions")
plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
Output:
4) Neural Network (1 Hidden Layer)
A neural network with one hidden layer can learn nonlinear relationships that linear models cannot capture. It performs layered transformations using activation functions such as ReLU, enabling it to model complex patterns in the data. The output layer applies softmax to produce class probabilities and training is done via backpropagation.
Hidden Layer:
a^{(1)} = \text{ReLU}(W^{(1)}x + b^{(1)})
Output Layer:
\hat{y} = \text{softmax}(W^{(2)}a^{(1)} + b^{(2)})
Loss:
L = -\sum_{k=1}^{K} y_k \ln(\hat{y}_k)
Where:
W^{(1)},W^{(2)} : weight matricesb^{(1)},b^{(2)} : bias vectorsa^{(1)} : hidden layer activationsx : input vector\hat y : softmax output probabilitiesy_k : true class label (one-hot)K : number of classesL : cross-entropy loss
Role of Gradient Descent
- Updates each layer's weights using gradients from backpropagation.
- Reduces prediction error across all layers.
- Enables deep learning with nonlinear boundaries.
Advantages
- Learns complex, nonlinear structures.
- Highly flexible and powerful for classification.
- Works efficiently with mini-batch GD.
Example:
- Performs forward pass through a hidden ReLU layer and softmax output.
- Backpropagation computes gradients for both layers.
- GD updates weight matrices W1 and W2 and biases.
- Loss decreases over epochs, showing successful learning.
- Decision boundary plot shows nonlinear boundaries learned via GD.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
np.random.seed(3)
X, y = make_blobs(n_samples=450, centers=3, cluster_std=1.5)
K = 3
D = X.shape[1]
H = 32
W1 = np.random.randn(D, H) * np.sqrt(2 / D)
b1 = np.zeros(H)
W2 = np.random.randn(H, K) * np.sqrt(2 / H)
b2 = np.zeros(K)
lr = 0.05
epochs = 200
batch = 64
losses = []
relu = lambda z: np.maximum(0, z)
def softmax(z):
z -= z.max(axis=1, keepdims=True)
expz = np.exp(z)
return expz / expz.sum(axis=1, keepdims=True)
for _ in range(epochs):
idx = np.random.permutation(len(X))
Xs, Ys = X[idx], y[idx]
for i in range(0, len(Xs), batch):
xb = Xs[i:i + batch]
yb = Ys[i:i + batch]
z1 = xb.dot(W1) + b1
a1 = relu(z1)
logits = a1.dot(W2) + b2
probs = softmax(logits)
Yb = np.zeros_like(probs)
Yb[np.arange(len(yb)), yb] = 1
dlog = (probs - Yb) / len(yb)
dW2 = a1.T.dot(dlog)
db2 = dlog.sum(axis=0)
da1 = dlog.dot(W2.T)
dz1 = da1 * (z1 > 0)
dW1 = xb.T.dot(dz1)
db1 = dz1.sum(axis=0)
W2 -= lr * dW2
b2 -= lr * db2
W1 -= lr * dW1
b1 -= lr * db1
logits_full = relu(X.dot(W1) + b1).dot(W2) + b2
pf = softmax(logits_full)
Yf = np.zeros_like(pf)
Yf[np.arange(len(y)), y] = 1
losses.append(-(Yf * np.log(pf + 1e-12)).mean())
plt.figure()
plt.plot(losses, color="green")
plt.title("Neural Network — Loss")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.show()
xx, yy = np.meshgrid(
np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 300),
np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 300)
)
grid = np.c_[xx.ravel(), yy.ravel()]
pred = np.argmax(softmax(relu(grid.dot(W1) + b1).dot(W2) + b2),
axis=1).reshape(xx.shape)
plt.figure()
plt.contourf(xx, yy, pred, K, cmap="Greens")
plt.scatter(X[:, 0], X[:, 1], c=y, cmap="Greens", edgecolor="black")
plt.title("Neural Network — Decision Regions")
plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
Output:
5) SVM (Hinge Loss)
A Support Vector Machine finds a hyperplane that maximizes the margin between classes, providing robust classification. It uses hinge loss, which penalizes points that fall within the margin or are misclassified. The optimization aims to achieve the widest possible separation between the two classes.
L = \frac{1}{2}\|w\|^2 + C \cdot \max(0, 1 - y(w \cdot x + b))
Where:
w : weight vectorb : bias termx : inputy \in \{-1,+1\} : class labelC : regularization strengthmax(0,1−y(w⋅x+b)) : hinge lossL : total SVM objective
Role of Gradient Descent
- Applies subgradient descent to handle non-differentiable hinge loss.
- Adjusts parameters based on margin violations.
- Optimizes balance between margin size and classification errors.
Advantages
- Produces robust linear classifiers.
- Resistant to outliers compared to logistic regression.
- Simple to optimize in primal space with GD.
Example:
- Computes hinge loss using 1 - y*(w·x + b).
- Uses subgradient because hinge loss is not fully differentiable.
- Updates occur only for margin-violating points.
- Objective curve decreases steadily with GD.
- Final contour visualizes the learned separating hyperplane.
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
np.random.seed(4)
X, y_binary = make_blobs(n_samples=300, centers=2, cluster_std=1.2)
y = 2 * y_binary - 1
w = np.zeros(X.shape[1])
b = 0.0
lr = 0.01
C = 1.0
epochs = 500
losses = []
for _ in range(epochs):
margins = y * (X.dot(w) + b)
hinge = np.maximum(0, 1 - margins)
loss = 0.5 * np.dot(w, w) + C * hinge.mean()
losses.append(loss)
mask = margins < 1
if mask.any():
dw = w - (C / len(X)) * X[mask].T.dot(y[mask])
db = -(C / len(X)) * y[mask].sum()
else:
dw = w
db = 0.0
w -= lr * dw
b -= lr * db
plt.figure()
plt.plot(losses, color="green")
plt.title("Linear SVM (hinge) — Objective")
plt.xlabel("Epoch")
plt.ylabel("Objective")
plt.grid(True)
plt.show()
xx, yy = np.meshgrid(
np.linspace(X[:, 0].min() - 1, X[:, 0].max() + 1, 200),
np.linspace(X[:, 1].min() - 1, X[:, 1].max() + 1, 200)
)
grid = np.c_[xx.ravel(), yy.ravel()]
scores = grid.dot(w) + b
plt.figure()
plt.contourf(xx, yy, (scores.reshape(xx.shape) > 0).astype(int), cmap="Greens")
plt.scatter(X[:, 0], X[:, 1], c=y_binary, cmap="Greens",
edgecolor="black", alpha=0.85)
plt.title("Linear SVM — Decision Boundary (approx)")
plt.xlabel("x1")
plt.ylabel("x2")
plt.show()
Output:
6) Matrix Factorization
Matrix Factorization decomposes a user–item rating matrix into lower-dimensional latent factors. These factors reveal hidden user preferences and item attributes. The model predicts missing ratings by reconstructing the full matrix from the learned factors making it crucial in recommender systems.
Reconstruction:
R \approx P Q^T
Loss:
L = \sum_{(i,j)\in\Omega} (R_{ij} - P_iQ_j^T)^2 + \lambda (\|P\|^2 + \|Q\|^2)
Where:
R : rating matrixP : user latent matrixQ : item latent matrix\Omega : observed user-item pairsR_{ij} : actual ratingP_iQ^T_j : predicted rating\lambda : regularization strengthL : reconstruction loss
Role of Gradient Descent
- Performs SGD on observed entries to update latent vectors.
- Minimizes reconstruction error and regularization penalty.
- Learns user and item embeddings that generalize well.
Advantages
- Works well with sparse rating matrices.
- Scales efficiently to large real-world datasets.
- Produces interpretable latent features.
Example:
- Factorizes matrix into latent user vectors P and item vectors Q.
- For each observed rating, computes prediction and error.
- Gradients update P[i] and Q[j] using SGD.
- Loss curve shows reconstruction improvement.
- Final two plots show observed vs reconstructed rating matrices.
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(5)
n_users, n_items = 30, 25
true_k = 4
P_true = np.random.randn(n_users, true_k)
Q_true = np.random.randn(n_items, true_k)
R_full = P_true.dot(Q_true.T)
mask = np.random.rand(n_users, n_items) < 0.4
R = np.where(mask, R_full + 0.5 * np.random.randn(n_users, n_items), 0.0)
k = 4
P = 0.1 * np.random.randn(n_users, k)
Q = 0.1 * np.random.randn(n_items, k)
lr = 0.01
epochs = 80
reg = 0.1
losses = []
obs = np.argwhere(mask)
for _ in range(epochs):
np.random.shuffle(obs)
for i, j in obs:
pred = P[i].dot(Q[j])
err = R[i, j] - pred
dP = -2 * err * Q[j] + 2 * reg * P[i]
dQ = -2 * err * P[i] + 2 * reg * Q[j]
P[i] -= lr * dP
Q[j] -= lr * dQ
pred_all = P.dot(Q.T)
diff = mask * (R - pred_all)
loss = (diff**2).sum() / mask.sum() + reg * (np.sum(P**2) + np.sum(Q**2))
losses.append(loss)
plt.figure()
plt.plot(losses, color="green")
plt.title("Matrix Factorization — Loss (observed)")
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.grid(True)
plt.show()
recon = P.dot(Q.T)
plt.figure(figsize=(10, 4))
plt.subplot(1, 2, 1)
plt.imshow(np.where(mask, R, np.nan), aspect='auto', cmap="Greens")
plt.title("Observed Ratings")
plt.xlabel("Item index")
plt.ylabel("User index")
plt.colorbar(shrink=0.6)
plt.subplot(1, 2, 2)
plt.imshow(recon, aspect='auto', cmap="Greens")
plt.title("Reconstructed Matrix")
plt.xlabel("Item index")
plt.ylabel("User index")
plt.colorbar(shrink=0.6)
plt.tight_layout()
plt.show()
Output:
From all examples we can see gradient descent helped us improve our model prediction by reducing their loss and choosing optimal weights for them.
Applications
- Training Neural Networks: Updates weights using backpropagation, allowing deep models like CNNs, RNNs, LSTMs and Transformers to learn complex patterns.
- Linear and Logistic Regression: Minimizes prediction or classification error by optimizing model coefficients when analytical solutions are not feasible.
- Support Vector Machines: Optimizes hinge loss to adjust the separating hyperplane for maximum-margin classification.
- Multiclass Classification: Learns class-specific weight vectors by minimizing multiclass cross-entropy to produce probability distributions.
- Matrix Factorization for Recommender Systems: Learns user and item latent factors using gradient descent to predict missing ratings and generate personalized recommendations.

