পাঠ ১১ · ৪৫-এর মধ্যে · মডিউল ২
Home / AI Courses / Machine Learning / Gradient Descent

Gradient descent প্রয়োগ

GD for linear regression
৭ মিনিট পড়া মাঝারি · Intermediate NumPy কোডসহ

এই পাঠে যা শিখবেন

  • Gradient descent — intuition, formula, ও geometry
  • Linear regression-এ MSE-র gradient — derivation
  • Learning rate — কেন critical, কী fail mode
  • Batch, SGD, Mini-batch — কখন কোনটি

১ · Intuition — পাহাড় থেকে নামা

ভাবুন আপনি ঘন কুয়াশায় একটি পাহাড়ের উপর। নিচে নামতে চান, কিন্তু কিছু দেখা যাচ্ছে না। কী করবেন? — পায়ের নিচে কোন দিকে slope সবচেয়ে বেশি — সেদিকে এক step যান। আবার slope check, আবার step। ধীরে ধীরে valley-এ পৌঁছাবেন।

Loss surface-এ একই কাজ করে Gradient DescentGradient Descent (GD)Loss function-এর gradient ব্যবহার করে parameters update — সর্বনিম্ন loss-এর দিকে। Cauchy ১৮৪৭-এ প্রথম describe। আজকের সব ML/DL training-এর foundation।। Gradient — slope-এর "steepest ascent" দিক। তাই $-$gradient = "steepest descent"।

Update rule

$$\mathbf{w}_{t+1} = \mathbf{w}_t - \eta \, \nabla_{\mathbf{w}} L(\mathbf{w}_t)$$

$\eta$ — learning rate (step size)। ছোট হলে slow। বড় হলে overshoot হতে পারে।

২ · Linear regression-এ gradient

Loss:

$$L(\mathbf{w}, b) = \frac{1}{N} \sum_{i=1}^{N} (y_i - \mathbf{w}^\top \mathbf{x}_i - b)^2$$

$\mathbf{w}$-র সাপেক্ষে partial derivative:

$$\frac{\partial L}{\partial \mathbf{w}} = -\frac{2}{N} \sum_{i=1}^{N} (y_i - \mathbf{w}^\top \mathbf{x}_i - b) \mathbf{x}_i$$

$b$-র সাপেক্ষে:

$$\frac{\partial L}{\partial b} = -\frac{2}{N} \sum_{i=1}^{N} (y_i - \mathbf{w}^\top \mathbf{x}_i - b)$$

Vectorized form (residual $r_i = y_i - \hat{y}_i$):

$$\nabla_{\mathbf{w}} L = -\frac{2}{N} X^\top \mathbf{r}, \quad \nabla_b L = -\frac{2}{N} \sum r_i$$

৩ · জ্যামিতিক ছবি

Linear regression-এর loss $L(w, b)$ — quadratic, bowl-shaped। প্রতিটি iteration — bowl-এর floor-এর দিকে এক step। Convex surface-এ — সঠিক learning rate দিলে guaranteed minimum-এ পৌঁছানো।

Gradient Descent — Loop ১. Predict ŷ = Xw + b ২. Loss L = mean((y − ŷ)²) ৩. Gradient ∇L (w, b-এর সাপেক্ষে) ৪. Update w ← w − η ∇L repeat 📉 Loss Surface — Bowl Shape start min
Loop চলে — predict → loss → gradient → update। প্রতি iteration-এ minimum-এর কাছে।

৪ · NumPy দিয়ে — শূন্য থেকে

Python · NumPy
import numpy as np

# Data
X_raw = np.array([500, 800, 1200, 1500, 2000, 2500])
y = np.array([25, 40, 55, 70, 95, 120])

# Normalize (gradient descent-এ critical)
X_norm = (X_raw - X_raw.mean()) / X_raw.std()
y_norm = (y - y.mean()) / y.std()

# Initialize
w, b = 0.0, 0.0
lr = 0.1
N = len(X_norm)

for epoch in range(1000):
    y_hat = w * X_norm + b
    error = y_norm - y_hat

    grad_w = -2 * np.mean(error * X_norm)
    grad_b = -2 * np.mean(error)

    w -= lr * grad_w
    b -= lr * grad_b

    if epoch % 100 == 0:
        loss = np.mean(error ** 2)
        print(f"Epoch {epoch:4d}: loss={loss:.6f}, w={w:.4f}, b={b:.4f}")

print(f"\nFinal: w={w:.4f}, b={b:.4f}")

    
Loss প্রতিটি epoch-এ কমছে। ১,০০০ iteration-এ converge। Normalization important — না করলে gradient explode হতে পারে।

৫ · Learning rate — সবচেয়ে গুরুত্বপূর্ণ hyperparameter

$\eta$ ছোট (যেমন ০.০০০১) — slow convergence, hour-হাজার iteration লাগে।
$\eta$ বড় (যেমন ১.০) — overshoot, loss diverge। NaN পর্যন্ত যেতে পারে।
$\eta$ ঠিক (০.০১-০.১) — দ্রুত converge।

Python · NumPy
import numpy as np

X_raw = np.array([500, 800, 1200, 1500, 2000, 2500])
y = np.array([25, 40, 55, 70, 95, 120])

X = (X_raw - X_raw.mean()) / X_raw.std()
y_n = (y - y.mean()) / y.std()

# তিন learning rate compare
for lr in [0.001, 0.1, 1.5]:
    w, b = 0.0, 0.0
    for epoch in range(50):
        y_hat = w * X + b
        err = y_n - y_hat
        w -= lr * (-2 * np.mean(err * X))
        b -= lr * (-2 * np.mean(err))
    final_loss = np.mean((y_n - (w*X + b)) ** 2)
    print(f"lr={lr:5.3f}: final loss = {final_loss:.4f}, w={w:.3f}")

    
$lr = 0.001$ — slow। $lr = 0.1$ — converged। $lr = 1.5$ — diverge (loss massive বা NaN)।

৬ · তিন variant — Batch, SGD, Mini-batch

  • Batch GD: পুরো dataset দিয়ে gradient। Stable কিন্তু slow per iteration।
    Update: $\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla L_{\text{full}}$।
  • Stochastic GD (SGD): এক sample দিয়ে gradient। Fast কিন্তু noisy।
    Update per sample: $\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla L_i$।
  • Mini-batch GD: ৩২/৬৪/১২৮ samples-এর batch। Balance — DL-এর default।
    Update: $\mathbf{w} \leftarrow \mathbf{w} - \eta \nabla L_{\text{batch}}$।
"SGD" naming history-গত — actually আজকের "SGD" সাধারণত mini-batch। Pure single-sample SGD rarely used।

৭ · Mini-batch SGD — practical implementation

Python · NumPy
import numpy as np

np.random.seed(0)
N = 1000
X = np.random.randn(N, 3)
true_w = np.array([2.0, -1.5, 0.5])
y = X @ true_w + 3.0 + np.random.normal(0, 0.5, N)

# Initialize
w = np.zeros(3)
b = 0.0
lr = 0.05
batch_size = 32

for epoch in range(50):
    idx = np.random.permutation(N)
    for start in range(0, N, batch_size):
        batch = idx[start:start+batch_size]
        Xb, yb = X[batch], y[batch]

        y_hat = Xb @ w + b
        err = yb - y_hat

        grad_w = -2 * Xb.T @ err / len(batch)
        grad_b = -2 * np.mean(err)

        w -= lr * grad_w
        b -= lr * grad_b

    if epoch % 10 == 0:
        loss = np.mean((y - (X @ w + b)) ** 2)
        print(f"Epoch {epoch:2d}: loss={loss:.4f}")

print(f"\nlearned w = {w}")
print(f"true w    = {true_w}")
print(f"learned b = {b:.3f}, true b = 3.0")

    
Mini-batch SGD — true weights recover। Production DL-এ এটাই workflow। Batch shuffling প্রতি epoch-এ — important।

৮ · Convergence diagnose

  • Loss curve: প্রতি epoch loss plot। Smooth decrease → ভাল। Spike/oscillation → lr বড়।
  • Gradient norm: $\|\nabla L\|$ → ০ মানে minimum কাছাকাছি।
  • Validation loss: Train কমছে, val বাড়ছে → overfitting শুরু।
  • Early stopping: Val loss stagnate হলে থামান।

৯ · Modern variants — preview

  • Momentum: Previous gradient-এর memory — ravine-এ smooth movement।
  • Adam: Adaptive learning rate per parameter। DL-এর default।
  • RMSprop: Adaptive — সব parameter-এর আলাদা scale।
  • Learning rate scheduling: ধীরে ধীরে lr কমানো।
Linear regression-এর convex surface-এ যেকোনো GD variant guaranteed converge। Neural networks-এর non-convex surface-এ — local minimum trap, saddle points নিয়ে চিন্তা করতে হবে। তবু এই concept সর্বত্র apply।

ভাবনার প্রশ্ন

প্রতিটি প্রশ্ন নিজে কিছুক্ষণ ভাবুন — তারপর "→ উত্তর" চাপুন।

প্র ০১ "Feature scaling না করলে gradient descent fail" — কেন? Closed-form OLS-এ scaling গুরুত্বপূর্ণ নয় কেন?

Feature scaling — GD-র জন্য make-or-break। প্রায়ই beginner বুঝে না কেন।

সমস্যা:

  • Feature ১: "age" — range ০-১০০।
  • Feature ২: "income" — range ০-১০M।
  • Loss surface — extremely elongated ellipse।
  • Gradient — large feature-এর দিকে dominate।

Geometric intuition:

  • Scaled features — circular bowl।
  • Direct path to minimum।
  • Same lr সব direction-এ কাজ করে।

Unscaled features:

  • Long, narrow valley (canyon)।
  • Gradient — narrow direction-এ steep, long-এ shallow।
  • "Zigzag" pattern — slow convergence।
  • Sometimes diverge।

Scaling techniques:

  • StandardScaler: $(x - \mu) / \sigma$ — zero mean, unit variance।
  • MinMaxScaler: $[0, 1]$ range।
  • RobustScaler: Outlier-robust।

Closed-form-এ কেন matter না:

  • OLS — analytic solution।
  • Direct compute — iterative steps নেই।
  • Scaling — answer same (numerically slightly different)।
  • Coefficient interpretation — scale-dependent।

Subtle issues even in closed-form:

  • Numerical stability — extreme magnitudes-এ problems।
  • Regularization — scaling-dependent (Ridge penalty unfair)।
  • Best practice: always scale।

Production tip:

  • Train-এ fit, test-এ apply (no leakage)।
  • Pipeline-এ wrap।
  • Deploy-এ same scaler।

Neural networks:

  • Even more critical।
  • BatchNorm — internal scaling।
  • LayerNorm — Transformer।
  • "Always normalize" — DL gospel।

মূল উপলব্ধি: Iterative methods scale-sensitive। Closed-form not, but practical considerations push scaling everywhere। GD পাঠ — scale habit গড়ার সুযোগ।

প্র ০২ SGD-এর "noise" আশীর্বাদ না অভিশাপ? Mini-batch size ছোট/বড় কোন effect — গণিত ও empirical দু'দিক থেকে?

SGD — modern ML-এর engine। Noise-এর role surprisingly complex।

SGD-র দৃশ্যমান behavior:

  • Loss curve — wiggle (noisy)।
  • Final convergence — minimum-এর "neighborhood"।
  • Exact minimum-এ stop করে না।

Noise-এর সুবিধা:

(১) Local minima escape:

  • Non-convex loss surface-এ — random kick local minimum বেরিয়ে আসতে সাহায্য করে।
  • Batch GD — local trap-এ stuck।
  • SGD — exploration through noise।

(২) Implicit regularization:

  • Noise — model "sharp minima" avoid করে।
  • Flat minima — better generalization।
  • Bayesian interpretation — implicit prior।

(৩) Computational efficiency:

  • Each step — small batch, fast।
  • Many steps possible per second।
  • Streaming data compatible।

(৪) Memory efficiency:

  • Large dataset RAM-এ fit না হলে essential।
  • GPU memory limited — batch-by-batch।

Noise-এর অসুবিধা:

  • Convergence noisy — hard to monitor।
  • Final accuracy slightly worse than full GD।
  • Hyperparameter sensitive (lr, batch size)।
  • Reproducibility issue।

Batch size — তিন regime:

(১) Small batch (1-16):

  • High noise — strong regularization।
  • Better generalization sometimes।
  • Slow per epoch।
  • GPU underutilized।

(২) Medium (32-256):

  • Sweet spot for most tasks।
  • GPU well-utilized।
  • Reasonable noise।
  • Default in most frameworks।

(৩) Large (1024+):

  • Less noise — close to batch GD।
  • Faster epochs।
  • Generalization gap reported (Keskar 2017)।
  • "Linear scaling rule" — lr ∝ batch size।

Theoretical perspective:

  • SGD ≈ GD + Gaussian noise (roughly)।
  • Noise variance ∝ 1/batch size।
  • Continuous time limit — Langevin dynamics।
  • "Implicit bias" theory active research।

Practical guidelines:

  • Computer vision: 32-128।
  • NLP: 16-64 (memory limits)।
  • Tabular: 64-512।
  • Empirically tune via val set।

Modern variants:

  • Adam — adaptive per-parameter।
  • LARS, LAMB — large batch training।
  • "Lion" optimizer — recent।

মূল উপলব্ধি: Noise — bug না, feature। Optimal batch size problem-dependent। "Bigger batch always better" — myth।

প্র ০৩ Linear regression convex — তবু GD সরাসরি minimum-এ যায় না, "approach" করে। কেন? Convergence rate কী?

Convexity — GD-এর জন্য আদর্শ shape। কিন্তু details subtle।

Convex function:

  • Bowl-shaped — single minimum।
  • Any local minimum = global minimum।
  • Gradient = ০ একমাত্র minimum-এ।

GD on convex function:

  • Guaranteed convergence (under right lr)।
  • "Asymptotic" — minimum-এ approach, exactly পৌঁছায় না।
  • "$\epsilon$-optimal" — minimum-এর $\epsilon$ neighborhood-এ stop।

Convergence rates:

(১) Convex + smooth ($L$-Lipschitz gradient):

  • $L(\mathbf{w}_t) - L^* \leq O(1/t)$।
  • "Sublinear" rate।
  • $\epsilon$-optimal: $O(1/\epsilon)$ iterations।

(২) Strongly convex ($\mu$-strong):

  • $L(\mathbf{w}_t) - L^* \leq O(\rho^t)$, $\rho < 1$।
  • "Exponential" / "linear" rate।
  • $\epsilon$-optimal: $O(\log(1/\epsilon))$ iterations।
  • Quadratic loss — strongly convex।

Linear regression case:

  • MSE quadratic — strongly convex।
  • Linear convergence — fast।
  • Practical: ১০০-১,০০০ iterations sufficient।

Why "approach" not reach:

  • Discrete steps — never exactly land on minimum।
  • Gradient → ০ as we approach — steps → ০।
  • Asymptotic behavior।

Stopping criteria:

  • Max iterations reached।
  • Loss change < threshold।
  • Gradient norm < threshold।
  • Validation loss not improving।

Acceleration:

  • Momentum: $O(1/t^2)$ vs $O(1/t)$ — Nesterov।
  • Conjugate gradient: Exact in $\leq n$ steps for linear systems।
  • Newton's method: Quadratic convergence — but expensive।

Non-convex reality:

  • Neural networks — non-convex।
  • Local minima theoretical concern।
  • Empirically — most local minima good।
  • "Lottery ticket hypothesis" — initialization matters।

Practical observation:

  • Linear regression — overkill to use GD typically।
  • Closed-form fast for small problems।
  • GD shines at scale + non-linearity।

মূল উপলব্ধি: Convex + linear regression = GD-র "ideal home"। Theory beautiful, practice approximate। Real ML-এ messy non-convex landscape — তবু concept identical।

প্র ০৪ "Vanishing/exploding gradients" — GD-এর famous problem। Linear regression-এ ঘটে কি? Deep network-এ কেন crucial?

Gradient pathologies — DL training-এর central challenge।

Linear regression-এ:

  • Single-layer — কোনো nesting নেই।
  • Gradient direct — input × residual।
  • "Vanishing" — minimum-এ approach করলে natural।
  • "Exploding" — খুব বড় feature-এ বা wrong scaling।

Linear-এ exploding scenarios:

  • Unscaled features (income in millions)।
  • Large lr — overshoot then more overshoot।
  • Numerical overflow।
  • NaN propagation।

Solutions in linear:

  • Scale features।
  • Reasonable lr।
  • Gradient clipping — extreme cases।

Deep networks-এ amplification:

  • Chain rule — gradient = product of layer gradients।
  • $L$ layers, each gradient $g$।
  • Total: $g^L$।
  • $g < 1$: vanishing — last layers শেখে না।
  • $g > 1$: exploding — divergence।

Why critical for DL:

  • Vanishing — early layers freeze, slow learning।
  • Exploding — NaN, training crash।
  • Both — model untrainable beyond a few layers।

Historical impact:

  • Pre-2010 — DL training stuck at ~5 layers।
  • Post — solutions enabled "deep" learning।
  • ResNet (2015) — skip connections — direct fix।

Modern solutions:

  • Initialization: Xavier (2010), He (2015) — variance preserving।
  • BatchNorm (2015): Internal normalization।
  • LayerNorm: Transformer standard।
  • Residual connections: Gradient highway।
  • Activation choice: ReLU — gradient ১ when positive।
  • Gradient clipping: Norm threshold।

RNN-এ extra severe:

  • Same weights repeated through time।
  • Long sequences — exponential blow-up/decay।
  • LSTM/GRU — gating mechanism — gradient flow control।
  • Transformer — attention বদলে recurrence — sidesteps।

Diagnostic:

  • Layer-wise gradient magnitude — uniform চাই।
  • TensorBoard/W&B histograms।
  • Loss spike — exploding warning।
  • Stagnation — vanishing warning।

Theoretical depth:

  • Mean field theory — depth-wise dynamics।
  • Edge of chaos — initialization at boundary।
  • Neural tangent kernel — wide network theory।

মূল উপলব্ধি: Linear regression-এ rare problem, deep network-এ existential threat। Modern DL-এর architectural choice (BN, ResNet, attention) — সবই এই সমস্যা solve করার জন্য। GD-র gradient flow understand করা — DL মাস্টার করার চাবি।

অনুশীলন

  1. হিসাব করুন: $w = 1$, $b = 0$। Data: $x = [1, 2]$, $y = [3, 5]$।
    • $\hat{y}, errors$ কত?
    • $\partial L / \partial w$ ও $\partial L / \partial b$ কত?
    • $\eta = 0.1$ দিয়ে এক step পরে $w, b$ কত?
    • $\hat{y} = [1, 2]$, errors $= [2, 3]$।
    • $\partial L / \partial w = -2 \cdot \text{mean}(x \cdot e) = -2 \cdot (2 + 6)/2 = -8$।
    • $\partial L / \partial b = -2 \cdot \text{mean}(e) = -2 \cdot 2.5 = -5$।
    • $w \leftarrow 1 - 0.1 \cdot (-8) = 1.8$, $b \leftarrow 0 - 0.1 \cdot (-5) = 0.5$।
  2. NumPy: উপরের data-তে full GD ১০ iterations চালান। Loss-এর pattern দেখুন।
    import numpy as np
    x, y = np.array([1, 2]), np.array([3, 5])
    w, b, lr = 0.0, 0.0, 0.1
    for i in range(10):
        err = y - (w*x + b)
        w -= lr * (-2 * np.mean(x * err))
        b -= lr * (-2 * np.mean(err))
        print(i, np.mean(err**2), w, b)
  3. চিন্তা: $\eta = 10$ দিলে কী হবে? Visualize লেখা ছাড়া predict করুন। তারপর কোডে check।

    $\eta$ অত্যন্ত বড় — overshoot। প্রতি step-এ minimum পার করে far। Loss exponentially বাড়বে। Eventually NaN/inf। Lesson: lr conservative শুরু।

আরও পড়ুন

কোড রানার কাজ না করলে? Google Colab ব্যবহার করুন।
পূর্ববর্তী পাঠ
পাঠ ১০ · OLS ও Normal Equations