Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
🤖 Week 7 – Machine Learning Core  ·  दिन 39

दिन 39: Multiple Regression, Ridge और Lasso

⏱ 2.5 hours📶 Intermediate🎯 100% self-study
दिन 39 / 60

✅ आज आप सीखेंगे

  • एक साथ कई features
  • City और furnishing को one-hot encode करना
  • Coefficients “बाकी स्थिर रखकर” पढ़ना
  • Multicollinearity और log-transformed targets
  • Ridge और Lasso: features सिकोड़ना और चुनना

🏢 असली दुनिया में

सिर्फ़ area वाला model हर flat पर ₹7 lakh ग़लत था। Buyers city, metro दूरी, उम्र, furnishing और parking की भी परवाह करते हैं। जो model सबका इस्तेमाल करे – और बताए कि हर एक rupees में कितना कीमती है – वह pricing tool बनता है जिस पर sales teams भरोसा करती हैं।

Step 1: categories को numbers में बदलें

Python
import pandas as pd
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
print(X.columns.tolist())
print(X.head(3))
['area_sqft', 'bedrooms', 'bathrooms', 'age_years', 'metro_km', 'city_Hyderabad', 'city_Jaipur', 'city_Lucknow', 'city_Pune', 'furnishing_Semi-Furnished', 'furnishing_Unfurnished', 'parking_Yes'] area_sqft bedrooms bathrooms age_years metro_km city_Hyderabad city_Jaipur city_Lucknow city_Pune furnishing_Semi-Furnished \ 0 1210 2 2 18 7.0 0 0 0 1 0 1 850 2 2 15 4.6 0 0 0 0 1 2 530 1 1 8 2.1 1 0 0 0 1 furnishing_Unfurnished parking_Yes 0 0 0 1 0 0 2 0 1
🧠 drop_first क्यों?

5 शहरों में से 4 columns रखते हैं; हटाया गया (Bengaluru) reference बनता है। तब हर city coefficient का मतलब है “Bengaluru से अंतर”। सभी 5 रखने से perfect collinearity होती है (dummy-variable trap)।

Step 2: fit और evaluate

Python
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, r2_score
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
y = h["price_lakh"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
area_only = LinearRegression().fit(X_tr[["area_sqft"]], y_tr)
full = LinearRegression().fit(X_tr, y_tr)
for name, m, cols in [("area only", area_only, ["area_sqft"]), ("all features", full, X.columns)]:
    p = m.predict(X_te[cols])
    print(f"{name:13s} MAE = ₹{mean_absolute_error(y_te, p):.2f} lakh   R² = {r2_score(y_te, p):.3f}")
area only MAE = ₹10.94 lakh R² = 0.656 all features MAE = ₹4.63 lakh R² = 0.932

Step 3: हर feature कितना कीमती है?

Python
import pandas as pd
from sklearn.linear_model import LinearRegression
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
m = LinearRegression().fit(X, h["price_lakh"])
coef = pd.Series(m.coef_, index=X.columns).round(3)
print(coef.sort_values().to_string())
city_Lucknow -27.994 city_Jaipur -27.330 city_Hyderabad -9.686 city_Pune -8.075 furnishing_Unfurnished -4.868 furnishing_Semi-Furnished -2.336 metro_km -1.724 bedrooms -0.550 age_years -0.519 area_sqft 0.049 bathrooms 0.090 parking_Yes 2.767
💼 Coefficients पढ़ना

हर number उस feature की +1 unit पर price (₹ lakh) का बदलाव है, बाकी सबको स्थिर रखकर। उदाहरण: metro_km ≈ −1.7 मतलब उसी size, शहर और उम्र के लिए metro से हर extra km कीमत लगभग ₹1.7 lakh घटाता है।

⚠️ Bedrooms का sign अजीब?

Bedrooms और bathrooms, area से बहुत correlated हैं। Area स्थिर रखने पर extra bedroom का मतलब छोटे कमरे – इसलिए coefficient छोटा या negative हो सकता है। यही multicollinearity है: predictions ठीक, अलग coefficients अस्थिर।

Python
import pandas as pd
from statsmodels.stats.outliers_influence import variance_inflation_factor
h = pd.read_csv("house_prices.csv")
num = h[["area_sqft", "bedrooms", "bathrooms", "age_years", "metro_km"]].assign(const=1)
vif = pd.Series([variance_inflation_factor(num.values, i) for i in range(num.shape[1] - 1)], index=num.columns[:-1]).round(2)
print(vif.to_string())
print("VIF > 5 → strongly explained by the other features")
area_sqft 3.05 bedrooms 6.35 bathrooms 4.38 age_years 1.00 metro_km 1.00 VIF > 5 → strongly explained by the other features

बेहतर target: log(price)

कीमतें percentages में बढ़ती हैं (metro station हर flat में % जोड़ता है), और right-skewed हैं। log(price) model करना अक्सर बेहतर fit देता है और coefficients “% बदलाव” बन जाते हैं।

Python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
X["log_area"] = np.log(X["area_sqft"])
y = h["price_lakh"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42)
plain = LinearRegression().fit(X_tr.drop(columns="log_area"), y_tr)
logm = LinearRegression().fit(X_tr.drop(columns="area_sqft"), np.log(y_tr))
p1 = plain.predict(X_te.drop(columns="log_area"))
p2 = np.exp(logm.predict(X_te.drop(columns="area_sqft")))
print(f"price model     MAE = ₹{mean_absolute_error(y_te, p1):.2f} lakh")
print(f"log-price model MAE = ₹{mean_absolute_error(y_te, p2):.2f} lakh")
c = pd.Series(logm.coef_, index=X_tr.drop(columns="area_sqft").columns)
print(f"each km from metro → {(np.exp(c['metro_km']) - 1) * 100:.1f}% price | furnished → {(np.exp(c['furnishing_Unfurnished']) - 1) * -100:.1f}% more than unfurnished")
price model MAE = ₹4.63 lakh log-price model MAE = ₹3.32 lakh each km from metro → -3.4% price | furnished → 8.5% more than unfurnished

Regularisation: Ridge और Lasso

📏
Linear regressionसिर्फ़ errors न्यूनतम। कई features हों तो शोर पर ज़्यादा प्रतिक्रिया।
🪢
Ridge (L2)Errors + α × (coefficients के वर्गों का जोड़)। सभी coefficients धीरे सिकोड़ता है – correlated features में बढ़िया।
✂️
Lasso (L1)Errors + α × (|coefficients| का जोड़)। कमज़ोर को ठीक 0 कर देता है – अपने-आप feature selection।
α penalty की ताक़त तय करता है
Python
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
rng = np.random.default_rng(0)
for i in range(30):                                   # add 30 useless noise columns
    X[f"noise_{i}"] = rng.normal(size=len(X))
X_tr, X_te, y_tr, y_te = train_test_split(X, h["price_lakh"], test_size=0.5, random_state=1)
for name, est in [("Linear", LinearRegression()), ("Ridge α=10", Ridge(alpha=10)), ("Lasso α=0.3", Lasso(alpha=0.3, max_iter=20000))]:
    m = make_pipeline(StandardScaler(), est).fit(X_tr, y_tr)
    coefs = m[-1].coef_
    print(f"{name:12s} test R²={m.score(X_te, y_te):.3f} | non-zero coefs={np.sum(np.abs(coefs) > 1e-6):2d} of {len(coefs)}")
Linear test R²=0.937 | non-zero coefs=42 of 42 Ridge α=10 test R²=0.935 | non-zero coefs=42 of 42 Lasso α=0.3 test R²=0.936 | non-zero coefs=16 of 42
Python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
Xs = StandardScaler().fit_transform(X)
alphas = np.logspace(-2, 1.3, 40)
paths = np.array([Lasso(alpha=a, max_iter=20000).fit(Xs, h["price_lakh"]).coef_ for a in alphas])
plt.figure(figsize=(9, 4.2))
for j, col in enumerate(X.columns):
    plt.plot(alphas, paths[:, j], label=col if j < 9 else None)
plt.xscale("log"); plt.axhline(0, color="black", lw=0.6)
plt.xlabel("alpha (penalty strength)"); plt.ylabel("coefficient (scaled)")
plt.title("Lasso path: weak features drop to zero first; area survives longest")
plt.legend(fontsize=7, ncol=2); plt.show()
Alpha बढ़ने पर शून्य की ओर सिकुड़ते Lasso coefficient paths
α बढ़ने पर Lasso एक-एक करके features हटाता है – क्रम उनका महत्व बताता है।
Python
import pandas as pd
from sklearn.linear_model import RidgeCV, LassoCV
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import make_pipeline
h = pd.read_csv("house_prices.csv")
X = pd.get_dummies(h.drop(columns="price_lakh"), columns=["city", "furnishing", "parking"], drop_first=True, dtype=int)
ridge = make_pipeline(StandardScaler(), RidgeCV(alphas=[0.01, 0.1, 1, 10, 100])).fit(X, h["price_lakh"])
lasso = make_pipeline(StandardScaler(), LassoCV(cv=5, random_state=0, max_iter=20000)).fit(X, h["price_lakh"])
print("best Ridge alpha:", ridge[-1].alpha_, "| best Lasso alpha:", round(lasso[-1].alpha_, 4))
best Ridge alpha: 0.1 | best Lasso alpha: 0.047

🏅 आज के Job Skills

✔ One-hot features के साथ multiple regression✔ Coefficients सही समझना✔ VIF से multicollinearity पकड़ना✔ Log targets, Ridge और Lasso का इस्तेमाल

Practice tasks

🏋️ Practice – ख़ुद करें

Task 1: study_hours, attendance, tuition, internet और parent_education (one-hot) से student average predict करें। कौन से features सबसे ज़रूरी?
Solution देखें
Python
import pandas as pd
from sklearn.linear_model import LinearRegression
st = pd.read_csv("students_performance.csv")
X = pd.get_dummies(st[["study_hours", "attendance", "tuition", "internet", "parent_education"]], drop_first=True, dtype=int)
m = LinearRegression().fit(X, st["average"])
print(pd.Series(m.coef_, index=X.columns).round(2).sort_values()); print("R²", round(m.score(X, st["average"]), 3))
parent_education_School -3.04 attendance 0.44 parent_education_Post-Graduate 0.81 tuition_Yes 1.76 internet_Yes 2.50 study_hours 6.24 dtype: float64 R² 0.814
Task 2: Student model पर LassoCV चलाएँ। Lasso कौन से features रखता है?
Solution देखें
Python
import pandas as pd
from sklearn.linear_model import LassoCV
from sklearn.preprocessing import StandardScaler
st = pd.read_csv("students_performance.csv")
X = pd.get_dummies(st[["study_hours", "attendance", "tuition", "internet", "parent_education", "gender", "school_type"]], drop_first=True, dtype=int)
m = LassoCV(cv=5, random_state=0).fit(StandardScaler().fit_transform(X), st["average"])
print(pd.Series(m.coef_, index=X.columns).round(2))
study_hours 8.01 attendance 4.00 tuition_Yes 0.82 internet_Yes 0.97 parent_education_Post-Graduate 0.28 parent_education_School -1.41 gender_Male 0.05 school_type_Private 0.13 dtype: float64
Task 3: Hyderabad में 1,100 sqft, 2-bed, 2-bath, 5 साल पुराने, metro से 1.5 km, semi-furnished, parking वाले flat की कीमत estimate करें।

Quick quiz

🧠 Quick Quiz – ख़ुद को जाँचें

1. Multiple regression में coefficient मतलब feature का असर…
बाकी सब समान।
2. drop_first=True किससे बचाता है?
Dummies में perfect collinearity।
3. कौन coefficients को ठीक शून्य कर सकता है?
L1 penalty।
4. Ridge/Lasso से पहले features scale क्यों?
वरना units penalty तय करेंगी।
5. High VIF क्या बताता है?
Feature बाकियों से predict हो सकता है।

Interview corner

💼 Interview Corner

Ridge और Lasso में फ़र्क?

दोनों बड़े coefficients पर penalty लगाकर overfitting घटाते हैं। Ridge (L2) सभी coefficients सिकोड़ता है पर शून्य नहीं करता – correlated features में अच्छा। Lasso (L1) कुछ को ठीक शून्य कर feature selection करता है। Elastic Net दोनों का मिश्रण है।

Multicollinearity क्या है और क्यों मायने रखती है?

जब features आपस में बहुत correlated हों। Predictions सही रह सकती हैं, पर coefficients अस्थिर और समझने में मुश्किल हो जाते हैं। Correlation/VIF से पकड़ें; features हटाकर या जोड़कर या Ridge से ठीक करें।

सारांश

  • Categories को one-hot (drop_first) करें और सभी features साथ fit करें।
  • Coefficients = बाकी स्थिर रखकर असर; multicollinearity (VIF) पर ध्यान।
  • log(price) अक्सर बेहतर fit और % असर देता है।
  • Ridge सिकोड़ता, Lasso चुनता है; CV से α tune करें और पहले scale करें।
➡️ आगे

Day 40: logistic regression – numbers से हाँ/नहीं और probabilities predict करने तक।

अक्सर पूछे जाने वाले प्रश्न (FAQ)

क्या prices हमेशा log-transform करें?
जब target right-skewed हो या असर गुणात्मक हो तब आज़माएँ, और original scale पर MAE मिलाएँ। Predictions को exp() से वापस लाना याद रखें।
Regression के लिए statsmodels या scikit-learn?
statsmodels coefficients के p-values और confidence intervals देता है (explanation)। scikit-learn prediction pipelines के लिए बना है। Analysts अक्सर दोनों लेते हैं।
← Data Science (60 Days)
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

अगला topicदिन 40: Logistic Regression: Loan Approval आपकी प्रगति: 39 / 60 (65%) · Lesson 40 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

आपकी राय से हम content और बेहतर बनाते हैं।

अपना review और सुझाव लिखें (वैकल्पिक)

Review approve होने के बाद आपका नाम और शहर इसके साथ public दिख सकते हैं। Email या phone न लिखें।

▶ CodingEasily on YouTube

Video से सीखें – आसान Hindi में

चुनी हुई video: RDBMS भाग 3 – Class XI Commerce IT

▶ Channel subscribe करें