🤖 AI/ML

Gradient Descent

Gradient Descent

An optimization algorithm that minimizes a loss function. Core to deep learning training.

📖 Detailed Explanation

Gradient Descent is an optimization algorithm that iteratively updates parameters in the direction opposite to the gradient in order to find the minimum of a loss function. It is the core mechanism for efficiently training millions of weights in deep learning and underlies the training of all neural networks.

Proposed by Cauchy in 1847, this algorithm was combined with Rumelhart's 1986 backpropagation paper and became the foundation of modern deep learning. When AlexNet won the ImageNet competition in 2012, the effectiveness of large-scale GPU-based gradient descent training was demonstrated.

The core principle is to calculate the gradient of the loss function at the current position and move in the opposite direction by the learning rate. It is expressed by the formula w = w - lr * gradient(L), and this process is repeated until the loss becomes sufficiently small.

In practice, Mini-batch SGD, which uses mini-batches, is the standard rather than Batch GD, which uses the entire dataset. Variant algorithms such as Adam, AdaGrad, and RMSprop automatically adjust the learning rate, greatly improving convergence speed and stability.

💻 Code Example

import numpy as np

# 간단한 Gradient Descent 구현
def gradient_descent(X, y, learning_rate=0.01, epochs=1000):
    m, n = X.shape
    weights = np.zeros(n)
    bias = 0

    for epoch in range(epochs):
        # 예측값 계산
        y_pred = np.dot(X, weights) + bias

        # 손실 계산 (MSE)
        loss = np.mean((y_pred - y) ** 2)

        # 그래디언트 계산
        dw = (2/m) * np.dot(X.T, (y_pred - y))
        db = (2/m) * np.sum(y_pred - y)

        # 파라미터 업데이트
        weights -= learning_rate * dw
        bias -= learning_rate * db

        if epoch % 100 == 0:
            print(f"Epoch {epoch}, Loss: {loss:.4f}")

    return weights, bias

# 사용 예시
X = np.random.randn(100, 3)
y = 2*X[:, 0] + 3*X[:, 1] - X[:, 2] + np.random.randn(100)*0.1
weights, bias = gradient_descent(X, y, learning_rate=0.1, epochs=500)

🗣️ Say It Like This in Practice

In a model tuning meeting

"The loss keeps oscillating because the learning rate is too high. If you lower it from 0.001 to 0.0001 and switch to the Adam optimizer, gradient descent should converge stably."

In a technical interview

"The difference between SGD and Mini-batch GD is the number of samples used per update. SGD uses 1 sample, so it is noisy but fast, while Mini-batch typically uses 32-256 samples, which reduces the variance of the gradient estimate and makes it stable."

In a code review

"Training without gradient clipping can cause the exploding gradient problem. It would be good to limit it to about max_norm=1.0 with torch.nn.utils.clip_grad_norm_."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

1
Learning Rate Setting Mistakes

If it is too large, training diverges, and if it is too small, training is slow. Use a learning rate scheduler or an adaptive optimizer such as Adam.

2
Local Minimum Problem

With non-convex functions, training can get stuck in a local minimum rather than the global minimum. Try Momentum or training from multiple initial values.

3
Feature Scaling Not Applied

If the input features have different scales, the gradient direction is distorted. Be sure to normalize with StandardScaler or MinMaxScaler.

🔗 Related Terms

📚 Learn More