Look for the interactive boxes: Rule Maker vs Learner (Section 01), Which Type Is It? (02), Train a Classifier (03), Watch K-Means (04), Overfitting Lab (06), Many Training Sets (07) and The Accuracy Trap (08). Move the sliders and press the buttons — every number is calculated live in your browser.
What Is Machine Learning?
Machine Learning (ML) is a part of Artificial Intelligence. In ML, a computer learns rules from examples instead of being given the rules by a programmer.
Think of a recipe. In traditional programming, you give the computer the ingredients (data) and the recipe (rules), and it cooks the dish (answers). In machine learning, you give it the ingredients and many finished dishes. It works out the recipe by itself. That learned recipe is called a model.
Machine Learning is a way for computers to find patterns in past data and use those patterns to make predictions on new data — without a person writing a rule for every case.
Traditional Programming vs Machine Learning
| Input: data + rules (code) |
| Output: answers |
| Rules are written by people |
| Breaks when a case has no rule |
| Must be rewritten when the world changes |
| Example: "if the email contains 'lottery', mark it spam" |
| Input: data + answers (labels) |
| Output: rules (the model) |
| Rules are found by the computer |
| Usually improves with more good data |
| Can handle new cases that look like the old ones |
| Example: a spam filter trained on labelled emails |
Try It — Rule Maker vs Learner
Each dot is an email, placed by how many suspicious words it has. Red emails are spam, green are not. First, set the rule by hand. Then let the machine find the rule from the labelled examples.
इंटरैक्टिव बॉक्स देखें: नियम बनाने वाला बनाम सीखने वाला (सेक्शन 01), यह कौन-सा प्रकार है? (02), classifier train करें (03), K-Means देखें (04), Overfitting लैब (06), कई training set (07) और Accuracy का जाल (08)। स्लाइडर खिसकाएँ और बटन दबाएँ — हर संख्या आपके ब्राउज़र में तुरंत गणना होती है।
Machine Learning क्या है?
Machine Learning (ML) Artificial Intelligence (AI) का एक हिस्सा है। ML में कंप्यूटर को प्रोग्रामर नियम नहीं देता — कंप्यूटर उदाहरणों से खुद नियम सीखता है।
एक रेसिपी के बारे में सोचिए। पारंपरिक प्रोग्रामिंग में आप कंप्यूटर को सामग्री (data) और रेसिपी (नियम) देते हैं, और वह पकवान (उत्तर) बनाता है। Machine Learning में आप उसे सामग्री और कई तैयार पकवान देते हैं। रेसिपी वह खुद निकालता है। इस सीखी हुई रेसिपी को model कहते हैं।
Machine Learning कंप्यूटर के लिए पुराने data में पैटर्न खोजने और उन पैटर्न से नए data पर अनुमान लगाने का तरीका है — बिना इसके कि कोई इंसान हर स्थिति के लिए नियम लिखे।
पारंपरिक प्रोग्रामिंग बनाम Machine Learning
| input: data + नियम (कोड) |
| Output: उत्तर |
| नियम इंसान लिखते हैं |
| जिस स्थिति का नियम न हो, वहाँ टूट जाता है |
| दुनिया बदलने पर दोबारा लिखना पड़ता है |
| उदाहरण: "अगर ईमेल में 'लॉटरी' लिखा है, तो उसे स्पैम मानो" |
| input: data + उत्तर (label) |
| Output: नियम (model) |
| नियम कंप्यूटर खुद खोजता है |
| अच्छा data बढ़ने पर आमतौर पर बेहतर होता है |
| पुराने जैसे दिखने वाले नए मामलों को सँभाल सकता है |
| उदाहरण: label वाले ईमेल से train किया गया स्पैम फ़िल्टर |
आज़माएँ — नियम बनाने वाला बनाम सीखने वाला
हर बिंदु एक ईमेल है, जिसे उसमें मौजूद संदिग्ध शब्दों की संख्या के हिसाब से रखा गया है। लाल ईमेल स्पैम हैं, हरे नहीं। पहले नियम खुद हाथ से तय करें। फिर मशीन को label वाले उदाहरणों से नियम खोजने दें।
请留意这些互动框:人写规则 vs Machine Learning(第 01 节)、这是哪种学习?(02)、训练一个 classifier(03)、观察 K-Means(04)、Overfitting 实验室(06)、许多 training set(07)和 Accuracy 陷阱(08)。拖动滑块、点击按钮——所有数字都在你的浏览器中实时计算。
什么是 Machine Learning?
Machine Learning(ML)是 Artificial Intelligence(AI)的一部分。在 Machine Learning 中,规则不是由程序员写给计算机的,而是计算机从例子中自己学会规则。
想一想做菜的菜谱。在传统编程中,你给计算机食材(数据)和菜谱(规则),它做出菜(答案)。在 Machine Learning 中,你给它食材和许多做好的菜,它自己推算出菜谱。这个学到的菜谱就叫做模型。
Machine Learning 是让计算机在过去的数据中找出规律,并用这些规律对新数据做出预测的方法——不需要人为每一种情况都写规则。
传统编程与 Machine Learning 的对比
| 输入:数据 + 规则(代码) |
| 输出:答案 |
| 规则由人编写 |
| 遇到没有规则的情况就会出错 |
| 世界一变就得重写 |
| 例子:"如果邮件里有'彩票',就标为垃圾邮件" |
| 输入:数据 + 答案(label) |
| 输出:规则(模型) |
| 规则由计算机自己找出 |
| 好数据越多,通常效果越好 |
| 能处理与旧例子相似的新情况 |
| 例子:用带 label 的邮件训练出的垃圾邮件过滤器 |
动手试试——制定规则 vs 学习规则
每个点代表一封邮件,按其中可疑词的数量摆放。红色是垃圾邮件,绿色不是。先亲手设定规则,然后让机器从带 label 的例子中自己找出规则。
Three Types of Machine Learning
ML methods are grouped by what kind of feedback they learn from: correct answers, no answers at all, or rewards and penalties. Knowing the type of your problem tells you which tools to use.
Most ML used in business today is supervised learning — it is the most mature and the easiest to measure.
Try It — Which Type Is It?
Read each situation and choose the type of learning. You get a short explanation after every answer.
Machine Learning के तीन प्रकार
ML के तरीकों को इस आधार पर बाँटा जाता है कि वे किस तरह की प्रतिक्रिया (feedback) से सीखते हैं: सही उत्तरों से, बिना किसी उत्तर के, या reward और penalty से। आपकी समस्या किस प्रकार की है, यह जानने से पता चलता है कि कौन-से टूल इस्तेमाल करने हैं।
आज व्यापार में इस्तेमाल होने वाला ज़्यादातर ML Supervised Learning है — यह सबसे परिपक्व है और इसे मापना सबसे आसान है।
आज़माएँ — यह कौन-सा प्रकार है?
हर स्थिति पढ़ें और Learning का प्रकार चुनें। हर उत्तर के बाद आपको एक छोटी व्याख्या मिलेगी।
Machine Learning 的三种类型
Machine Learning 方法按照它从哪种反馈中学习来 classification:正确答案、完全没有答案,或者 reward 与 penalty。知道你的问题属于哪一类,就知道该用哪些工具。
如今企业中使用的 Machine Learning 大多是 Supervised Learning——它最成熟,也最容易衡量效果。
动手试试——这属于哪一类?
阅读每个场景,选择学习类型。每次回答后都会有简短的解释。
Supervised Learning — Learning from Labelled Data
Supervised learning is the most widely used type of ML. You need examples where the right answer is already known: emails marked spam or not, houses with their sale prices, X-rays checked by doctors. There are two main tasks: classification (predict a category) and regression (predict a number).
Here is a complete example you can run. It makes 20,000 labelled card transactions (about 5% fraud), trains a Random Forest, and tests it on data it did not see during training.
Supervised Learning — label वाले data से सीखना
Supervised Learning ML का सबसे ज़्यादा इस्तेमाल होने वाला प्रकार है। इसके लिए ऐसे उदाहरण चाहिए जिनका सही उत्तर पहले से पता हो: स्पैम या सही चिह्नित ईमेल, बिक्री कीमत वाले घर, डॉक्टरों द्वारा जाँचे गए एक्स-रे। इसके दो मुख्य काम हैं: classification (श्रेणी का अनुमान) और regression (संख्या का अनुमान)।
यह एक पूरा उदाहरण है जिसे आप चला सकते हैं। यह 20,000 label वाले कार्ड लेन-देन बनाता है (लगभग 5% धोखाधड़ी), एक Random Forest train करता है, और उसे ऐसे data पर जाँचता है जो training में नहीं दिखा था।
Supervised Learning——从带 label 的数据中学习
Supervised Learning 是使用最广泛的 Machine Learning 类型。你需要一些已经知道正确答案的例子:标好"垃圾/正常"的邮件、带成交价的房子、医生检查过的 X 光片。它有两大任务:classification(预测类别)和 regression(预测数值)。
下面是一个可以直接运行的完整例子。它生成 20,000 笔带 label 的信用卡交易(约 5% 为欺诈),训练一个 Random Forest,并在训练时没见过的数据上测试。
from sklearn.datasets import make_classification
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
# ── Labelled data: 20,000 card transactions, about 5% fraud ──
X, y = make_classification(n_samples=20_000, n_features=12, n_informative=6,
weights=[0.95, 0.05], class_sep=1.2, random_state=42)
# ── Split into train and test ──────────────────────────────
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.20, random_state=42, stratify=y
)
# ── Train the supervised model ─────────────────────────────
model = RandomForestClassifier(n_estimators=200, random_state=42)
model.fit(X_train, y_train)
# ── Evaluate on held-out test data ────────────────────────
y_pred = model.predict(X_test)
print(classification_report(y_test, y_pred, target_names=['legit', 'fraud']))
Accuracy is 98%, which sounds great. But the recall for fraud is only 0.66 — one fraud in three gets through. When one class is rare, accuracy alone hides the problem. Section 08 shows why.
Try It — Train a Classifier
This is one of the simplest supervised models: k-nearest neighbours. The training data are students with their study and sleep hours, labelled ● pass or ■ fail. The coloured background shows what the model would predict for any new student.
Accuracy (accuracy) 98% है, जो बढ़िया लगती है। लेकिन धोखाधड़ी के लिए Recall सिर्फ़ 0.66 है — हर तीन में से एक धोखाधड़ी निकल जाती है। जब एक श्रेणी दुर्लभ हो, तो अकेली Accuracy समस्या छिपा देती है। सेक्शन 08 इसका कारण दिखाता है।
आज़माएँ — एक classifier train करें
यह सबसे सरल Supervised models में से एक है: k-Nearest Neighbours (kNN)। training data में छात्र हैं, उनकी पढ़ाई और नींद के घंटों के साथ, और label ● पास या ■ फ़ेल। रंगीन पृष्ठभूमि बताती है कि model किसी भी नए छात्र के लिए क्या अनुमान लगाएगा।
Accuracy 是 98%,听起来很好。但欺诈类的 Recall 只有 0.66——每三笔欺诈就有一笔漏网。当某一类很少见时,只看 Accuracy 会掩盖问题。第 08 节会解释原因。
动手试试——训练一个 classifier
这是最简单的 Supervised 模型之一:k-Nearest Neighbours(kNN)。training data 是一些学生的学习时长和睡眠时长,label 为 ● 通过 或 ■ 不通过。彩色背景显示模型会对任何一个新学生做出什么预测。
Unsupervised Learning — Finding Hidden Patterns
Very often you have plenty of data but no labels. Nobody has tagged each customer with a "type", or marked each transaction as "normal". Unsupervised learning finds structure in the data without being told what to look for. The most common task is clustering — putting similar items into groups.
Here is K-Means on 400 customers described by two features. Notice that the code never uses any labels.
Unsupervised Learning — छिपे पैटर्न खोजना
अक्सर आपके पास बहुत data होता है पर कोई label नहीं। किसी ने हर ग्राहक का "प्रकार" नहीं लिखा, न ही हर लेन-देन को "सामान्य" चिह्नित किया। Unsupervised Learning बिना बताए data में ढाँचा खोजती है। सबसे आम काम है clustering — मिलती-जुलती चीज़ों को समूहों में रखना।
यहाँ दो feature वाले 400 ग्राहकों पर K-Means है। ध्यान दें कि कोड कहीं भी label का उपयोग नहीं करता।
Unsupervised Learning——发现隐藏的规律
很多时候你有大量数据,却没有 label。没人给每位顾客标上"类型",也没人把每笔交易标为"正常"。Unsupervised Learning 在没有提示的情况下发现数据中的结构。最常见的任务是 clustering——把相似的东西分到同一组。
下面用两个 feature 描述 400 位顾客,并运行 K-Means。注意代码中完全没有用到 label。
import numpy as np
import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
# ── 400 customers, NO labels — just two features ───────────
rng = np.random.default_rng(7)
centres = [(1.5, 9), (4, 4), (8, 1.5), (6, 8)] # (visits/week, avg spend ₹k)
df = pd.DataFrame(np.vstack([rng.normal(c, (0.8, 1.0), (100, 2)) for c in centres]),
columns=['visits_per_week', 'avg_spend_k'])
# ── Scale features (K-Means uses distances) ────────────────
X_scaled = StandardScaler().fit_transform(df)
# ── Ask K-Means for 4 groups ───────────────────────────────
kmeans = KMeans(n_clusters=4, random_state=42, n_init=10)
df['cluster'] = kmeans.fit_predict(X_scaled)
print(df.groupby('cluster').agg(customers=('avg_spend_k', 'size'),
visits=('visits_per_week', 'mean'),
spend=('avg_spend_k', 'mean')).round(1))
Try It — Watch K-Means Work
Each dot is a customer. Press Step to watch K-Means alternate between its two moves, or Run to let it finish.
आज़माएँ — K-Means को काम करते देखें
हर बिंदु एक ग्राहक है। कदम दबाकर देखें कि K-Means अपनी दो चालों के बीच कैसे बदलता है, या चलाएँ दबाकर उसे पूरा होने दें।
动手试试——观看 K-Means 的工作过程
每个点代表一位顾客。点击单步观察 K-Means 如何交替执行两个动作,或点击运行让它自动完成。
The Machine Learning Workflow
Real ML projects follow the same steps. Rushing an early step causes problems later: bad data in means bad predictions out, and a model that was never tested properly can fail quietly after launch.
Collecting, cleaning and exploring data (steps 2–4) usually take most of the time — often around 60–80% of a project. Training and tuning are often the quickest part once the data is ready.
Split off the test data before cleaning, scaling or choosing features. If the test data influences any of these steps, information "leaks" into training and your test score will look better than reality. Section 10 shows how a scikit-learn Pipeline prevents this.
Overfitting & Underfitting — The Central Challenge
The real goal of ML is not to do well on the training data. It is to do well on new data. This is called generalisation. A model that is too simple misses real patterns — underfitting. A model that is too complex memorises the training data, noise included — overfitting. We want the middle: complex enough for the signal, simple enough to ignore the noise.
Try It — The Overfitting Lab
We fit curves of rising complexity to 15 homes (blue). The dashed line is the true pattern. Orange circles are new homes used for validation. Watch the right-hand chart: training error keeps falling, but validation error falls and then rises.
Machine Learning का workflow
असली ML प्रोजेक्ट एक जैसे कदमों पर चलते हैं। शुरुआती कदम में जल्दबाज़ी बाद में दिक्कतें लाती है: खराब data अंदर तो खराब अनुमान बाहर, और जिस model को ठीक से परखा नहीं गया वह लॉन्च के बाद चुपचाप फ़ेल हो सकता है।
data इकट्ठा करना, साफ़ करना और समझना (कदम 2–4) आमतौर पर सबसे ज़्यादा समय लेते हैं — अक्सर प्रोजेक्ट का लगभग 60–80%। data तैयार होने के बाद training और tuning अक्सर सबसे तेज़ हिस्सा होते हैं।
data साफ़ करने, स्केल करने या feature चुनने से पहले test data अलग कर लें। अगर test data इनमें से किसी कदम पर असर डालता है, तो जानकारी training में "लीक" हो जाती है और test स्कोर असलियत से बेहतर दिखता है। सेक्शन 10 दिखाता है कि scikit-learn का Pipeline इसे कैसे रोकता है।
Overfitting और Underfitting — मुख्य चुनौती
ML का असली लक्ष्य training data पर अच्छा करना नहीं है, बल्कि नए data पर अच्छा करना है। इसे जनरलाइज़ेशन कहते हैं। बहुत सरल model असली पैटर्न चूक जाता है — Underfitting। बहुत जटिल model training data को शोर समेत रट लेता है — Overfitting। हमें बीच का रास्ता चाहिए: संकेत पकड़ने लायक जटिल, पर शोर को अनदेखा करने लायक सरल।
आज़माएँ — Overfitting लैब
हम 15 घरों (नीले) पर बढ़ती जटिलता वाले वक्र fit करते हैं। डैश वाली रेखा असली पैटर्न है। नारंगी गोले validation के लिए नए घर हैं। दाएँ चार्ट को देखें: training error घटती रहती है, पर validation error पहले घटती है और फिर बढ़ती है।
Machine Learning 的 workflow 程
真实的 Machine Learning 项目都遵循同样的步骤。早期步骤草率,后面就会出问题:垃圾数据进,垃圾预测出;没有好好测试的模型上线后可能悄无声息地失效。
收集、清洗和探索数据(第 2–4 步)通常最花时间——往往占项目的 60–80% 左右。数据准备好以后,训练和调参往往是最快的部分。
在清洗、缩放或挑选 feature 之前先把 test data 分出去。如果 test data 影响了其中任何一步,信息就会"泄漏"到训练中,测试分数会比实际更好看。第 10 节展示 scikit-learn 的 Pipeline 如何避免这个问题。
Overfitting 与 Underfitting——核心挑战
Machine Learning 真正的目标不是在 training data 上表现好,而是在新数据上表现好,这叫泛化。太简单的模型会错过真实规律——Underfitting。太复杂的模型会把 training data 连同 noise 一起背下来——Overfitting。我们要的是中间状态:复杂到能抓住信号,又简单到能忽略 noise。
动手试试——Overfitting 实验室
我们用复杂度不断增加的曲线去 fit 15 套房子(蓝色)。虚线是真实规律,橙色圆圈是用于验证的新房子。看右边的图:training error 一直下降,而 validation error 先降后升。
Fixes for Underfitting and Overfitting
| Problem | How it looks | Fix | scikit-learn example |
|---|---|---|---|
| Underfitting | Training and test scores are both low | Use a more flexible model, add better features, reduce the penalty | max_depth=None, higher C |
| Overfitting | Training score high, test score much lower | Simpler model, more data, regularisation | max_depth=3, lower C, Ridge(alpha=…) |
| Overfitting | Big gap between training and validation curves | Stop training early; average many models | early_stopping=True, RandomForestClassifier |
| Not sure? | One train/test split gives a noisy answer | Use cross-validation to compare settings fairly | cross_val_score(model, X, y, cv=5) |
The Bias-Variance Tradeoff
Imagine collecting a new training set and training the same kind of model again. Bias asks: on average, is the model in the right place? Variance asks: how much does the model change from one training set to the next? Simple models usually have high bias; very complex models usually have high variance.
| What it is: the model is too simple |
| Misses real patterns |
| Wrong on training and test data |
| Different training sets give almost the same (wrong) model |
| Example: a straight line for curved data |
| Fix: more flexible model, better features |
| What it is: the model is too complex for the data |
| Fits the training data almost perfectly |
| Does much worse on new data |
| Different training sets give very different models |
| Example: a very deep tree on a small dataset |
| Fix: regularise, prune, more data, average many models |
Try It — Many Training Sets
Each green line is the same kind of model trained on a different random set of 20 homes. The purple line is their average; the dashed line is the truth. Pick a model and press +30 training sets.
Underfitting और Overfitting के उपाय
| समस्या | कैसे दिखती है | उपाय | scikit-learn उदाहरण |
|---|---|---|---|
| Underfitting | training और test दोनों स्कोर कम | ज़्यादा लचीला model, बेहतर feature, कम penalty | max_depth=None, बड़ा C |
| Overfitting | training स्कोर ऊँचा, test स्कोर बहुत कम | सरल model, ज़्यादा data, regularisation | max_depth=3, छोटा C, Ridge(alpha=…) |
| Overfitting | training और validation वक्रों में बड़ा अंतर | training जल्दी रोकें; कई models का औसत लें | early_stopping=True, RandomForestClassifier |
| पक्का नहीं? | एक train/test बँटवारा अस्थिर उत्तर देता है | सेटिंग्स की निष्पक्ष तुलना के लिए cross-validation | cross_val_score(model, X, y, cv=5) |
Bias-Variance ट्रेडऑफ़
कल्पना कीजिए कि आप एक नया training set इकट्ठा करते हैं और उसी तरह का model फिर से train करते हैं। Bias पूछता है: औसतन, क्या model सही जगह है? Variance पूछता है: एक training set से दूसरे तक model कितना बदलता है? सरल models में आमतौर पर Bias ज़्यादा होता है; बहुत जटिल models में Variance।
| क्या है: model बहुत सरल है |
| असली पैटर्न चूक जाता है |
| training और test दोनों पर गलत |
| अलग training set लगभग एक जैसा (गलत) model देते हैं |
| उदाहरण: टेढ़े data पर सीधी रेखा |
| उपाय: ज़्यादा लचीला model, बेहतर feature |
| क्या है: data के हिसाब से model बहुत जटिल है |
| training data पर लगभग पूरी तरह fit |
| नए data पर बहुत खराब |
| अलग training set बहुत अलग model देते हैं |
| उदाहरण: छोटे dataset पर बहुत गहरा ट्री |
| उपाय: रेगुलराइज़ करें, प्रून करें, ज़्यादा data, कई models का औसत |
आज़माएँ — कई training set
हर हरी रेखा उसी तरह का model है, जो 20 घरों के अलग यादृच्छिक सेट पर train हुआ है। बैंगनी रेखा उनका औसत है; डैश वाली रेखा सच है। एक model चुनें और +30 training set दबाएँ।
Underfitting 与 Overfitting 的解决办法
| 问题 | 表现 | 解决办法 | scikit-learn 示例 |
|---|---|---|---|
| Underfitting | 训练分数和测试分数都低 | 换更灵活的模型、加入更好的 feature、减小 penalty | max_depth=None,更大的 C |
| Overfitting | 训练分数高,测试分数低得多 | 更简单的模型、更多数据、regularisation | max_depth=3,更小的 C,Ridge(alpha=…) |
| Overfitting | 训练曲线和验证曲线差距很大 | 提前停止训练;对多个模型取平均 | early_stopping=True,RandomForestClassifier |
| 拿不准? | 单次训练/测试划分的结果不稳定 | 用 cross-validation 公平地比较不同设置 | cross_val_score(model, X, y, cv=5) |
Bias-Variance 权衡
设想你重新收集一个新的 training set,再训练同一种模型。Bias 问的是:平均来看,模型的位置对不对?Variance 问的是:换一个 training set,模型会变化多少?简单模型通常 Bias 高;非常复杂的模型通常 Variance 高。
| 是什么:模型太简单 |
| 错过真实规律 |
| 在 training data 和 test data 上都不准 |
| 不同 training set 得到几乎一样(但错误)的模型 |
| 例子:用直线去 fit 弯曲的数据 |
| 解决:更灵活的模型、更好的 feature |
| 是什么:相对于数据,模型太复杂 |
| 几乎完美地 fit training data |
| 在新数据上差很多 |
| 不同 training set 得到差别很大的模型 |
| 例子:在小 dataset 上训练很深的 Decision Tree |
| 解决:regularisation、剪枝、更多数据、多个模型取平均 |
动手试试——许多个 training set
每条绿线都是同一种模型,分别在不同的 20 套随机房子上训练得到。紫线是它们的平均,虚线是真实规律。选一个模型,然后点击 +30 个 training set。
Model Evaluation — Choosing the Right Metric
Accuracy is easy to understand but often misleading. Suppose 99% of patients are healthy. A model that says "healthy" to everyone is 99% accurate — and finds no sick patients. Always pick a metric that matches the real cost of each kind of mistake.
⚠ MISSED
Accuracy 99% | Precision: undefined (no positives) | Recall 0% — finds nobody
Accuracy 98.1% | Precision 33% | Recall 88% | F1 0.48 — finds 88 of 100
| Metric | Formula | Use when | Be careful when |
|---|---|---|---|
| Accuracy | (TP+TN) / all | Classes are balanced and both mistakes cost the same | One class is rare — it looks good while missing it |
| Precision | TP / (TP+FP) | False alarms are costly (e.g. blocking real emails) | Missing a case is the bigger danger |
| Recall | TP / (TP+FN) | Missing a case is costly (disease, fraud) | False alarms are expensive |
| F1 score | 2·P·R / (P+R) | Rare class; you need both precision and recall | The two mistakes have very different costs |
| ROC-AUC | Area under the ROC curve | Judging how well the model ranks cases, at all thresholds | Very rare class — also check PR-AUC |
| RMSE | √(Σ(y−ŷ)² / n) | Regression where big errors are especially bad | Outliers — one huge error dominates |
| MAE | Σ|y−ŷ| / n | Regression; easy to explain; less affected by outliers | You must punish big errors more |
Try It — The Accuracy Trap
10,000 patients, only 100 of them sick. The model gives every patient a score. Move the threshold: everyone to the right is called "sick". Start with "predict healthy for all".
model का मूल्यांकन — सही metric चुनना
Accuracy (accuracy) समझना आसान है पर अक्सर भ्रामक होती है। मान लीजिए 99% मरीज़ स्वस्थ हैं। जो model हर किसी को "स्वस्थ" कहे, वह 99% सटीक है — और एक भी बीमार मरीज़ नहीं पकड़ता। हमेशा ऐसा metric चुनें जो हर तरह की गलती की असली कीमत से मेल खाए।
⚠ छूटे
Accuracy 99% | Precision: परिभाषित नहीं (कोई positive नहीं) | Recall 0% — किसी को नहीं पकड़ता
Accuracy 98.1% | Precision 33% | Recall 88% | F1 0.48 — 100 में से 88 को पकड़ता है
| metric | सूत्र | कब इस्तेमाल करें | कब सावधान रहें |
|---|---|---|---|
| Accuracy (Accuracy) | (TP+TN) / कुल | श्रेणियाँ संतुलित हों और दोनों गलतियों की कीमत बराबर हो | एक श्रेणी दुर्लभ हो — उसे चूकते हुए भी अच्छी दिखती है |
| Precision | TP / (TP+FP) | झूठी चेतावनी महँगी हो (जैसे असली ईमेल रोकना) | किसी मामले को चूकना ज़्यादा बड़ा खतरा हो |
| Recall | TP / (TP+FN) | मामला चूकना महँगा हो (बीमारी, धोखाधड़ी) | झूठी चेतावनियाँ महँगी हों |
| F1 स्कोर | 2·P·R / (P+R) | दुर्लभ श्रेणी; Precision और Recall दोनों चाहिए | दोनों गलतियों की कीमत बहुत अलग हो |
| ROC-AUC | ROC वक्र के नीचे का क्षेत्र | सभी threshold पर model की रैंकिंग क्षमता परखना | बहुत दुर्लभ श्रेणी — PR-AUC भी देखें |
| RMSE | √(Σ(y−ŷ)² / n) | regression, जहाँ बड़ी गलतियाँ खास तौर पर बुरी हों | outlier — एक बहुत बड़ी गलती हावी हो जाती है |
| MAE | Σ|y−ŷ| / n | regression; समझाना आसान; outlier का असर कम | बड़ी गलतियों को ज़्यादा सज़ा देनी हो |
आज़माएँ — Accuracy का जाल
10,000 मरीज़, जिनमें से सिर्फ़ 100 बीमार हैं। model हर मरीज़ को एक स्कोर देता है। threshold खिसकाएँ: दाईं ओर के सभी को "बीमार" कहा जाएगा। "सबको स्वस्थ कहो" से शुरू करें।
模型评估——选择合适的指标
Accuracy 很好理解,但常常会误导人。假设 99% 的病人是健康的。一个对所有人都说"健康"的模型 Accuracy 是 99%——却一个病人也找不出来。一定要选择与每种错误的真实代价相匹配的指标。
⚠ 漏诊
Accuracy 99% | Precision:无定义(没有阳性预测) | Recall 0%——一个也没找到
Accuracy 98.1% | Precision 33% | Recall 88% | F1 0.48——100 人中找到 88 人
| 指标 | 公式 | 适用场景 | 需要小心的情况 |
|---|---|---|---|
| Accuracy | (TP+TN) / 全部 | 各类数量均衡,两种错误代价相同 | 某一类很少见——漏掉它分数照样好看 |
| Precision | TP / (TP+FP) | 误报代价高(例如拦截正常邮件) | 漏掉病例的危害更大 |
| Recall | TP / (TP+FN) | 漏报代价高(疾病、欺诈) | 误报代价很高 |
| F1 分数 | 2·P·R / (P+R) | 少数类问题;Precision 和 Recall 都需要 | 两种错误的代价相差很大 |
| ROC-AUC | ROC 曲线下的面积 | 在所有 threshold 下评估模型的排序能力 | 类别极不平衡——还要看 PR-AUC |
| RMSE | √(Σ(y−ŷ)² / n) | regression 问题,大 error 特别糟糕时 | 存在 outlier——一个巨大 error 会主导结果 |
| MAE | Σ|y−ŷ| / n | regression 问题;容易解释;受 outlier 影响较小 | 需要更重地 penalty 大 error 时 |
动手试试——Accuracy 陷阱
10,000 名病人,其中只有 100 人患病。模型给每位病人打一个分数。移动 threshold:threshold 右边的人都被判为"患病"。先从"全部预测为健康"开始。
Common ML Algorithms — When to Use Which
The chart below is a real run: six common algorithms on the same dataset (scikit-learn's breast cancer data, 569 patients), each scored with 5-fold cross-validation. The code is just below it.
On this small, clean dataset the simple models (Logistic Regression, SVM) do best. The single Decision Tree scores 100% on training data but lowest on new data — clear overfitting. Random Forest and Gradient Boosting fix much of that, but took about 100× longer to train here. The best algorithm depends on the data, so always compare against a simple baseline.
आम ML algorithm — कब कौन-सा
नीचे का चार्ट एक असली रन है: एक ही dataset (scikit-learn का ब्रेस्ट कैंसर data, 569 मरीज़) पर छह आम algorithm, हर एक को 5-fold cross-validation से परखा गया। कोड इसके ठीक नीचे है।
इस छोटे, साफ़ dataset पर सरल model (Logistic Regression, SVM) सबसे अच्छा करते हैं। अकेला Decision Tree training data पर 100% लाता है पर नए data पर सबसे कम — साफ़ Overfitting। Random Forest और Gradient Boosting इसे काफ़ी हद तक ठीक करते हैं, पर यहाँ उन्हें train होने में लगभग 100 गुना समय लगा। सबसे अच्छा algorithm data पर निर्भर करता है, इसलिए हमेशा एक सरल baseline से तुलना करें।
常见 Machine Learning algorithm——何时用哪一个
下面的图表是一次真实运行的结果:在同一个 dataset(scikit-learn 的乳腺癌数据,569 名病人)上运行六种常见 algorithm,每种都用 5 折 cross-validation 评分。代码就在图表下方。
在这个小而干净的 dataset 上,简单模型(Logistic Regression、SVM)表现最好。单棵 Decision Tree 在 training data 上得到 100%,在新数据上却最低——明显的 Overfitting。Random Forest 和 Gradient Boosting 在很大程度上弥补了这一点,但在这里训练时间大约多了 100 倍。最好的 algorithm 取决于数据,所以一定要和一个简单的 baseline 做比较。
from sklearn.datasets import load_breast_cancer
from sklearn.model_selection import cross_validate, StratifiedKFold
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
from sklearn.neighbors import KNeighborsClassifier
X, y = load_breast_cancer(return_X_y=True) # 569 patients, 30 features
models = {
'Logistic Regression': make_pipeline(StandardScaler(), LogisticRegression(max_iter=1000)),
'Decision Tree': DecisionTreeClassifier(random_state=42),
'Random Forest': RandomForestClassifier(n_estimators=200, random_state=42),
'Gradient Boosting': GradientBoostingClassifier(random_state=42),
'SVM (RBF)': make_pipeline(StandardScaler(), SVC()),
'k-NN (k=5)': make_pipeline(StandardScaler(), KNeighborsClassifier()),
}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
print(f"{'Model':<22}{'Train acc':>10}{'CV acc':>9}")
for name, model in models.items():
r = cross_validate(model, X, y, cv=cv, return_train_score=True)
print(f"{name:<22}{r['train_score'].mean():>10.3f}{r['test_score'].mean():>9.3f}")
| Algorithm | Type | Good for | Needs scaling? | Easy to explain? |
|---|---|---|---|---|
| Linear / Logistic Regression | Linear | First baseline; clear, simple relationships | Yes | Yes |
| Decision Tree | Tree | Readable if-else rules; mixed data types | No | Yes |
| Random Forest | Ensemble | Strong all-rounder; handles noise well | No | Partly |
| Gradient Boosting (XGBoost, LightGBM) | Ensemble | Often the best on large tables of data | No | Partly |
| SVM | Kernel | Small and medium datasets, many features, text | Yes | No |
| k-Nearest Neighbours | Instance-based | Simple baseline; small datasets | Yes | Partly |
| Neural Network | Deep learning | Images, text, audio; very large datasets | Yes | No |
Complete ML Pipeline in Python
This is a full, runnable template for a supervised project: it creates example data, fills missing values, scales numbers, encodes categories, tunes a model with cross-validation, tests it once on held-out data and saves it. Replace the example data with your own CSV.
| algorithm | प्रकार | किसके लिए अच्छा | scaling चाहिए? | समझाना आसान? |
|---|---|---|---|---|
| Linear / Logistic Regression | linear | पहली baseline; साफ़, सरल संबंध | हाँ | हाँ |
| Decision Tree | ट्री | पढ़ने योग्य if-else नियम; मिले-जुले data प्रकार | नहीं | हाँ |
| Random Forest | ensemble | मज़बूत ऑल-राउंडर; शोर अच्छी तरह सँभालता है | नहीं | कुछ हद तक |
| Gradient Boosting (XGBoost, LightGBM) | ensemble | बड़ी टेबल वाले data पर अक्सर सबसे अच्छा | नहीं | कुछ हद तक |
| SVM | कर्नेल | छोटे-मध्यम dataset, बहुत feature, टेक्स्ट | हाँ | नहीं |
| k-Nearest Neighbours | उदाहरण-आधारित | सरल baseline; छोटे dataset | हाँ | कुछ हद तक |
| Neural Network | Deep Learning | तस्वीरें, टेक्स्ट, ऑडियो; बहुत बड़े dataset | हाँ | नहीं |
Python में पूरी ML pipeline
यह एक Supervised प्रोजेक्ट का पूरा, चलने योग्य टेम्पलेट है: यह उदाहरण data बनाता है, खाली मान भरता है, संख्याओं को स्केल करता है, श्रेणियों को एनकोड करता है, cross-validation से model tune करता है, अलग रखे data पर एक बार परखता है और उसे सेव करता है। उदाहरण data की जगह अपनी CSV लगाएँ।
| algorithm | 类型 | 擅长 | 需要缩放? | 容易解释? |
|---|---|---|---|---|
| 线性 / Logistic Regression | 线性 | 第一个 baseline;清晰、简单的关系 | 是 | 是 |
| Decision Tree | 树 | 可读的 if-else 规则;混合数据类型 | 否 | 是 |
| Random Forest | 集成 | 强大的通用模型;对 noise 稳健 | 否 | 部分 |
| Gradient Boosting(XGBoost、LightGBM) | 集成 | 在大型表格数据上常常最好 | 否 | 部分 |
| SVM | 核方法 | 中小型 dataset、feature 很多、文本 | 是 | 否 |
| k-Nearest Neighbours | 基于实例 | 简单 baseline;小 dataset | 是 | 部分 |
| Neural Network | Deep Learning | 图像、文本、音频;超大 dataset | 是 | 否 |
用 Python 搭建完整的 Machine Learning pipeline
这是一个完整、可运行的 Supervised Learning 项目模板:它生成示例数据、填补缺失值、缩放数值、编码类别、用 cross-validation 调参、在留出的数据上测试一次,最后保存模型。把示例数据换成你自己的 CSV 即可。
import numpy as np
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.impute import SimpleImputer
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.model_selection import train_test_split, StratifiedKFold, GridSearchCV
from sklearn.metrics import classification_report, roc_auc_score
import joblib
# ── 0. Example data: 5,000 loan customers (replace with your own CSV) ──
rng = np.random.default_rng(0)
n = 5_000
df = pd.DataFrame({
'age': rng.integers(21, 70, n),
'income': rng.normal(60, 20, n).round(1), # ₹ thousand / month
'credit_score': rng.integers(500, 850, n),
'balance': rng.normal(200, 80, n).round(1),
'city': rng.choice(['Mumbai', 'Delhi', 'Pune', 'Baddi'], n),
'product_type': rng.choice(['card', 'loan', 'emi'], n),
})
risk = (-0.012 * (df.credit_score - 675) - 0.03 * (df.income - 60)
+ 0.006 * (df.balance - 200) + 0.4 * (df.product_type == 'emi'))
df['default'] = (rng.random(n) < 1 / (1 + np.exp(-(risk - 1.6)))).astype(int)
df.loc[rng.random(n) < 0.05, 'income'] = np.nan # some missing values
X, y = df.drop(columns='default'), df['default']
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42, stratify=y)
# ── 1. Define column types ─────────────────────────────────
num_cols = ['age', 'income', 'credit_score', 'balance']
cat_cols = ['city', 'product_type']
# ── 2. Preprocessing sub-pipelines ─────────────────────────
num_pipe = Pipeline([('imp', SimpleImputer(strategy='median')),
('sc', StandardScaler())])
cat_pipe = Pipeline([('imp', SimpleImputer(strategy='most_frequent')),
('ohe', OneHotEncoder(handle_unknown='ignore'))])
preprocessor = ColumnTransformer([('num', num_pipe, num_cols),
('cat', cat_pipe, cat_cols)])
# ── 3. Full ML pipeline ────────────────────────────────────
full_pipe = Pipeline([('prep', preprocessor),
('model', GradientBoostingClassifier(random_state=42))])
# ── 4. Hyperparameter tuning with 5-fold cross-validation ──
param_grid = {'model__n_estimators': [100, 300],
'model__learning_rate': [0.05, 0.1],
'model__max_depth': [2, 3]}
cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=42)
gs = GridSearchCV(full_pipe, param_grid, cv=cv, scoring='roc_auc', n_jobs=-1)
gs.fit(X_train, y_train)
print(f"Best CV AUC-ROC : {gs.best_score_:.4f}")
print(f"Best params : {gs.best_params_}")
# ── 5. Final evaluation on the untouched test set ──────────
best = gs.best_estimator_
y_pred = best.predict(X_test)
y_prob = best.predict_proba(X_test)[:, 1]
print(classification_report(y_test, y_pred))
print(f"Test AUC-ROC : {roc_auc_score(y_test, y_prob):.4f}")
# ── 6. Save the whole pipeline (preprocessing + model) ─────
joblib.dump(best, 'ml_pipeline.pkl')
Inside cross-validation, the imputer and scaler are re-fitted on the training folds only, so no information leaks from the validation fold. Saving the pipeline also saves the preprocessing, so new data is prepared in exactly the same way. Notice the result: accuracy 81%, but recall for defaulters is only 0.44 — a good reason to tune the decision threshold next.
Golden Rules of Machine Learning
debt_to_income_ratio or days_since_last_purchase can help more than switching algorithms.Machine learning is not magic — it is learning from examples, checked carefully on new data. The most useful skill is not knowing many algorithms. It is understanding the problem, the data, and how to measure whether the model is really good.
cross-validation के अंदर imputer और scaler केवल training fold पर दोबारा fit होते हैं, इसलिए validation fold से कोई जानकारी लीक नहीं होती। pipeline सेव करने से प्रीप्रोसेसिंग भी सेव होती है, इसलिए नया data बिल्कुल उसी तरह तैयार होता है। नतीजा देखें: Accuracy 81%, पर default करने वालों के लिए Recall सिर्फ़ 0.44 — अगला कदम डिसीज़न threshold tune करना होना चाहिए।
Machine Learning के सुनहरे नियम
debt_to_income_ratio या days_since_last_purchase जैसा सोच-समझकर बनाया feature algorithm बदलने से ज़्यादा मदद कर सकता है।Machine Learning जादू नहीं है — यह उदाहरणों से सीखना है, जिसे नए data पर ध्यान से परखा जाता है। सबसे काम का हुनर बहुत सारे algorithm जानना नहीं है, बल्कि समस्या को, data को, और यह मापने के तरीके को समझना है कि model सच में अच्छा है या नहीं।
在 cross-validation 中,填补器和缩放器只在训练折上重新 fit,所以验证折的信息不会泄漏。保存 pipeline 时预处理也一起被保存,新数据会按完全相同的方式处理。注意结果:Accuracy 81%,但违约者的 Recall 只有 0.44——下一步应该调整判定 threshold。
Machine Learning 的黄金法则
debt_to_income_ratio 或 days_since_last_purchase,带来的提升可能比换 algorithm 还大。Machine Learning 不是魔法——它是从例子中学习,并在新数据上认真检验。最有用的能力不是知道很多 algorithm,而是理解问题、理解数据,以及知道如何衡量模型是否真的好。