পাঠ ০৯ · ৪৫-এর মধ্যে · মডিউল ২
Home / AI Courses / Machine Learning / Linear Regression

Linear Regression — শূন্য থেকে

Linear regression from scratch
৮ মিনিট পড়া মাঝারি · Intermediate NumPy কোডসহ

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

  • Linear regression — তিন ভিন্ন দৃষ্টিতে: সরলরেখা, parameter ও prediction
  • MSE loss কেন বাছা হয় — square কেন, absolute কেন না
  • Single feature ও multi-feature linear regression — vector form
  • NumPy দিয়ে নিজে বানিয়ে লাইন ফিট করা

১ · সমস্যা — কীভাবে শুরু

ভাবুন আপনি ঢাকার একটি real-estate firm-এ কাজ করছেন। গ্রাহক একটি ফ্ল্যাটের আয়তন বললে — আপনার বলতে হবে আনুমানিক দাম। আপনার কাছে past data: ১,০০০ বিক্রি হওয়া ফ্ল্যাটের (area, price)।

Scatter plot করলে দেখবেন — area বাড়ার সাথে price বাড়ে, প্রায় linear pattern। তাই একটি সরলরেখা টানলে — যেকোনো নতুন area-র জন্য price predict করা যাবে। এটাই Linear RegressionLinear Regressionএকটি supervised ML মডেল — input ও output-এর মধ্যে linear সম্পর্ক ধরে। MSE loss minimize করে best line পাওয়া যায়। ১৭৯৫-এ Gauss ও Legendre আলাদাভাবে আবিষ্কার করেন।।

তিন প্রশ্ন

১) Model: কেমন function ব্যবহার করব? — সরলরেখা $\hat{y} = w x + b$।
২) Loss: কোন line "ভালো" — সেটা মাপব কীভাবে? — MSE।
৩) Optimization: সবচেয়ে ভাল $w, b$ কীভাবে খুঁজব? — closed-form বা GD।

২ · মডেল — সরলরেখা

একক feature-এ লিনিয়ার মডেল:

$$\hat{y} = w \cdot x + b$$

এখানে — $x$ হলো input (যেমন area in square feet), $\hat{y}$ হলো predicted output (price), $w$ হলো weight (slope, রেখার ঢাল), $b$ হলো bias (intercept, $x=0$ যেখানে রেখা $y$-অক্ষ ছোঁয়)।

ভাবুন একটি rickshaw-এর ভাড়া। প্রথম ১ km — ৩০ টাকা base ($b$), তারপর প্রতি km-এ ১৫ টাকা ($w$)। ৫ km গেলে ভাড়া = $15 \times 5 + 30 = 105$ টাকা। এটাই linear model।

৩ · Multi-feature — vector form

বাস্তবে এক feature-এ price predict ভাল হয় না। আরও features লাগে — bedroom সংখ্যা, location, পুরাতন কত বছর। তাই:

$$\hat{y} = w_1 x_1 + w_2 x_2 + \ldots + w_n x_n + b$$

Compact form (ভেক্টর — দেখুন AI Foundations L11):

$$\hat{y} = \mathbf{w}^\top \mathbf{x} + b$$

$\mathbf{x}$ একটি $n$-মাত্রিক feature ভেক্টর, $\mathbf{w}$ একই মাত্রার weight ভেক্টর। প্রতিটি feature-এর নিজস্ব weight। AI-র সব মডেল — ছোট-বড় — এই form-এর সম্প্রসারণ।

৪ · Loss — কোন line ভালো?

৩-৪টি data points-এর মধ্যে অসংখ্য line টানা যায়। কোনটা "best"? — যে line average-এ সবচেয়ে কম ভুল করে। ভুল = actual $y_i$ ও predicted $\hat{y}_i$-এর পার্থক্য। সব data point-এ যোগ করতে হবে।

সবচেয়ে সাধারণ — Mean Squared ErrorMSE — Mean Squared Errorপ্রতিটি error-কে square করে গড় নেওয়া। বড় error-কে অতিরিক্ত শাস্তি দেয়। Linear regression-এর default loss।:

$$L(w, b) = \frac{1}{N} \sum_{i=1}^{N} (y_i - \hat{y}_i)^2 = \frac{1}{N} \sum_{i=1}^{N} (y_i - w x_i - b)^2$$

কেন square? তিনটি কারণ:

  • Negative ও positive error cancel হয় না (sign বাদ পড়ে)।
  • বড় error বেশি penalty পায় — মডেল গুরুতর ভুল এড়ায়।
  • Square — differentiable, smooth — gradient descent সম্ভব।
বিকল্প — Mean Absolute Error (MAE, $|y - \hat{y}|$)। Outlier-resistant কিন্তু $0$-তে non-differentiable, optimization কঠিন। তাই MSE বেশি ব্যবহৃত।

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

Scatter plot-এ data points ছড়ানো। Line ফিট করার অর্থ — এমন রেখা বাছা যেখানে point থেকে line-এর "vertical distance"-গুলোর squared sum সর্বনিম্ন। প্রতিটি point থেকে line পর্যন্ত vertical line — এর দৈর্ঘ্যই error।

Linear Regression — তিন দৃষ্টিতে ŷ = w·x + b 📊 জ্যামিতিক — line fit x y data + best line 📐 গাণিতিক রূপ ŷ = w·x + b w: slope b: intercept Loss (MSE): (1/N)Σ(y − ŷ)² Goal: min loss → best w, b 🤖 AI-তে ব্যবহার Price prediction (housing) Demand forecast (sales) Neural network layer (linear part) Baseline model (always start here) সব ML-এর প্রথম পাঠ
Linear regression — line ফিট করা = MSE সর্বনিম্ন করা = $w, b$ খুঁজে বের করা।

৬ · NumPy দিয়ে — হাতে-কলমে

চলুন একটি toy data-তে আমরা নিজে $w, b$ guess করি, MSE মাপি।

Python · NumPy
import numpy as np

# Toy data — area (sqft) ও price (lakh)
x = np.array([500, 800, 1200, 1500, 2000, 2500])
y = np.array([25, 40, 55, 70, 95, 120])

# একটি গেস
w, b = 0.05, 0.0

y_hat = w * x + b
errors = y - y_hat
mse = np.mean(errors ** 2)

print("y      =", y)
print("y_hat  =", y_hat)
print("errors =", errors)
print(f"MSE    = {mse:.2f}")

    
$w = 0.05$ মানে — প্রতি sqft-এ ০.০৫ লাখ টাকা। ১০০০ sqft → ৫০ লাখ। MSE মান কম হলে fit ভালো। পরের পাঠে (L10) আমরা best $w, b$-এর exact formula শিখব।

৭ · Manual line ফিট — gridsearch

সবচেয়ে naive পদ্ধতি — $w$-র অনেক values try করে সবচেয়ে কম MSE বাছা।

Python · NumPy
import numpy as np

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

best_w, best_b, best_mse = None, None, float('inf')

# Grid search — w 0.01 থেকে 0.1, b 0 থেকে 30
for w in np.arange(0.01, 0.10, 0.001):
    for b in np.arange(-5, 30, 0.5):
        y_hat = w * x + b
        mse = np.mean((y - y_hat) ** 2)
        if mse < best_mse:
            best_mse, best_w, best_b = mse, w, b

print(f"Best w = {best_w:.4f}")
print(f"Best b = {best_b:.2f}")
print(f"Best MSE = {best_mse:.4f}")

    
Grid search কাজ করে — কিন্তু slow। ২ parameters-এর জন্য ঠিক, ১০০০-D-তে অসম্ভব। তাই L10-এ closed-form solution, L11-এ gradient descent।

৮ · scikit-learn — এক লাইনে

Python · scikit-learn
import numpy as np
from sklearn.linear_model import LinearRegression

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

model = LinearRegression()
model.fit(x, y)

print(f"w (slope) = {model.coef_[0]:.4f}")
print(f"b (intercept) = {model.intercept_:.4f}")
print(f"R² score = {model.score(x, y):.4f}")

# নতুন area-র জন্য predict
print(f"1800 sqft → {model.predict([[1800]])[0]:.2f} লাখ")

    
sklearn ভেতরে closed-form (Normal Equations) ব্যবহার করে — মুহূর্তেই optimal $w, b$ বের করে। কিন্তু ভেতরে কী ঘটছে — সেটাই L10-এ।

৯ · Linear regression-এর assumptions

মডেল ভাল কাজ করতে চাইলে কিছু শর্ত মানে চলে:

  • Linearity: $x$ ও $y$-এর সম্পর্ক সত্যিই linear। Curve হলে — polynomial features বা non-linear মডেল লাগে।
  • Independence: Errors পরস্পর independent (time series-এ violation হয়)।
  • Homoscedasticity: Error variance constant — সব $x$ range-এ সমান spread।
  • Normality: Errors approximately normal-distributed (MLE interpretation)।
  • No multicollinearity: Features পরস্পর highly correlated না।

১০ · কোথায় ব্যবহার, কোথায় না

  • ভাল ক্ষেত্র: Trend forecasting, baseline model, interpretable price/sales prediction।
  • খারাপ ক্ষেত্র: Image classification, NLP — relationship strongly non-linear।
  • Best practice: Project শুরু করুন linear regression দিয়ে — baseline। তারপর complex মডেল যদি linear performance ছাড়িয়ে যায়, তবেই use।
"Simple is better than complex" — সবচেয়ে underrated ML wisdom। ৭০% problem-এ logistic/linear regression-ই production-grade। XGBoost/Neural networks-এর আগে এটা মাস্টার করুন।

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

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

প্র ০১ MSE বনাম MAE — কোনটি কখন ব্যবহার করবেন? Outlier-rich data-তে কোনটি বেশি sensible? কেন সবাই MSE-ই default করে?

Loss function-এর choice — ML-এর সবচেয়ে underappreciated decision। মডেল identical, loss ভিন্ন — result drastically ভিন্ন।

MSE-র সুবিধা:

  • Smooth, everywhere differentiable — gradient descent সহজ।
  • Closed-form solution আছে (Normal Equations) — analytic global optimum।
  • Maximum Likelihood interpretation — Gaussian noise model-এ MSE-ই MLE।
  • Big errors disproportionately penalized — outlier-এ বেশি focus।
  • Convex — local minimum = global minimum।

MSE-র অসুবিধা:

  • Outlier-এ over-sensitive — একটি extreme point পুরো model টানে।
  • Unit squared — interpretation কঠিন (RMSE = $\sqrt{\text{MSE}}$ হয়)।
  • Asymmetric error যদি cost ভিন্ন — MSE মাপতে পারে না।

MAE-র সুবিধা:

  • Outlier-robust — error-এ linear penalty।
  • Same unit — interpretable ("গড় ভুল ৫ টাকা")।
  • Median-এর গাণিতিক analog (MSE-এর mean)।

MAE-র অসুবিধা:

  • $0$-তে non-differentiable — gradient descent tricky (subgradient লাগে)।
  • Closed-form নেই — iterative optimization।
  • Multiple optima সম্ভব।

কখন কোনটি:

  • Clean data, normal-distributed errors: MSE।
  • Outlier-prone (real-world data): MAE বা Huber loss।
  • Asymmetric cost: Custom — যেমন quantile regression।

Huber loss — middle ground:

$$L_{\delta}(e) = \begin{cases} \frac{1}{2}e^2 & |e| \leq \delta \\ \delta(|e| - \frac{1}{2}\delta) & |e| > \delta \end{cases}$$

  • Small error — quadratic (MSE-এর মতো)।
  • Large error — linear (MAE-এর মতো)।
  • Outlier-robust + smooth।
  • $\delta$ — hyperparameter।

মূল উপলব্ধি: Default MSE — কারণ history, gradient-friendliness, statistical foundation। কিন্তু production data outlier থাকলে — Huber বা MAE বিবেচনা করুন। Loss choice = problem statement।

প্র ০২ Linear regression কে "machine learning" বলা যায় কি? এটা তো শুধু গণিত — fit একটি line। AI/ML-এর বাকি সব এর সাথে কীভাবে সম্পর্কিত?

এই প্রশ্ন philosophically gripping — এবং technical-ভাবেও তথ্যবহুল। Linear regression-এর role overestimate করা যায় না।

হ্যাঁ — এটি ML:

  • Data-থেকে শেখা — parameter estimation from examples।
  • Generalization — unseen data-তে predict।
  • Loss-based optimization — সব ML-এর core।
  • Train/test paradigm — ML-এর foundation।

Linear regression — DL-এর ভিত্তি:

  • Single neuron: $y = \sigma(w^\top x + b)$ — linear regression + activation।
  • Layer: Multiple linear regression parallel।
  • Deep network: Linear regression-এর nested composition।
  • "Universal approximation theorem" — enough linear units = any function।

Concept যা reuse হয়:

  • Weight, bias: Every model has these।
  • Loss function: MSE → cross-entropy → contrastive — পরিবর্তন কিন্তু concept same।
  • Gradient descent: Linear regression-এ teach, Transformer-এ same algorithm।
  • Overfitting: Polynomial regression-এ first encounter।
  • Regularization: Ridge/Lasso (L15) — DL-এর weight decay।

Linear regression-এর extensions:

  • Polynomial regression: $y = w_0 + w_1 x + w_2 x^2 + \ldots$ — basis function।
  • Logistic regression: Linear + sigmoid — classification।
  • Generalized Linear Models: Poisson, Gamma — link function।
  • Ridge/Lasso: Regularized variants।
  • Bayesian linear regression: Uncertainty quantification।

Production reality:

  • Many "AI" applications use linear regression internally।
  • Recommendation system — linear factor models common।
  • Banking risk score — logistic regression dominant।
  • Real estate pricing — linear regression baseline।

Pedagogical value:

  • সব ML concept first introduced here।
  • Math tractable — closed-form solution exists।
  • Visualization possible (1-2 features)।
  • Debug-friendly — coefficients interpretable।

Research perspective:

  • "Lazy NN" theory — wide neural networks ≈ linear regression-এর mode।
  • Neural Tangent Kernel — DL-এর linearization।
  • "Implicit regularization" — gradient descent in over-parameterized linear models।

মূল উপলব্ধি: Linear regression "শুধু গণিত" না — এটি ML-এর atomic unit। এটি না বুঝে advanced topic study করা possible কিন্তু superficial। প্রতিটি Transformer-এর ভেতরে — অসংখ্য linear regression।

প্র ০৩ আপনি Daraz-এর জন্য একটি product price predictor বানাচ্ছেন। Linear regression কাজ করবে? কী assumptions ভঙ্গ হবে? কী features বাছবেন?

Real-world ML problem — assumption-checking-এর master class।

Problem definition:

  • Input: product description, category, brand, specs, seller।
  • Output: optimal listing price (BDT)।
  • Goal: dynamically suggest competitive price।

Linear regression — first attempt:

  • Baseline: features × weights → price।
  • Quick to deploy, interpretable।
  • Stakeholder-এর কাছে justifiable: "weight 0.05 on screen size means price increases ৫% per inch"।

Assumption violations:

(১) Non-linearity:

  • Brand premium — non-linear ("Apple" baseline ৩x competitor)।
  • Capacity → price — diminishing returns (256GB vs 512GB pricing)।
  • Solution: log-transform, polynomial features।

(২) Heteroscedasticity:

  • Cheap items — small price variance।
  • Premium items — huge variance (collector items, rare)।
  • Solution: log(price) target, weighted regression।

(৩) Multicollinearity:

  • "RAM" ও "Storage" highly correlated।
  • "Brand premium" ও "Build quality" overlap।
  • Solution: PCA, feature selection, Ridge regression।

(৪) Outliers:

  • Mispriced listings (BDT 100 typo for laptop)।
  • Counterfeit/refurbished items।
  • Solution: Huber loss, RANSAC, manual filtering।

Feature engineering:

  • Numerical: RAM, storage, screen size, weight (log transform যেখানে skewed)।
  • Categorical: Brand (target encoding), category (one-hot)।
  • Text: Title length, key keywords (TF-IDF)।
  • Image: Pre-trained CNN features।
  • Seller: Rating, history, location।
  • Time: Listing age, season (Eid premium)।

Better alternatives:

  • Random Forest/XGBoost: Non-linearity capture, interpretable।
  • Neural network: Image + text + tabular fusion।
  • Hierarchical models: Per-category modeling।

Production pipeline:

  • Linear regression — initial baseline (Week 1)।
  • XGBoost — production model (Week 4)।
  • Deep learning — research project (Quarter 2)।
  • A/B test all।

Business considerations:

  • Price ceiling — manipulation prevent।
  • Seller bias — সব sellers fair treatment।
  • Explainability — seller-কে কেন এই price বলছি।
  • Drift — fashion trend, inflation।

মূল উপলব্ধি: Real-world-এ linear regression rarely sufficient। কিন্তু rejection-এর আগে — try, understand failure modes, pick right alternative।

প্র ০৪ "Linear regression-এ closed-form solution আছে — তাহলে gradient descent কেন শিখব?" — এই argument কতটা সঠিক? কখন GD অপরিহার্য?

এই tension — ML-এর foundational tradeoff।

Closed-form solution-এর সুবিধা:

  • Exact answer — no approximation।
  • One-shot computation।
  • Deterministic — randomness নেই।
  • Beautiful math।

Closed-form-এর সীমাবদ্ধতা:

  • Computational: $(X^\top X)^{-1}$ — $O(n^3)$ feature count-এ। ১০,০০০ features = অসম্ভব।
  • Memory: $(X^\top X)$ — $n \times n$ matrix। ১০৫ features = ১০¹⁰ entries।
  • Numerical: Singular matrix — invert করা যায় না। Multicollinearity-এ unstable।
  • Existence: Most ML loss-এর closed-form নেই (cross-entropy, hinge)।
  • Online learning: Streaming data-তে whole $X^\top X$ recompute possible না।

Gradient descent-এর শক্তি:

  • Any differentiable loss-এ work।
  • Memory-efficient — sample-by-sample।
  • Online learning compatible।
  • GPU-friendly — matrix operations parallelizable।
  • Stochastic version (SGD) — large-scale data-এ practical।

কখন GD অপরিহার্য:

  • Logistic regression: Closed-form নেই।
  • Neural networks: Non-convex, no analytical solution।
  • SVM (kernel): Dual formulation — different solver।
  • Tree boosting: Functional gradient descent।
  • Big data: Memory constraints।

Linear regression-এ GD যখন better:

  • Features > ১০,০০০।
  • Online/streaming data।
  • Sparse matrix (text, recommendations)।
  • Distributed computing।

Pedagogical reasons:

  • GD — DL-এর foundation।
  • Loss landscape intuition।
  • Hyperparameter (LR, batch size) feel।
  • Convergence diagnosis।

Hybrid approaches:

  • QR decomposition: Numerically stable closed-form alternative।
  • Conjugate gradient: Iterative, exact in finite steps।
  • L-BFGS: Quasi-Newton, fast for medium problems।
  • SGD with momentum: Modern default।

Production reality:

  • scikit-learn — small data closed-form, large data SGD।
  • TensorFlow/PyTorch — exclusively gradient-based।
  • Spark MLlib — distributed gradient descent।

মূল উপলব্ধি: Closed-form elegant কিন্তু narrow। GD universal — সব ML-এর primary tool। Linear regression — দু'টোই demonstrate করার গণিতিক ground।

অনুশীলন

  1. হিসাব করুন: $w = 2$, $b = 5$। Data: $x = [1, 2, 3]$, $y = [8, 10, 12]$।
    • Predicted $\hat{y}$ কত?
    • প্রতি sample-এর error কত?
    • MSE কত?
    • $\hat{y} = 2x + 5 = [7, 9, 11]$।
    • Errors: $[8-7, 10-9, 12-11] = [1, 1, 1]$।
    • MSE $= (1^2 + 1^2 + 1^2) / 3 = 1.0$।
  2. NumPy: উপরের toy area-price data-তে $w = 0.04, b = 5$ ও $w = 0.06, b = -2$ — কোন combination ভাল MSE দেয়?
    import numpy as np
    x = np.array([500, 800, 1200, 1500, 2000, 2500])
    y = np.array([25, 40, 55, 70, 95, 120])
    
    for w, b in [(0.04, 5), (0.06, -2)]:
        mse = np.mean((y - (w*x + b)) ** 2)
        print(f"w={w}, b={b}, MSE={mse:.2f}")

    সাধারণত $w \approx 0.05, b \approx 0$ optimal — উভয়ই সরে গেলে MSE বাড়ে।

  3. চিন্তা: CGPA → starting salary predict করতে চান (Bangladeshi students, fresh grads)। কোন features যোগ করবেন? Linear regression কতটা কাজ করবে — কোথায় ভেঙে পড়বে?

    Features: CGPA, university tier, major (CSE vs others), internship count, English score, location, gender।

    Linear regression — baseline OK। সমস্যা: tier-effect non-linear (top-3 vs rest huge gap), industry-specific premium, gender bias। Solution: tree-based model বা mixed-effects model।

আরও পড়ুন

কোড রানার কাজ না করলে? Google Colab ব্যবহার করুন।
পূর্ববর্তী পাঠ
পাঠ ০৮ · Feature engineering