दिन 36: Machine Learning क्या है?
✅ आज आप सीखेंगे
- Rules vs examples से सीखना
- Supervised, unsupervised, reinforcement
- Regression vs classification
- Features, labels, training और testing
- Overfitting और 7-step ML workflow
🏢 असली दुनिया में
एक bank पहले rule book से loans approve करता था: “income ₹40,000 से ऊपर और credit score 700 से ऊपर”। अच्छे customers छूट जाते और risky approve हो जाते। 1,200 पुरानी applications और उनके नतीजों से machine-learning model pattern ख़ुद सीखता है – और नए data के साथ बेहतर होता रहता है।
Rules vs learning
Traditional programming
- Rules आप लिखते हैं
- Data + rules → जवाब
- दुनिया बदले तो टूटता है
- Example: if score > 700 then approve
Machine learning
- Rules computer ढूँढता है
- Data + जवाब → rules (model)
- Data बदले तो फिर train
- Example: model 1,200 पुराने loans से सीखता है
import pandas as pd
loans = pd.read_csv("loan_applications.csv")
print(loans.head())
rule = (loans["monthly_income"] > 40000) & (loans["credit_score"] > 700)
print(f"Old rule accuracy: {(rule.astype(int) == loans['approved']).mean():.1%}")
print(f"Approval rate in history: {loans['approved'].mean():.1%}")import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
loans = pd.read_csv("loan_applications.csv")
X = loans[["monthly_income", "credit_score", "loan_amount", "years_employed"]]
y = loans["approved"]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
model = DecisionTreeClassifier(max_depth=4, random_state=42).fit(X_train, y_train)
print(f"ML model accuracy on unseen applications: {model.score(X_test, y_test):.1%}")scikit-learn की पाँच lines ने उन applications पर hand-written rule को हरा दिया जो model ने कभी नहीं देखीं। कल आप हर line ठीक से समझेंगे।
Machine learning के प्रकार
| समस्या | प्रकार | Output | Course day |
|---|---|---|---|
| House price predict | Supervised – regression | number (₹ lakh) | 38–39 |
| Loan approve करें? | Supervised – classification | class (हाँ/नहीं) | 40–43 |
| Customer churn करेगा? | Supervised – classification | probability | 56–60 |
| Mall customers के groups | Unsupervised – clustering | segment id | 46 |
| कई columns compress करना | Unsupervised – dimensionality reduction | कम features | 47 |
| Review positive/negative | Supervised – NLP classification | sentiment | 48 |
| अगले महीने का AQI | Time-series forecasting | भविष्य की values | 49 |
ज़रूरी शब्द
import pandas as pd
h = pd.read_csv("house_prices.csv")
X = h.drop(columns="price_lakh") # features (inputs)
y = h["price_lakh"] # label / target (what we predict)
print("Features:", list(X.columns))
print("Target:", y.name, "| one example →", dict(X.iloc[0]), "→", y.iloc[0], "lakh")| शब्द | मतलब |
|---|---|
| Feature (X) | Input column: area, bedrooms, city |
| Label / target (y) | जो जवाब predict करना है: price |
| Model | सीखा हुआ function f(X) ≈ y |
| Training | जाने-पहचाने examples पर model fit करना |
| Test set | Model की ईमानदार जाँच के लिए अलग रखे examples |
| Prediction | नए X के लिए model का output |
| Overfitting | Training data रटना, नए data पर fail |
Overfitting – रटना vs सीखना
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
loans = pd.read_csv("loan_applications.csv")
X = loans[["monthly_income", "credit_score", "loan_amount", "years_employed"]]; y = loans["approved"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
for depth in [1, 2, 4, 8, 16, None]:
m = DecisionTreeClassifier(max_depth=depth, random_state=42).fit(X_tr, y_tr)
print(f"depth={str(depth):4s} train={m.score(X_tr, y_tr):.3f} test={m.score(X_te, y_te):.3f}")import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
loans = pd.read_csv("loan_applications.csv")
X = loans[["monthly_income", "credit_score", "loan_amount", "years_employed"]]; y = loans["approved"]
X_tr, X_te, y_tr, y_te = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
d = range(1, 16); tr, te = [], []
for k in d:
m = DecisionTreeClassifier(max_depth=k, random_state=42).fit(X_tr, y_tr)
tr.append(m.score(X_tr, y_tr)); te.append(m.score(X_te, y_te))
plt.figure(figsize=(8.5, 3.8))
plt.plot(d, tr, marker="o", label="training accuracy", color="#94a3b8")
plt.plot(d, te, marker="o", label="test accuracy", color="#4f46e5")
best = d[te.index(max(te))]; plt.axvline(best, color="#16a34a", ls="--", label=f"sweet spot (depth {best})")
plt.xlabel("model complexity (tree depth)"); plt.ylabel("accuracy"); plt.legend()
plt.title("Too simple = underfit, too complex = overfit"); plt.show()
जो student पिछले साल का paper रट ले, वह उस पर 100% लाता है पर नए paper में fail। Test set ही “नया paper” है – training में model को इसे कभी न दिखाएँ।
ML workflow
- 1Business समस्या और metric तय करें
- 2Data इकट्ठा और साफ़ करें
- 3EDA और feature engineering
- 4Train / test split
- 5Baseline, फिर बेहतर models train करें
- 6Test set पर evaluate
- 7Deploy, monitor, retrain
अगर simple rule या SQL report समस्या हल करे तो वही लें। ML के लिए labels वाला काफ़ी अच्छा पुराना data, साफ़ metric और उसे संभालने वाला चाहिए।
🏅 आज के Job Skills
Practice tasks
🏋️ Practice – ख़ुद करें
credit_score और monthly_income से train करें। कितनी accuracy कम हुई?Solution देखें
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
l = pd.read_csv("loan_applications.csv")
X_tr, X_te, y_tr, y_te = train_test_split(l[["credit_score", "monthly_income"]], l["approved"], test_size=0.25, random_state=42, stratify=l["approved"])
print(round(DecisionTreeClassifier(max_depth=4, random_state=42).fit(X_tr, y_tr).score(X_te, y_te), 3))Quick quiz
🧠 Quick Quiz – ख़ुद को जाँचें
Interview corner
💼 Interview Corner
Supervised और unsupervised learning में क्या फ़र्क है?
Supervised learning labelled examples पर train होकर जाना-पहचाना target predict करती है (price, churn)। Unsupervised learning बिना labels के data में ढाँचा ढूँढती है (clusters, components, anomalies)।
Overfitting क्या है और कैसे रोकें?
Model training data का शोर सीख लेता है और नए data पर fail होता है। Held-out test set, cross-validation, सरल models या regularisation, ज़्यादा data, और early stopping से रोकें।
सारांश
- ML rules हाथ से लिखने की जगह examples से सीखता है।
- Supervised (regression, classification), unsupervised, reinforcement।
- X = features, y = target; हमेशा अनदेखे test data पर evaluate।
- Overfitting = रटना; सबसे अच्छे test score का लक्ष्य।
Day 37: scikit-learn step by step – fit, predict, score, और सही baseline।
