Seedha content par jao
🤖 Python Hindi Bot
Namaste! Main Python Hindi Bot hoon 🐍
Python ya AI se related kuch bhi type karke pucho, ya neeche se quick sawaal chuno.
WhatsApp

Stay Connected with PythonHindii

Join our WhatsApp Community to get the latest Python tutorials, coding tips, interview questions, project updates, and learning resources directly on your phone.

Join WhatsApp Community
⇧
Python Hindi Logo
Python in Hindi | Programming Education

XGBoost & LightGBM in Python Hindi: Gradient Boosting सीखें

XGBoost और LightGBM in Python: Gradient Boosting आसान हिंदी में

Machine Learning में जब data table (rows और columns) के रूप में हो, जैसे customers की जानकारी, loan applications या sensors की readings, तब सबसे ज्यादा इस्तेमाल होने वाले और असरदार तरीकों में Gradient Boosting का नाम आता है। Python में इसे इस्तेमाल करने की दो बहुत लोकप्रिय libraries हैं: XGBoost और LightGBM।

इस tutorial में आप सीखेंगे कि Ensemble Learning क्या है, Gradient Boosting कैसे काम करता है, Decision Trees मिलकर एक मज़बूत model कैसे बनाते हैं, XGBoost और LightGBM क्या हैं और उनमें क्या अंतर है, दोनों को install कैसे करें, leaf-wise tree growth और histogram-based learning क्या हैं, classification के लिए model कैसे train करें, train-test split और accuracy से model कैसे जाँचें, कौन-से hyperparameters सबसे जरूरी हैं, और overfitting व cross-validation का क्या मतलब है।

इस lesson के लिए Python की basics, lists और loops की समझ चाहिए। जरूरत हो तो Python Lists Complete Guide in Hindi और Python For Loop in Hindi पहले पढ़ लें। Code चलाते समय error आए, तो Python Exception Handling in Hindi भी काम आएगा।

📌 इस Lesson का Scope: यह beginner-friendly introduction है। इसमें classification पर ध्यान है। Regression, ranking, GPU training, GridSearch/Optuna से tuning, SHAP और model deployment को detail में नहीं पढ़ाया गया है।
🎥 Video में Topic समझें

Ensemble Learning क्या है?

Ensemble Learning का विचार सीधा है: एक अकेले model पर भरोसा करने की जगह कई models को मिलाकर फैसला लिया जाए। जैसे किसी मुश्किल सवाल पर एक व्यक्ति की जगह कई लोगों की राय लें, तो आम तौर पर बेहतर जवाब मिलता है।

Ensemble के दो आम तरीके हैं:

तरीकाकैसे काम करता हैउदाहरण
Baggingकई trees एक साथ, अलग-अलग data के हिस्सों पर बनते हैं और उनके जवाब मिला दिए जाते हैं।Random Forest
BoostingTrees एक के बाद एक बनते हैं, और हर नया tree पिछले trees की गलतियाँ सुधारने पर ध्यान देता है।Gradient Boosting, XGBoost, LightGBM

Decision Trees मिलकर कैसे काम करते हैं?

एक Decision Tree data को सवालों की शृंखला से बाँटता है, जैसे "क्या age 30 से ज्यादा है?" फिर "क्या income 50,000 से ज्यादा है?" और अंत में एक नतीजा देता है। अकेला छोटा tree कमज़ोर होता है, इसलिए उसे weak learner कहते हैं।

Boosting में ऐसे कई छोटे trees एक क्रम में जोड़े जाते हैं। पहला tree एक मोटा-मोटा अनुमान देता है, दूसरा tree उस अनुमान की गलती पर काम करता है, तीसरा बची हुई गलती पर, और इसी तरह आगे। सब trees के योगदान को जोड़कर अंतिम prediction बनता है।

Tree 1 (मोटा अनुमान) ▼ गलती (error) बचती है Tree 2 (गलती सुधारता है) ▼ थोड़ी गलती अब भी बची Tree 3 (और सुधार) ▼ ... → सभी trees का जोड़ = अंतिम prediction

Gradient Boosting क्या है?

Gradient Boosting एक boosting तरीका है जिसमें हर नया tree पिछले model की गलतियों (residuals) को कम करने के लिए बनता है। "Gradient" शब्द इसलिए है क्योंकि यह loss function को घटाने के लिए gradient की दिशा में कदम बढ़ाता है। शुरुआत में इसे इस सरल रूप में समझना काफी है:

  1. पहले एक साधारण अनुमान लें (जैसे सभी का औसत)।
  2. असली मान और अनुमान का अंतर (residual) निकालें।
  3. एक छोटा tree बनाएँ जो इस residual को predict करे।
  4. उस tree का सिर्फ थोड़ा हिस्सा (learning rate × tree का अनुमान) अपने अनुमान में जोड़ें।
  5. नए residual निकालकर यह प्रक्रिया बार-बार दोहराएँ।
नया अनुमान = पुराना अनुमान + learning_rate × (नए tree का अनुमान)

एक छोटा उदाहरण (बिना library के)

तीन students के असली नंबर 50, 60 और 80 हैं। नीचे के code में सरलता के लिए मान लिया गया है कि हर tree residual को ठीक-ठीक predict कर लेता है। असली trees ऐसा सिर्फ लगभग करते हैं, लेकिन विचार यही रहता है।

Example — Residual घटते जाना
y = [50, 60, 80] pred = [sum(y) / len(y)] * 3 # शुरुआती अनुमान: औसत lr = 0.5 # learning rate print("Start:", [round(p, 2) for p in pred]) for r in range(1, 4): res = [a - p for a, p in zip(y, pred)] pred = [p + lr * e for p, e in zip(pred, res)] print(f"Round {r}: residual={[round(e, 2) for e in res]} -> new prediction={[round(p, 2) for p in pred]}")

Terminal Output:

Start: [63.33, 63.33, 63.33] Round 1: residual=[-13.33, -3.33, 16.67] -> new prediction=[56.67, 61.67, 71.67] Round 2: residual=[-6.67, -1.67, 8.33] -> new prediction=[53.33, 60.83, 75.83] Round 3: residual=[-3.33, -0.83, 4.17] -> new prediction=[51.67, 60.42, 77.92]

हर round में residual घटता गया और prediction असली मान (50, 60, 80) के पास पहुँचता गया। यही boosting का मूल विचार है।

Single Tree बनाम Boosting (असली demo)

अब scikit-learn के built-in breast cancer dataset पर देखें कि एक अकेला छोटा tree और boosting में क्या फर्क पड़ता है। यहाँ हम scikit-learn का GradientBoostingClassifier इस्तेमाल कर रहे हैं, ताकि कुछ extra install किए बिना यही विचार चलाकर देखा जा सके।

Example
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.tree import DecisionTreeClassifier from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import accuracy_score data = load_breast_cancer() X, y = data.data, data.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) # एक अकेला छोटा tree (सिर्फ एक सवाल पूछता है) stump = DecisionTreeClassifier(max_depth=1, random_state=42) stump.fit(X_train, y_train) print("Single stump:", round(accuracy_score(y_test, stump.predict(X_test)), 4)) # ऐसे 100 छोटे trees, boosting से जुड़े हुए gb = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=1, random_state=42 ) gb.fit(X_train, y_train) print("Boosting 100 stumps:", round(accuracy_score(y_test, gb.predict(X_test)), 4))

Terminal Output:

Single stump: 0.8947 Boosting 100 stumps: 0.9561

एक अकेले छोटे tree की accuracy लगभग 0.89 रही, जबकि ऐसे ही 100 छोटे trees को boosting से जोड़ने पर लगभग 0.96। आपके scikit-learn version पर आंकड़े थोड़े अलग हो सकते हैं।

XGBoost in Python क्या है?

XGBoost (eXtreme Gradient Boosting) एक popular open-source Gradient Boosting library है। इसका नाम "extreme" इसलिए है क्योंकि इसे तेज़ और ताकतवर बनाने पर बहुत ध्यान दिया गया है। इसकी मुख्य बातें:

  • Decision trees पर आधारित gradient boosting।
  • Regularization (L1/L2) की सुविधा, जिससे overfitting घटाने में मदद मिलती है।
  • Missing values को संभालने की क्षमता।
  • Parallel processing और तेज़ training।
  • scikit-learn जैसा आसान interface (XGBClassifier, XGBRegressor)।

LightGBM in Python क्या है?

LightGBM (Light Gradient Boosting Machine) Microsoft द्वारा विकसित एक gradient boosting framework है, जो खास तौर पर तेज़ training और कम memory इस्तेमाल पर केंद्रित है। इसकी दो पहचान हैं: histogram-based learning और leaf-wise tree growth। इसका scikit-learn जैसा interface LGBMClassifier और LGBMRegressor के रूप में मिलता है।

Histogram-based Learning क्या है?

Tree बनाते समय हर split के लिए यह देखना पड़ता है कि किस feature के किस मान पर data को बाँटना सबसे अच्छा रहेगा। अगर किसी continuous feature (जैसे income) के लाखों अलग-अलग मान हों, तो हर मान को जाँचना धीमा और महंगा है।

Histogram-based learning में continuous मानों को पहले सीमित संख्या के bins (डिब्बों) में बाँट दिया जाता है, और split इन्हीं bins की सीमाओं पर खोजा जाता है। इससे training तेज़ होती है और memory कम लगती है। LightGBM की official documentation के अनुसार यह तरीका training को तेज़ करता है और memory use घटाता है। XGBoost में भी histogram-based तरीका (tree_method="hist") मौजूद है।

Income के हज़ारों अलग मान: 12000, 12500, 13100, 47000, 48200 ... ▼ bins में बाँटें Bin 1: कम income | Bin 2: मध्यम income | Bin 3: ज्यादा income ... ▼ Split सिर्फ bins की सीमाओं पर जाँचे जाते हैं (तेज़ और हल्का)

Leaf-wise Tree Growth in LightGBM

Trees दो तरीकों से बढ़ाए जा सकते हैं:

बातLevel-wise (depth-wise)Leaf-wise (best-first)
कैसे बढ़ता हैएक level के सभी nodes साथ में split होते हैंजिस leaf को split करने से loss सबसे ज्यादा घटे, वही split होता है
Tree का आकारसंतुलित (symmetric)असंतुलित, जहाँ जरूरत हो वहाँ गहरा
किसमें आमXGBoost का default (grow_policy="depthwise")LightGBM का तरीका
जोखिमकमछोटे data पर overfitting का खतरा ज्यादा

LightGBM की documentation बताती है कि leaf-wise तरीका leaves की संख्या स्थिर रखने पर आम तौर पर level-wise से कम loss तक पहुँचता है। लेकिन data छोटा हो तो यह overfit कर सकता है, इसलिए max_depth जैसे parameters से tree की गहराई सीमित की जा सकती है। LightGBM में complexity का मुख्य parameter num_leaves है (default 31)।

ध्यान दें: XGBoost भी grow_policy="lossguide" से leaf-wise जैसा तरीका इस्तेमाल कर सकता है। इसलिए "XGBoost = level-wise, LightGBM = leaf-wise" को default व्यवहार की तुलना समझें, कोई कठोर नियम नहीं।

XGBoost vs LightGBM: मुख्य अंतर

बातXGBoostLightGBM
Tree growth (default)Level-wise (depthwise)Leaf-wise (best-first)
Complexity का मुख्य parametermax_depth (default 6)num_leaves (default 31)
Learning rate (parameter का नाम)learning_rate / eta (default 0.3)learning_rate (default 0.1)
Histogram-based तरीकाहाँ (hist)हाँ
Scikit-learn style classesXGBClassifier, XGBRegressorLGBMClassifier, LGBMRegressor
किस पर जोरमज़बूती, regularization, व्यापक featuresतेज़ training और कम memory, खास तौर पर बड़े data पर
कौन-सा चुनें? दोनों बहुत अच्छे हैं। कोई एक हमेशा बेहतर नहीं होता। सबसे अच्छा तरीका है अपने data पर दोनों आज़माना और cross-validation से नतीजे तुलना करना। Default values और व्यवहार versions के साथ बदल सकते हैं, इसलिए XGBoost documentation और LightGBM documentation देखते रहें।

XGBoost और LightGBM कैसे install करें?

Install (Terminal या Command Prompt में)
pip install xgboost lightgbm scikit-learn
Install verify करना
import xgboost import lightgbm import sklearn print("XGBoost:", xgboost.__version__) print("LightGBM:", lightgbm.__version__) print("scikit-learn:", sklearn.__version__)

Terminal Output: आपके installed versions के नंबर print होंगे। उदाहरण के लिए XGBoost: x.y.z जैसा कुछ।

❌ Common Mistake

एक Python में install करके दूसरे Python से program चलाना। ModuleNotFoundError आए तो python -m pip install xgboost lightgbm इस्तेमाल करें, ताकि उसी Python में install हो जो आप चला रहे हैं।

Classification क्या है और Data कैसे तैयार करें?

Classification में model किसी data को एक class में डालता है, जैसे "spam या not spam" या "tumor malignant या benign"। हम scikit-learn का built-in load_breast_cancer dataset इस्तेमाल करेंगे, जिसमें 569 samples और 30 numeric features हैं, और target में दो class हैं (malignant और benign)।

Train-Test Split

Model को उसी data पर जाँचना, जिस पर वह सीखा है, धोखा है। इसलिए data को दो हिस्सों में बाँटते हैं: train set (सीखने के लिए) और test set (अनदेखे data पर जाँच के लिए)। train_test_split यही करता है।

Example
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split data = load_breast_cancer() X, y = data.data, data.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) print("Total:", X.shape) print("Train:", X_train.shape) print("Test :", X_test.shape)

Terminal Output:

Total: (569, 30) Train: (455, 30) Test : (114, 30)

test_size=0.2 का मतलब 20% data test के लिए। random_state=42 हर बार एक जैसा split देता है, ताकि नतीजे दोहराए जा सकें।

Tip: Decision trees पर आधारित models को आम तौर पर features की scaling (जैसे StandardScaler) की जरूरत नहीं पड़ती। यह linear models या neural networks से अलग बात है।

XGBoost Model Training

नीचे XGBoost से classification का पूरा program है। fit() से model सीखता है, predict() से अनुमान लगाता है और accuracy_score से सही अनुमानों का अनुपात निकलता है।

Complete Program — XGBoost
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from xgboost import XGBClassifier data = load_breast_cancer() X, y = data.data, data.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) model = XGBClassifier( n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42, ) model.fit(X_train, y_train) y_pred = model.predict(X_test) print("XGBoost Accuracy:", round(accuracy_score(y_test, y_pred), 4))

Terminal Output:

XGBoost Accuracy: 0.xxxx

यहाँ 0.xxxx की जगह आपके system का असली मान दिखेगा, जो 0 और 1 के बीच होता है। यह मान XGBoost और scikit-learn के versions पर थोड़ा निर्भर कर सकता है, इसलिए मैंने कोई काल्पनिक संख्या नहीं लिखी है।

LightGBM Model Training

LightGBM में structure लगभग वैसा ही है। फर्क यह है कि class का नाम LGBMClassifier है और complexity के लिए num_leaves मुख्य parameter है।

Complete Program — LightGBM
from sklearn.datasets import load_breast_cancer from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score from lightgbm import LGBMClassifier data = load_breast_cancer() X, y = data.data, data.target X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42 ) model = LGBMClassifier( n_estimators=100, learning_rate=0.1, num_leaves=31, random_state=42, verbose=-1, # अतिरिक्त messages बंद ) model.fit(X_train, y_train) y_pred = model.predict(X_test) print("LightGBM Accuracy:", round(accuracy_score(y_test, y_pred), 4))

Terminal Output:

LightGBM Accuracy: 0.xxxx

दोनों की एक साथ तुलना

Example — एक ही split पर दोनों models
from xgboost import XGBClassifier from lightgbm import LGBMClassifier from sklearn.metrics import accuracy_score models = { "XGBoost": XGBClassifier(n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42), "LightGBM": LGBMClassifier(n_estimators=100, learning_rate=0.1, num_leaves=31, random_state=42, verbose=-1), } for name, m in models.items(): m.fit(X_train, y_train) acc = accuracy_score(y_test, m.predict(X_test)) print(name, "Accuracy:", round(acc, 4))

यह code ऊपर वाले split (X_train, X_test आदि) के बाद चलाएँ। इस छोटे dataset पर दोनों के नतीजे आपस में बहुत पास आ सकते हैं, इसलिए सिर्फ एक accuracy देखकर किसी को "जीता हुआ" न मानें।

Feature Importance देखना

Example
import numpy as np importances = model.feature_importances_ top = np.argsort(importances)[::-1][:5] for i in top: print(data.feature_names[i], "->", importances[i])

इससे पता चलता है कि model के लिए कौन-से 5 features सबसे ज्यादा काम के रहे। आउटपुट आपके model और version पर निर्भर करेगा।

Accuracy से Model जाँचना

Accuracy = सही अनुमानों की संख्या ÷ कुल अनुमान। अगर test set के 114 में से 109 अनुमान सही हों, तो accuracy 109/114 ≈ 0.956 होगी।

⚠️ Accuracy की सीमा

अगर data में एक class बहुत ज्यादा हो (जैसे 95% transactions सही और सिर्फ 5% fraud), तो हमेशा "सही" कहने वाला model भी 95% accuracy पा लेगा। ऐसे imbalanced data में precision, recall और F1-score भी देखें। इन metrics को इस lesson में विस्तार से नहीं पढ़ाया गया है।

Important Hyperparameters

Hyperparameters वे settings हैं जो आप training शुरू होने से पहले तय करते हैं। इनका असर model की सटीकता, गति और overfitting पर पड़ता है।

Parameterकामकहाँ
n_estimatorsकुल trees (boosting rounds) की संख्यादोनों
learning_rateहर नया tree कितना योगदान दे (कदम का आकार)दोनों
max_depthTree की अधिकतम गहराईदोनों
num_leavesएक tree में leaves की अधिकतम संख्याLightGBM
subsampleहर tree के लिए data के rows का अनुपातदोनों
colsample_bytreeहर tree के लिए features का अनुपातदोनों
min_child_weight / min_child_samplesएक leaf में कम से कम कितना data चाहिएXGBoost / LightGBM
reg_alpha, reg_lambdaL1 और L2 regularization की ताकतदोनों

Learning Rate, Max Depth और N Estimators

ये तीनों parameters सबसे पहले समझने लायक हैं:

  • n_estimators: जितने ज्यादा trees, उतनी ज्यादा सीखने की क्षमता, लेकिन training धीमी और overfitting का खतरा।
  • learning_rate: छोटा मान = धीमे, सावधान कदम (अक्सर ज्यादा trees चाहिए); बड़ा मान = तेज़ कदम (पर अस्थिरता का खतरा)।
  • max_depth: गहरे trees जटिल पैटर्न पकड़ते हैं, लेकिन training data रटने (overfit) का खतरा बढ़ाते हैं।
अनुभव का नियम: learning_rate और n_estimators आपस में जुड़े हैं। learning_rate घटाएँ तो आम तौर पर n_estimators बढ़ाने पड़ते हैं।

n_estimators का असर (असली demo)

नीचे scikit-learn के Gradient Boosting से देखें कि trees की संख्या बढ़ाने पर train और test accuracy कैसे बदलती है (वही breast cancer dataset और वही split)।

Example
from sklearn.ensemble import GradientBoostingClassifier from sklearn.metrics import accuracy_score for n in [1, 5, 20, 100, 300]: m = GradientBoostingClassifier( n_estimators=n, learning_rate=0.1, max_depth=3, random_state=42 ).fit(X_train, y_train) tr = accuracy_score(y_train, m.predict(X_train)) te = accuracy_score(y_test, m.predict(X_test)) print(n, round(tr, 4), round(te, 4))

Terminal Output (columns: n_estimators, train accuracy, test accuracy):

1 0.6286 0.6228 5 0.9824 0.9561 20 0.9934 0.9561 100 1.0 0.9561 300 1.0 0.9561

सिर्फ 1 tree से model बहुत कमज़ोर है (underfit)। 5 trees के बाद test accuracy स्थिर हो गई, जबकि train accuracy 1.0 तक पहुँच गई। यानी ज्यादा trees से इस छोटे data पर test नतीजा और नहीं सुधरा।

learning_rate का असर

Example
for lr in [0.01, 0.1, 1.0]: m = GradientBoostingClassifier( n_estimators=50, learning_rate=lr, max_depth=3, random_state=42 ).fit(X_train, y_train) tr = accuracy_score(y_train, m.predict(X_train)) te = accuracy_score(y_test, m.predict(X_test)) print(lr, round(tr, 4), round(te, 4))

Terminal Output (columns: learning_rate, train accuracy, test accuracy):

0.01 0.978 0.9561 0.1 1.0 0.9561 1.0 1.0 0.9561

बहुत छोटे learning rate (0.01) के साथ 50 trees में model ने training data को अभी पूरी तरह नहीं सीखा (0.978)। 0.1 पर उसी 50 trees में train accuracy 1.0 हो गई। इसीलिए छोटे learning rate के साथ ज्यादा trees चाहिए।

Overfitting क्या है?

Overfitting तब होती है जब model training data को बहुत अच्छी तरह रट लेता है, लेकिन नए (अनदेखे) data पर खराब चलता है। निशानी: train accuracy बहुत ऊँची, test accuracy उससे काफी कम।

Example — max_depth बढ़ाने पर (असली demo)
for d in [1, 3, 6, 10]: m = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=d, random_state=42 ).fit(X_train, y_train) tr = accuracy_score(y_train, m.predict(X_train)) te = accuracy_score(y_test, m.predict(X_test)) print(d, round(tr, 4), round(te, 4))

Terminal Output (columns: max_depth, train accuracy, test accuracy):

1 0.9912 0.9561 3 1.0 0.9561 6 1.0 0.9474 10 1.0 0.9386

गहराई बढ़ने पर train accuracy 1.0 रही, लेकिन test accuracy घटकर 0.9386 तक आ गई। यह overfitting का संकेत है। (बहुत छोटे test set में ऐसे फर्क मामूली संख्या में rows से भी आ सकते हैं, इसलिए सिर्फ एक split पर निर्णय न लें।)

Overfitting घटाने के आम तरीके

  • max_depth या num_leaves घटाना।
  • learning_rate घटाकर trees की संख्या सोच-समझकर चुनना।
  • subsample और colsample_bytree से randomness जोड़ना।
  • reg_alpha और reg_lambda से regularization बढ़ाना।
  • Early stopping: validation data पर सुधार रुकते ही training रोक देना। इसका syntax versions के हिसाब से बदलता है, इसलिए XGBoost और LightGBM की documentation देखें।

Cross-Validation क्या है?

सिर्फ एक train-test split पर भरोसा करना जोखिम भरा हो सकता है, क्योंकि नतीजा इस पर निर्भर करता है कि कौन-सी rows test में गईं। Cross-validation में data को कई हिस्सों (folds) में बाँटा जाता है। हर बार एक fold test के लिए और बाकी train के लिए इस्तेमाल होता है, और अंत में सभी नतीजों का औसत लिया जाता है। 5-fold cross-validation में 5 बार train और test होता है।

Example — 5-fold Cross-Validation (असली demo)
from sklearn.model_selection import cross_val_score from sklearn.ensemble import GradientBoostingClassifier model = GradientBoostingClassifier( n_estimators=100, learning_rate=0.1, max_depth=3, random_state=42 ) scores = cross_val_score(model, X, y, cv=5, scoring="accuracy") print("Fold scores:", scores.round(4)) print("Mean:", round(scores.mean(), 4)) print("Std :", round(scores.std(), 4))

Terminal Output:

Fold scores: [0.9298 0.9474 0.9737 0.9825 0.9823] Mean: 0.9631 Std : 0.021

पाँचों folds में accuracy 0.93 से 0.98 के बीच रही और औसत लगभग 0.963 है। एक अकेले split से यह तस्वीर ज्यादा भरोसेमंद है।

यही cross_val_score XGBoost और LightGBM के साथ भी चलता है, क्योंकि दोनों के classes scikit-learn style interface देते हैं: cross_val_score(XGBClassifier(...), X, y, cv=5) और cross_val_score(LGBMClassifier(..., verbose=-1), X, y, cv=5)।

Gradient Boosting के Real-world Applications

Gradient boosting (XGBoost, LightGBM और ऐसी ही libraries) खास तौर पर tabular data, यानी rows और columns वाले data पर अक्सर इस्तेमाल होती है:

क्षेत्रउदाहरण
Banking और FinanceCredit risk, loan default और fraud detection
E-commerceCustomer churn, purchase prediction और product ranking
Healthcareबीमारी के जोखिम का अनुमान (शोध/सहायता के रूप में)
MarketingCampaign response और customer segmentation
Demand Planningबिक्री और stock का अनुमान
Data Science CompetitionsTabular data की कई competitions में लोकप्रिय विकल्प
कब सबसे अच्छा नहीं? Images, audio और लंबे text जैसे unstructured data के लिए आम तौर पर deep learning ज्यादा उपयुक्त रहती है। बहुत छोटे data पर सरल models भी अक्सर काफी होते हैं। हमेशा simple baseline से तुलना करें। Data अगर database में है, तो उसे पढ़ना सीखने के लिए MySQL Introduction in Hindi देखें।

Common Mistakes

❌ 1. सिर्फ train accuracy देखना

Train accuracy 100% हो सकती है, फिर भी model नए data पर कमज़ोर हो सकता है।

✅ सही तरीका

हमेशा अलग test set या cross-validation से जाँचें, और train व test accuracy की तुलना करें।

❌ 2. बहुत ज्यादा trees या बहुत गहरे trees बिना जाँच के

ज्यादा n_estimators और बड़ा max_depth/num_leaves overfitting बढ़ा सकते हैं।

✅ सही तरीका

छोटे मानों से शुरू करें, validation से जाँचें और early stopping इस्तेमाल करें।

❌ 3. LightGBM में छोटे data पर बड़ा num_leaves

Leaf-wise growth में छोटे data पर बहुत ज्यादा leaves से overfitting आसानी से हो सकती है।

✅ सही तरीका

num_leaves को सीमित रखें और max_depth, min_child_samples जैसे parameters से नियंत्रण करें।

❌ 4. सिर्फ accuracy पर निर्भर रहना

Imbalanced data में accuracy गुमराह कर सकती है।

✅ सही तरीका

Precision, recall और F1-score भी देखें, और confusion matrix से गलतियों का प्रकार समझें।

❌ 5. Test data से preprocessing या tuning करना (data leakage)

अगर आप test data की जानकारी से features बनाएँ या parameters चुनें, तो test नतीजा असलियत से बेहतर दिखेगा।

✅ सही तरीका

Tuning के लिए cross-validation या अलग validation set इस्तेमाल करें, और test set को सबसे अंत में सिर्फ एक बार देखें।

❌ 6. Libraries के versions और parameter नामों में उलझना

XGBoost में max_depth मुख्य है और LightGBM में num_leaves। Default values और कुछ syntax versions के साथ बदलते हैं।

✅ सही तरीका

अपने installed version की official documentation देखें और __version__ print करके version नोट रखें।

Quick Exercise 🧠

LightGBM के default tree growth तरीके को क्या कहते हैं?

A) Level-wise growth
B) Leaf-wise (best-first) growth
C) Random growth

सही उत्तर: B — Leaf-wise (best-first) growth

Practice Challenge

VS Code में boosting_practice.py नाम की file बनाएँ और नीचे के tasks पूरे करें।

  1. pip install xgboost lightgbm scikit-learn चलाकर तीनों libraries के versions print करें।
  2. load_breast_cancer का data लें और train_test_split (test_size=0.2, random_state=42) से split करें।
  3. XGBoost का XGBClassifier train करें और test accuracy print करें।
  4. LightGBM का LGBMClassifier train करें और test accuracy print करें।
  5. दोनों की accuracy की तुलना एक छोटी table या print से करें।
  6. n_estimators को 10, 50, 100, 300 पर बदलकर train और test accuracy print करें।
  7. learning_rate को 0.01, 0.1, 0.5 पर बदलकर नतीजे देखें।
  8. XGBoost में max_depth और LightGBM में num_leaves बदलकर overfitting के संकेत ढूँढें (train बनाम test accuracy)।
  9. cross_val_score (cv=5) से दोनों models का औसत score निकालें।
  10. Bonus: feature_importances_ से सबसे जरूरी 5 features print करें और comment में लिखें कि आपको क्या दिखा।

Quick Revision

Conceptमतलब
Ensemble Learningकई models को मिलाकर बेहतर फैसला लेना।
BaggingTrees अलग-अलग और एक साथ बनते हैं (जैसे Random Forest)।
BoostingTrees एक के बाद एक बनते हैं, हर नया tree पिछली गलती सुधारता है।
Gradient BoostingLoss घटाने के लिए residuals पर trees जोड़ते जाना।
XGBoostRegularization और मज़बूती वाली popular boosting library।
LightGBMतेज़ और हल्की boosting library (histogram + leaf-wise)।
Histogram-based learningContinuous values को bins में बाँटकर तेज़ split खोजना।
Leaf-wise growthउस leaf को split करना जिससे loss सबसे ज्यादा घटे।
Train-Test SplitData को सीखने और जाँच के हिस्सों में बाँटना।
Accuracyसही अनुमानों का अनुपात।
OverfittingTrain पर बहुत अच्छा, test पर कमज़ोर।
Cross-Validationकई folds पर जाँचकर औसत नतीजा निकालना।

FAQ — XGBoost और LightGBM

1. Ensemble Learning क्या है?

Ensemble Learning में एक अकेले model की जगह कई models को मिलाकर फैसला लिया जाता है। इसका लक्ष्य किसी एक model से बेहतर और ज्यादा स्थिर नतीजे पाना है। Bagging और Boosting इसके दो आम तरीके हैं।

2. Gradient Boosting क्या है?

Gradient Boosting एक boosting तरीका है जिसमें छोटे decision trees एक के बाद एक जोड़े जाते हैं और हर नया tree पिछले model की गलतियों (residuals) को घटाने की कोशिश करता है। सभी trees के योगदान को जोड़कर अंतिम prediction बनता है।

3. Bagging और Boosting में क्या अंतर है?

Bagging में कई models अलग-अलग data के हिस्सों पर एक साथ बनते हैं और उनके जवाब मिला दिए जाते हैं (जैसे Random Forest)। Boosting में models एक क्रम में बनते हैं और हर नया model पिछले की गलतियों पर ध्यान देता है (जैसे XGBoost और LightGBM)।

4. XGBoost क्या है?

XGBoost (eXtreme Gradient Boosting) एक popular open-source gradient boosting library है, जो decision trees पर आधारित है। इसमें regularization, missing values का संचालन और scikit-learn जैसा interface (XGBClassifier) मिलता है।

5. LightGBM क्या है?

LightGBM Microsoft द्वारा विकसित gradient boosting framework है, जो तेज़ training और कम memory उपयोग के लिए जाना जाता है। यह histogram-based learning और leaf-wise tree growth का इस्तेमाल करता है, और scikit-learn style interface (LGBMClassifier) देता है।

6. XGBoost और LightGBM में मुख्य अंतर क्या हैं?

Default रूप से XGBoost level-wise (depthwise) trees बढ़ाता है और max_depth मुख्य complexity parameter है, जबकि LightGBM leaf-wise trees बढ़ाता है और num_leaves मुख्य parameter है। दोनों histogram-based तरीके इस्तेमाल कर सकते हैं। Default values versions के साथ बदल सकती हैं।

7. XGBoost और LightGBM में कौन-सा बेहतर है?

कोई एक हमेशा बेहतर नहीं होता। यह data और problem पर निर्भर करता है। अपने data पर दोनों को cross-validation से आज़माकर तुलना करना सबसे अच्छा तरीका है।

8. XGBoost और LightGBM कैसे install करें?

Terminal में pip install xgboost lightgbm scikit-learn चलाएँ। फिर import xgboost और import lightgbm से जाँच लें और __version__ print करके versions देख लें।

9. Histogram-based learning क्या है?

इसमें continuous feature values को सीमित संख्या के bins में बाँट दिया जाता है और split इन्हीं bins की सीमाओं पर खोजा जाता है। इससे training तेज़ होती है और memory कम लगती है।

10. Leaf-wise tree growth क्या है?

Leaf-wise (best-first) growth में हर बार उस leaf को split किया जाता है जिससे loss सबसे ज्यादा घटे। इससे tree असंतुलित हो सकता है। छोटे data पर इसमें overfitting का खतरा ज्यादा होता है, इसलिए num_leaves और max_depth से नियंत्रण रखा जाता है।

11. learning_rate, n_estimators और max_depth क्या करते हैं?

n_estimators trees की कुल संख्या है, learning_rate बताता है कि हर नया tree कितना योगदान दे, और max_depth हर tree की अधिकतम गहराई तय करता है। learning_rate घटाने पर आम तौर पर n_estimators बढ़ाने पड़ते हैं।

12. Overfitting क्या है और उसे कैसे घटाएँ?

Overfitting में model training data को रट लेता है और नए data पर खराब चलता है। इसे घटाने के लिए tree की गहराई या leaves सीमित करें, learning_rate और n_estimators संतुलित रखें, subsample और colsample_bytree इस्तेमाल करें, regularization बढ़ाएँ और early stopping का उपयोग करें।

13. Cross-validation क्या है?

Cross-validation में data को कई folds में बाँटा जाता है। हर बार एक fold test के लिए और बाकी train के लिए इस्तेमाल होता है, और नतीजों का औसत लिया जाता है। इससे सिर्फ एक train-test split की तुलना में ज्यादा भरोसेमंद अनुमान मिलता है।

14. क्या XGBoost और LightGBM में features की scaling जरूरी है?

आम तौर पर नहीं। ये decision trees पर आधारित हैं, इसलिए StandardScaler जैसी scaling की उतनी जरूरत नहीं पड़ती जितनी linear models या neural networks में पड़ती है।

Summary

XGBoost और LightGBM = Gradient Boosting की दो लोकप्रिय Python libraries, जो कई छोटे decision trees को एक के बाद एक जोड़कर मज़बूत model बनाती हैं।

इस lesson में आपने Ensemble Learning और Gradient Boosting का विचार, decision trees का मिलकर काम करना, XGBoost और LightGBM की पहचान और अंतर, histogram-based learning, leaf-wise tree growth, installation, classification का पूरा workflow (train-test split, training, accuracy), जरूरी hyperparameters (learning rate, max depth, n_estimators), overfitting, cross-validation और real-world उपयोग समझे।

अब Practice Challenge पूरा करें और दोनों libraries को अपने data पर आज़माएँ। आगे के lessons में hyperparameter tuning, imbalanced data और regression पर बढ़ सकते हैं।

Related Articles — Python Hindii

🧑‍💻 Python Coding Lab

Python code likho, run karo aur practice karo — directly browser mein.