2.2.4 · HinglishLinear & Logistic Regression

Cost function (MSE) and gradient descent fitting

3,463 words16 min readRead in English

2.2.4 · AI-ML › Linear & Logistic Regression

Overview

Linear regression mein, hum apne data ke through best-fit line dhundna chahte hain. Lekin "best" ka matlab kya hai? Humein ek tarika chahiye jo measure kare ki hamare predictions kitne galat hain, aur phir unhe systematically improve kare. Mean Squared Error (MSE) hamare galat hone ka measure hai, aur gradient descent humara systematic improvement algorithm hai.

Figure — Cost function (MSE) and gradient descent fitting

Hum absolute values ki jagah square isliye karte hain kyunki squared functions har jagah differentiable hote hain, jo hume calculus use karke minimum efficiently dhundhne deta hai.


Cost Function: Mean Squared Error

Jahan:

  • = cost function (jo hum minimize karna chahte hain)
  • = parameters (weights aur bias: )
  • simple linear regression ke liye
  • ek convenience factor hai jo derivatives lete waqt cancel ho jaata hai

First principles se derivation

Hume cost function ki zarurat kyun hai? Hamare paas training examples hain. Hamari hypothesis predictions generate karti hai . Har prediction mein ek error hai: .

Step 1: Total error measure karo Sum of errors: kaam nahi karega (positive aur negative cancel ho jaate hain) Sum of absolute errors: kaam karta hai lekin zero par differentiable nahi hai

Step 2: Errors ko square karo

Ye step kyun? Squaring se saare errors positive ho jaate hain, badi errors zyada penalize hoti hain, aur ek smooth surface banti hai jise hum calculus se optimize kar sakte hain.

Step 3: MSE paane ke liye average karo

Ye step kyun? se divide karne par cost dataset size se independent ho jaati hai—5 size ki 10 errors ka cost same hona chahiye chahe hamare paas 100 examples hon ya 1000.

Step 4: factor add karo

Ye step kyun? Jab hum derivative lete hain, power rule squaring se 2 ka factor neeche laata hai, jo ke saath cancel ho jaata hai. Isse gradient cleaner ban jaata hai.

  • Outer sum: Saare training examples ke errors accumulate karta hai
  • Inner difference: Prediction minus actual (residual)
  • Square: Errors ko quadratically penalize karta hai
  • Division by 2n: Normalize karta hai aur derivatives simplify karta hai

Gradient Descent: Minimum Dhundna

Gradient ek vector hai jo sabse steep increase ki direction mein point karta hai. Hum neeche utarne ke liye ulti direction mein jaate hain.

Gradient Descent Update Rule Derive karna

Step 1: Update formula likho (general form)

Jahan:

  • ka matlab hai "update to"
  • learning rate hai (step size)
  • parameter ke respect mein partial derivative (slope) hai

Ye form kyun? Agar slope positive hai (hum uphill par hain), derivative positive hai, toh hum use subtract karte hain (left/down jaate hain). Agar slope negative hai (hum downhill par hain), hum ek negative subtract karte hain (right/down jaate hain).

Step 2: Partial derivative compute karo Cost function se shuru karo:

Simple linear regression ke liye, .

ke respect mein derivative lo:

Ye step kyun? Hume jaanna hai ki mein ek choti si change cost ko kitna change karti hai.

Step 3: Chain rule apply karo

Ye step kyun? Chain rule: ki derivative hoti hai. Yahan .

2, ke saath cancel ho jaata hai:

Step 4: compute karo

ke liye (bias/intercept):

ke liye (slope):

Generally, ke liye: jahan example ka -th feature hai (bias term ke liye ke saath).

Step 5: Final gradient

Saare parameters simultaneously update karo:

Simultaneous ka matlab: purane values use karke saari nayi values compute karo, phir sab ek saath update karo.


Learning Rate

Bahut chota: Convergence slow hoti hai (bahut saare iterations chahiye) Bahut bada: Hum minimum overshoot kar sakte hain aur diverge ho sakte hain (cost badhti hai) Bilkul sahi: Minimum tak fast convergence

Typical values: . Aksar trial and error ya adaptive methods se milte hain.

Gradient tumhe direction batata hai; batata hai ki kitna door jaana hai.


Worked Examples

Goal: ko gradient descent se fit karo.

Initialize: , learning rate

Iteration 1:

  1. Predictions compute karo:

  2. Errors (residuals) compute karo:

  3. Cost compute karo:

  4. Gradients compute karo: Ye step kyun? Har error ko bias term ke liye se multiply kiya jaata hai.

    Ye step kyun? Har error ko corresponding value se multiply kiya jaata hai.

  5. Parameters update karo:

    Ye step kyun? Hum gradient ki ulti direction mein jaate hain (downhill).

Iteration 2 (naye se):

  1. Predictions:

  2. Errors:

  3. Cost:

    Ye step kyun? Cost 7.5 se 1.51 ho gayi—hum downhill move kar rahe hain!

Tab tak continue karo jab tak cost significantly decrease karna band na kar de (convergence).


Step 1: Prediction aur error compute karo

  • Error:

Step 2: Cost compute karo

Step 3: Gradient compute karo

Ye negative kyun hai? Hamari prediction (2) actual (5) se kam hai. Error negative hai. se multiply karne par, hume -6 milta hai. Ye negative gradient batata hai: badhao taaki better predictions ho sakein.

Step 4: Update karo ( ke saath)

Ye step kyun? Negative gradient subtract karne ka matlab hai add karna, isliye badhta hai, jo hamare predictions badhayega (2 ko 5 ke kareeb le jaayega).

Verification:

  • Nayi prediction: (5 ke zyada kareeb ✓)
  • Nayi cost: (4.5 se kam ✓)

Common Mistakes

Ye sahi kyun lagta hai: Lagta hai most recent value use karna logical hai.

Ye galat kyun hai: Gradient compute karte waqt assume kiya gaya tha ki dono parameters apni purani values par hain. Partially updated value use karne se gradient direction corrupt ho jaati hai.

Fix: Pehle saare gradients compute karo, phir saare parameters ek saath update karo.

# Galat
theta_0 = theta_0 - alpha * grad_0
theta_1 = theta_1 - alpha * grad_1  # NEW theta_0 indirectly use karta hai
 
# Sahi
temp_0 = theta_0 - alpha * grad_0
temp_1 = theta_1 - alpha * grad_1
theta_0 = temp_0
theta_1 = temp_1

Ye sahi kyun lagta hai: Derivation mein sum dikhta hai, toh bas sum use karo.

Ye galat kyun hai: se divide kiye bina, tumhara effective learning rate dataset size ke saath scale karta hai. Zyada data add karne par ko shrink karna padega, jo ise non-transferable bana deta hai.

Fix: Hamesha se divide karo:


Ye sahi kyun lagta hai: Lagta hai saara data use karne se ye faster hoga.

Actually: Ye stochastic gradient descent (SGD) hai, batch gradient descent nahi. Ye galat per se nahi hai, lekin ye ek alag algorithm hai alag properties ke saath:

  • Batch GD: Saara data use karta hai, stable convergence, iteration ke hisab se slower
  • SGD: Ek point use karta hai, noisy updates, iteration ke hisab se faster, exactly converge nahi ho sakta

Dono valid hain; bas jaano ki tum kaunsa use kar rahe ho!


Ye kyun hota hai: Tum minimum overshoot kar rahe ho. Har update valley ke doosri taraf jump kar jaata hai.

Fix:

  1. kam karo (10 se divide karke try karo)
  2. Iteration-wise cost monitor karo—batch GD mein ye monotonically decrease honi chahiye
  3. Learning rate schedules ya adaptive methods use karo (Adam, RMSprop)

Visual: Agar cost vs. iteration plot jagged upward trend dikhaye, bahut bada hai.


Convergence Criteria

Practice mein, cost function monitor karo. Agar ye meaningfully decrease karna band kar de, toh converge ho gaye.


Batch vs. Stochastic vs. Mini-Batch

Method Update Uses Pros Cons
Batch GD Saare examples Stable, exact gradient Bade ke liye slow
Stochastic GD 1 random example Fast, online learning Noisy, exactly converge nahi hota
Mini-batch GD examples (e.g., 32) Speed/stability balance Ek aur hyperparameter

Batch GD (jo humne derive kiya):

Stochastic GD:

Mini-batch GD:


Feature Scaling ka Impact

Solution: Features ko similar scales par normalize karo (e.g., mean 0, std 1):

Isse cost function zyada circular/spherical ban jaata hai, jo gradient descent ko bade learning rates ke saath faster converge karne deta hai.


Recall Ek 12-saal ke bachche ko samjhao

Socho tum ek graph par kuch dots ke through best line draw karne ki koshish kar rahe ho. Tumhe kaise pata chalega ki tumhari line achi hai? Tum measure karte ho ki har dot tumhari line se kitna door hai (that's the error). Phir tum saare errors add karte ho—lekin pehle unhe square karte ho taaki badi galtiyan choti wali se zyada count karein. Woh total tumhari "cost" hai. Cost jitni choti, line utni achi.

Ab, best line kaise dhundte hain? Ek random line se shuru karo. Phir dekho ki cost ko chhota karne ke liye use kis taraf tilt karna chahiye—jaise ball ko pahaad se neeche dhakka dena. Use thoda si us direction mein tilt karo. Phir dobara check karo aur aur tilt karo. Ye tab tak karte raho jab tak tumhari line itni achi na ho jaaye ki use aur tilt karna koi help nahi kare. Yahi gradient descent hai—ye tumhari line ko sikhata hai ki valley ke bottom tak pahunchne ke liye downhill walk karo, jahan cost sabse kam ho.

"Learning rate" batata hai tumhare kadam kitne bade hain. Bahut bade aur tum valley ke upar se jump kar jaoge. Bahut chote aur pahunchne mein forever lag jaayega.


  • Measure: compute karo = tum kitne galat ho
  • Squared: Errors squared hain (badi galtiyan zyada hurt karti hain)
  • Errors: Prediction aur actual ke beech difference
  • Go: Parameters ko ek direction mein move karo
  • Downhill: Gradient ki ulti direction (steepest descent)

Ya socho: "Mean Squared Errors Guide Descent"


Connections

  • 2.2.03-Hypothesis-representation-in-linear-regression — Hypothesis jo hum optimize kar rahe hain
  • 2.2.05-Normal-equation — Gradient descent ka closed-form alternative
  • 2.06-Feature-scaling-and-normalization — Gradient descent ki convergence faster banata hai
  • 2.3.02-Logistic-cost-function — Classification ke liye alag cost function
  • 2.4.01-Gradient-descent-for-neural-networks — Backpropagation is idea ko extend karta hai
  • 3.1.02-Convex-optimization — MSE convex hai, global minimum guarantee karta hai
  • 4.2.01-Stochastic-gradient-descent — Large datasets ke liye faster variant
  • 4.2.03-Learning-rate-schedules ke liye adaptive strategies

#flashcards/ai-ml

Linear regression ke liye Mean Squared Error (MSE) cost function kya hai? :: , jahan prediction hai aur actual value. dataset size se normalize karta hai aur derivatives simplify karta hai.

MSE mein absolute values ki jagah errors ko kyun square karte hain?
Squaring se saare errors positive ho jaate hain, badi errors zyada heavily penalize hoti hain (quadratic penalty), aur ek smooth, differentiable cost surface banti hai. Absolute values ka zero par non-differentiable point hota hai, jo optimization mushkil banata hai.

Parameter ke liye gradient descent update rule kya hai? :: , jahan learning rate hai aur partial derivative us parameter ke respect mein cost function ka gradient (slope) hai.

Linear regression mein parameter ke respect mein MSE ka gradient kya hai?
, jahan example ka -th feature hai (bias ke liye ke saath).
Gradient descent mein learning rate kya hai?
Learning rate ek hyperparameter hai jo negative gradient ki direction mein step size control karta hai. Bahut chota ho toh slow convergence; bahut bada ho toh overshoot aur divergence ka risk. Typical values: 0.001 se 1.
Gradient descent mein saare parameters ke updates simultaneous kyun hone chahiye?
Kyunki gradient compute karte waqt assume kiya jaata hai ki saare parameters apni current (old) values par hain. Ek parameter pehle update karke phir us nayi value se agla update karna gradient direction corrupt kar deta hai. Saari nayi values compute karo, phir sab ek saath update karo.
Gradient descent mein learning rate bahut bada ho toh kya hota hai?
Cost decrease ki jagah increase ho sakti hai ya oscillate kar sakti hai. Tum minimum overshoot karte ho, valley ke ek taraf se doosri taraf jump karte ho bina bottom par settle hue.
Batch, stochastic, aur mini-batch gradient descent mein kya farq hai?
Batch GD har update mein saare examples use karta hai (stable, bade ke liye slow). Stochastic GD 1 random example use karta hai (fast, noisy). Mini-batch GD examples use karta hai (balanced). Teeno same cost minimize karte hain lekin alag update strategies se.
Gradient descent ke liye ek common convergence criterion kya hai?
Ruko jab cost mein change ek threshold se chhota ho: (e.g., ), ya jab gradient norm near zero ho, ya maximum iterations ke baad.
Feature scaling gradient descent ko faster converge kyun karne deta hai?
Jab features ki ranges bahut alag hoti hain, cost function elongated (narrow valley) ban jaata hai. Gradient descent slowly zigzag karta hai. Features ko similar ranges par scale karna (e.g., mean 0, std 1) cost surface ko zyada circular banata hai, faster aur direct convergence allow karta hai.
MSE cost function se gradient derive karo.
se shuru karo. Chain rule apply karo: . 2, ke saath cancel ho jaata hai. Kyunki , hume milta hai . Result: .

Gradient descent mein negative gradient ka kya matlab hai? :: Negative gradient ka matlab hai ki parameter badhne par cost decrease hoti hai, isliye hume parameter increase karna chahiye. Kyunki hum gradient subtract karte hain (), hum effectively mein add karte hain, use us direction mein move karte hain jo cost reduce karta hai.

Concept Map

difference

sum cancels out

square errors

penalizes big errors

differentiable everywhere

average over n

add one half factor

generates

define

enables calculus

used by

updates

Predictions vs actual

Residual errors

Need better measure

Squared errors

MSE cost J theta

Smooth surface

Size independent cost

Cleaner gradient

Hypothesis h theta x

Parameters theta

Gradient descent