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

Statsmodels in Hindi: OLS Regression, summary() और p-value आसान भाषा में

Statsmodels in Hindi: OLS Regression, summary() और p-value आसान भाषा में

Data analysis में अक्सर सिर्फ "अनुमान" काफी नहीं होता। आपको यह भी बताना पड़ता है कि कोई variable सच में असर डाल रहा है या नहीं, और नतीजे पर कितना भरोसा किया जा सकता है। जैसे: क्या पढ़ाई के घंटे बढ़ाने से score सच में बढ़ता है? क्या marketing खर्च का बिक्री पर असर है? ऐसे सवालों के लिए Python की Statsmodels library बनी है।

इस guide में आप शुरू से आगे तक चलेंगे: Statsmodels क्या है, install कैसे करें, दो APIs (array और formula), data तैयार करना, OLS regression, summary() पढ़ना, p-value और confidence interval, R-squared, model की जाँच (residuals, VIF, Breusch-Pagan), predictions, Logit और GLM, time series (ARIMA), hypothesis tests और आखिर में एक mini-project व practice questions।

इस lesson के लिए Python की basics और pandas DataFrame की बुनियादी समझ काफी है। अगर Python नई है तो पहले Python Install कैसे करें और Python Tutorial in Hindi देखें। Data analysis की बड़ी तस्वीर के लिए Data Analyst Tutorial in Hindi और Python libraries की झलक के लिए Top Python Libraries for Machine Learning & AI पढ़ सकते हैं। इसके सारे examples अपने system में (VS Code या terminal में) चलाएँ, क्योंकि इनके लिए pandas और statsmodels install होने चाहिए।

📌 इस Lesson का Scope: यह lesson Complete Python Course 2026 by Python Hindii की data analysis learning series का हिस्सा है और Statsmodels का Beginner-to-Intermediate guide है। इसमें pandas सिर्फ उतना समझाया गया है जितना Statsmodels के लिए जरूरी है। Pandas, scikit-learn और गहरे Machine Learning algorithms अलग lessons में आएँगे। नीचे के सारे outputs असली code चलाकर निकाले गए हैं।

इस Guide से आप क्या सीखेंगे?

#लक्ष्यमतलब
1Install और verifyStatsmodels set up करना और जाँचना कि चल रहा है।
2API चुननाArray API या formula API में से सही का इस्तेमाल।
3OLS modelsm.OLS से linear regression बनाना।
4summary() पढ़नाCoefficients, p-values और R-squared समझना।
5Assumptions जाँचनाResidual plots और diagnostic tests।
6OLS से आगेLogit, GLM, ARIMA और hypothesis tests।
असली दुनिया में कहाँ? Statsmodels तब काम आता है जब आपको नतीजे सिर्फ predict नहीं, समझाने भी हों: असर कितना बड़ा है, अनिश्चितता कितनी है, और test क्या कहता है। Pricing, marketing खर्च और health studies में यही workflow चलता है।

Statsmodels Roadmap

1. Setup → Install, import, verify 2. Data → pandas, add_constant 3. OLS model → Fit और summary() पढ़ना 4. Diagnostics → Residuals, VIF, tests 5. Other models → Logit, GLM, ARIMA 6. Practice → Project और exercises

Statsmodels क्या है?

Statsmodels statistical modeling की Python library है। यह models estimate करती है, आपके data के बारे में ideas को test करती है और बताती है कि नतीजों पर कितना भरोसा किया जा सकता है।

यह क्यों जरूरी है?

  • Standard errors, p-values और confidence intervals वाली detailed report देती है।
  • "क्या यह variable सच में मायने रखता है?" का जवाब देती है, सिर्फ "prediction क्या है?" का नहीं।
  • NumPy arrays और pandas DataFrames के साथ स्वाभाविक रूप से चलती है।
Data (DataFrame) → Model (OLS, Logit...) → fit() → Results (summary, predict)

Statsmodels vs scikit-learn

सवालStatsmodelsscikit-learn
मुख्य लक्ष्यसमझाना और test करनाPrediction
Detailed summary reportBuilt-inBuilt-in नहीं
p-values और confidence intervalsहाँDefault में नहीं मिलते
Constant (intercept)खुद जोड़ना पड़ता है (arrays में)अपने-आप जुड़ता है
याद रखें: दोनों libraries एक-दूसरे की पूरक हैं। जहाँ interpretation मायने रखता है वहाँ Statsmodels और जहाँ सिर्फ prediction चाहिए वहाँ scikit-learn चुनें। Statsmodels = models + statistical evidence। AI और ML के बड़े संदर्भ के लिए AI vs ML vs DL पढ़ें।

Installation और Setup

Statsmodels को Python 3 के साथ NumPy, SciPy, pandas और patsy चाहिए। pip से install करने पर ये dependencies अपने-आप आ जाती हैं। कौन से version अभी supported हैं, यह हमेशा official documentation में देख लें।

Terminal खोलें → pip install → Python खोलें → import करके जाँचें
Install करना
pip install statsmodels # साथ में आम तौर पर लगने वाली libraries (optional) pip install pandas matplotlib
Install की जाँच
import statsmodels import statsmodels.api as sm print(statsmodels.__version__)

Terminal Output: आपके system का version number आएगा (जैसे 0.14.x या उससे नया)। Version अलग हो सकता है, इसमें चिंता की बात नहीं।

⚠️ Common Mistake

एक Python में install करना और दूसरे Python से चलाना। अगर ModuleNotFoundError दिखे, तो यह चलाएँ: python -m pip install statsmodels। हर project के लिए अलग virtual environment बनाना अच्छा तरीका है, ताकि versions आपस में न उलझें।

दो APIs: Arrays और Formulas

Statsmodels में एक ही model बनाने के दो तरीके हैं। जो आपके data और आदत के हिसाब से ठीक लगे, वही चुनें।

बातArray API (statsmodels.api as sm)Formula API (statsmodels.formula.api as smf)
Codesm.OLS(y, X)smf.ols("y ~ x1 + x2", data=df)
InputArrays देते हैं: पहले y, फिर XColumn names से formula लिखते हैं
Constantखुद जोड़ना पड़ता है (add_constant)अपने-आप जुड़ता है
किसके लिए अच्छाMatrices और loopsCategories C(...) के साथ
आम imports
import numpy as np import pandas as pd import statsmodels.api as sm import statsmodels.formula.api as smf
याद रखें: Array API में क्रम sm.OLS(y, X) है, यानी target पहले आता है। इन्हें उलट देना सबसे आम गलती है।

Data तैयार करना

Models को numbers चाहिए। Fit करने से पहले data को pandas DataFrame में रखें, target (y) को features (X) से अलग करें और missing values संभालें।

Example 1 — छोटा dataset और y, X बनाना
import pandas as pd import statsmodels.api as sm df = pd.DataFrame({ "hours": [1, 2, 3, 4, 5, 6, 7, 8], "score": [52, 55, 61, 64, 70, 71, 78, 83], }) print(df.head(3)) y = df["score"] # target X = df[["hours"]] # feature(s) X = sm.add_constant(X) # intercept column जोड़ता है print(X.head(3))

Terminal Output:

hours score 0 1 52 1 2 55 2 3 61 const hours 0 1.0 1 1 1.0 2 2 1.0 3

add_constant ने const नाम का नया column जोड़ा है, जिसमें सारी values 1.0 हैं।

add_constant क्यों जरूरी है?

Model y = b0 + b1*x में b0 (intercept) निकालने के लिए 1 वाला एक column चाहिए। इसके बिना line को जबरदस्ती origin से गुजरना पड़ता है।

⚠️ Common Mistake

X में missing values या text columns छोड़ देना। Fit से पहले missing values को हटाएँ या भरें और categories को numbers में बदलें।

OLS का विचार

OLS यानी Ordinary Least Squares। यह वह सीधी line ढूँढता है जिससे data और line के बीच की squared दूरियों का कुल जोड़ जितना हो सके उतना कम हो।

y = b0 + b1·x + error लक्ष्य: (y - predicted y)² का जोड़ सबसे कम करना
शब्दमतलब
Intercept (b0)जब x = 0 हो तब y का अनुमान।
Slope (b1)x में एक इकाई बढ़ने पर y में बदलाव।
Residualअसली y माइनस अनुमानित y।
लक्ष्यSquared residuals का जोड़ कम से कम करना।
उदाहरण से समझें: सोचिए बिंदुओं के बादल के बीच से एक सीधा scale निकालना है। OLS scale को वहाँ रखता है जहाँ कुल squared दूरी सबसे कम हो। Key takeaway: Residuals को square करने से धनात्मक और ऋणात्मक गलतियाँ आपस में कटती नहीं और बड़ी गलतियों को ज्यादा सजा मिलती है।

पहला OLS Model

नीचे एक पूरा program है: यह data बनाता है, model fit करता है और पूरी report print करता है। इसके लिए pandas और statsmodels install होने चाहिए।

Example 2 — Complete OLS program
import pandas as pd import statsmodels.api as sm df = pd.DataFrame({ "hours": [1, 2, 3, 4, 5, 6, 7, 8], "score": [52, 55, 61, 64, 70, 71, 78, 83], }) y = df["score"] X = sm.add_constant(df[["hours"]]) model = sm.OLS(y, X) # 1. model define करें results = model.fit() # 2. estimate करें print(results.summary()) # 3. report पढ़ें

Terminal Output:

OLS Regression Results ============================================================================== Dep. Variable: score R-squared: 0.988 Model: OLS Adj. R-squared: 0.987 Method: Least Squares F-statistic: 514.3 Date: Tue, 10 Nov 2026 Prob (F-statistic): 4.81e-07 Time: 12:04:47 Log-Likelihood: -11.999 No. Observations: 8 AIC: 28.00 Df Residuals: 6 BIC: 28.16 Df Model: 1 Covariance Type: nonrobust ============================================================================== coef std err t P>|t| [0.025 0.975] ------------------------------------------------------------------------------ const 47.0357 0.976 48.215 0.000 44.649 49.423 hours 4.3810 0.193 22.677 0.000 3.908 4.854 ============================================================================== Omnibus: 3.728 Durbin-Watson: 2.949 Prob(Omnibus): 0.155 Jarque-Bera (JB): 1.405 Skew: -1.025 Prob(JB): 0.495 Kurtosis: 2.902 Cond. No. 11.5 ============================================================================== Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified.

Output में Date और Time की lines आपके system के हिसाब से अलग होंगी।

Define: sm.OLS(y, X) → Fit: model.fit() → Inspect: summary()

results के काम के attributes

Attributeमतलब
results.paramsEstimated coefficients
results.pvaluesहर coefficient का p-value
results.rsquaredFit का R-squared
results.residResiduals (असली माइनस fitted)

summary() कैसे पढ़ें?

Summary के तीन हिस्से होते हैं। देखने की जगह पता हो तो report आसान लगने लगती है।

हिस्साइसमें क्या हैकब देखें
ऊपर: Model overviewDep. Variable, Model, Method, No. Observations, R-squared, Adj. R-squared, F-statistic, Prob (F-statistic), AIC, BICcoefficient table के बाद R-squared देखें।
बीच: Coefficient tablecoef, std err, t, P>|t|, [0.025 0.975]। हर variable की एक row, const समेत।यहीं से शुरू करें। देखें कि P>|t| छोटा है या नहीं और confidence interval में 0 आता है या नहीं।
नीचे: DiagnosticsOmnibus, Durbin-Watson, Jarque-Bera, Skew, Kurtosis, Condition NumberResidual की जाँच आगे वाले हिस्से में।
पढ़ने का क्रम: 1. Coef table → 2. P-values → 3. R-squared → 4. Diagnostics
ध्यान दें: Summary का ठीक layout Statsmodels के versions के बीच थोड़ा अलग हो सकता है। तीन हिस्से वही रहते हैं।

Coefficients, p-values और Intervals

Columnयह क्या बताता है
coefअनुमानित असर: slope या intercept
std errअनुमान की अनिश्चितता; जितना छोटा, उतना सटीक
tcoef को std err से भाग देने पर
P>|t|p-value: अगर असली coefficient शून्य होता तो यह नतीजा कितना चौंकाने वाला होता
[0.025 0.975]Coefficient का 95% confidence interval

Slope को कैसे समझें?

हमारे example में hours का slope 4.381 आया। इसका मतलब: हर एक अतिरिक्त घंटे की पढ़ाई, बाकी चीज़ें समान रखने पर, लगभग 4.4 अंक ज्यादा score से जुड़ी है।

p-value का सही इस्तेमाल

  • छोटा p-value (आम तौर पर 0.05 से कम) "कोई असर नहीं" के खिलाफ सबूत है।
  • जिस confidence interval में 0 आता हो, उसका मतलब है कि असर शून्य होना भी संभव है।
  • Statistical significance का मतलब यह नहीं कि असर बड़ा या महत्वपूर्ण है।
Example 3 — Code में इन्हें निकालना

(यहाँ df, y, X और results पिछले example वाले हैं।)

print(results.params) # coefficients print(results.pvalues) # p-values print(results.conf_int()) # 95% intervals

Terminal Output:

const 47.035714 hours 4.380952 dtype: float64 const 5.336555e-09 hours 4.814029e-07 dtype: float64 0 1 const 44.648661 49.422767 hours 3.908245 4.853659

p-value 4.81e-07 का मतलब है 0.000000481, यानी बहुत छोटा।

⚠️ Common Mistake

Association (साथ-साथ बदलना) को कारण (cause) का सबूत मान लेना। Regression बताता है कि दो चीज़ें साथ में बदलती हैं, यह नहीं कि एक दूसरी का कारण है।

Fit Statistics: Model कितना अच्छा है?

Measureमतलब
R-squaredy के बदलाव का कितना हिस्सा model समझा पाता है (0 से 1)। जैसे 0.80 का मतलब 80%।
Adj. R-squaredFeatures की संख्या के हिसाब से सुधारा हुआ R-squared। Models की तुलना के लिए बेहतर।
F-statisticजाँचता है कि क्या पूरा model सिर्फ intercept वाले model से ज्यादा समझा रहा है। Prob (F-statistic) के साथ पढ़ें।
AIC और BICएक ही data पर models की तुलना। जितना कम, उतना बेहतर। BIC जटिलता पर ज्यादा सज़ा लगाता है।
Example 4 — Fit statistics code में
print(results.rsquared) print(results.rsquared_adj) print(results.fvalue, results.f_pvalue) print(results.aic, results.bic)

Terminal Output:

0.988467490000292 0.9865454050003406 514.2683544303793 4.81402926071499e-07 27.997213370778113 28.156096454137785
⚠️ Common Mistake

ऊँचे R-squared के पीछे भागना। Features जोड़ने से यह हमेशा बढ़ता है, बेकार features से भी। Models की तुलना adjusted R-squared, AIC या BIC से करें, साधारण R-squared से नहीं।

Formula API

Formula API में आप DataFrame के column names इस्तेमाल करके model को एक छोटी string में लिख देते हैं। पर्दे के पीछे patsy matrices बनाता है और intercept जोड़ता है।

Example 5 — Formula से वही model
import statsmodels.formula.api as smf results = smf.ols("score ~ hours", data=df).fit() print(results.params)

Terminal Output:

Intercept 47.035714 hours 4.380952 dtype: float64

Intercept को यहाँ Intercept नाम मिला है और नतीजे Array API वाले जैसे ही हैं।

Formula cheat sheet

Formulaमतलब
y ~ x1 + x2y को x1 और x2 से समझाना (intercept जुड़ता है)
y ~ x1 + x2 - 1Intercept हटाना
y ~ x1 * x2x1, x2 और उनका interaction
y ~ C(group)group को category की तरह लेना
y ~ np.log(x)Formula के अंदर ही transformation लगाना
smf.ols("score ~ hours + C(school)", data=df).fit()
याद रखें: C(school) 0/1 वाले dummy columns बनाता है और एक category को baseline (आधार) के रूप में छोड़ देता है।

Predictions करना

Model fit होने के बाद आप नए x values पर y का अनुमान लगा सकते हैं। Statsmodels हर अनुमान के आसपास की अनिश्चितता भी बता सकता है।

Example 6 — नए values का अनुमान
import pandas as pd new_X = pd.DataFrame({"hours": [9, 10]}) new_X = sm.add_constant(new_X, has_constant="add") pred = results.predict(new_X) print(pred)

Terminal Output:

0 86.464286 1 90.845238 dtype: float64

9 और 10 घंटे के लिए अनुमानित score क्रमशः लगभग 86.5 और 90.8 हैं।

Example 7 — Intervals के साथ
frame = results.get_prediction(new_X).summary_frame(alpha=0.05) print(frame.round(2).to_string())

Terminal Output:

0 86.464286 1 90.845238 dtype: float64 mean mean_se mean_ci_lower mean_ci_upper obs_ci_lower obs_ci_upper 0 86.46 0.98 84.08 88.85 82.58 90.35 1 90.85 1.15 88.03 93.66 86.68 95.01
Columnमतलब
meanअनुमानित मान
mean_ci_lower / upperऔसत response का interval
obs_ci_lower / upperएक नई observation का interval (ज्यादा चौड़ा)
⚠️ Common Mistake और Pro Tip

नए data पर add_constant लगाना भूल जाना। Columns training वाले X से मेल खाने चाहिए। और training range से बहुत बाहर के values का अनुमान लगाने में सावधानी रखें।

Assumptions और Residuals

OLS के नतीजे तभी भरोसे लायक हैं जब उसकी assumptions ठीक-ठाक पूरी हों। Residuals (गलतियाँ) बताते हैं कि वे पूरी हो रही हैं या नहीं।

Assumptionमतलब
1. Linearityx और y का रिश्ता लगभग सीधी line जैसा हो।
2. Independent errorsएक residual अगले का अनुमान न दे। Time data में अक्सर दिक्कत आती है।
3. Constant varianceFitted values के साथ residuals का फैलाव लगभग एक जैसा रहे (homoskedasticity)।
4. Normal residualsResiduals लगभग घंटी के आकार के हों। छोटे samples में ज्यादा मायने रखता है।
Example 8 — Residuals बनाम Fitted values

(यहाँ भी पिछले example वाला results इस्तेमाल हुआ है।)

import matplotlib.pyplot as plt plt.scatter(results.fittedvalues, results.resid) plt.axhline(0, color="red") plt.xlabel("Fitted values") plt.ylabel("Residuals") plt.show() # Normality देखने के लिए: sm.qqplot(results.resid, line="s") plt.show()

Code चलाने पर plot की window खुलेगी। क्या देखें: शून्य के आसपास बिखरे हुए बादल जैसे बिंदु अच्छे संकेत हैं। कोई curve या फनल (चौड़ी होती हुई) आकृति दिखे तो समस्या है।

⚠️ Common Mistake

Residuals देखे बिना सिर्फ p-values पर भरोसा कर लेना।

VIF और Heteroskedasticity Tests

Multicollinearity और VIF

जब features आपस में बहुत ज्यादा जुड़े हों, तो coefficients अस्थिर हो जाते हैं। Variance Inflation Factor (VIF) इसे नापता है। आम नियम के अनुसार लगभग 5 से 10 से ऊपर के मान को चेतावनी माना जाता है।

Heteroskedasticity: Breusch-Pagan test

यह जाँचता है कि residuals का फैलाव features के साथ बदलता है या नहीं। छोटा p-value बताता है कि variance स्थिर नहीं है।

Example 9 — VIF और Breusch-Pagan
import pandas as pd import statsmodels.api as sm from statsmodels.stats.outliers_influence import variance_inflation_factor from statsmodels.stats.diagnostic import het_breuschpagan df = pd.DataFrame({ "score": [52, 55, 61, 64, 70, 71, 78, 83, 60, 66, 74, 80], "hours": [1, 2, 3, 4, 5, 6, 7, 8, 2, 4, 6, 7], "sleep": [6, 7, 5, 6, 8, 7, 6, 8, 5, 7, 8, 7], }) y = df["score"] X = sm.add_constant(df[["hours", "sleep"]]) results = sm.OLS(y, X).fit() # VIF: हर column के लिए vif = [variance_inflation_factor(X.values, i) for i in range(X.shape[1])] print([round(float(v), 2) for v in vif]) # Breusch-Pagan test lm, lm_p, f, f_p = het_breuschpagan(results.resid, X) print(round(lm_p, 4))

Terminal Output:

[1.0, 1.48, 1.48] 0.6151

दोनों features (hours, sleep) के VIF छोटे हैं और Breusch-Pagan का p-value बड़ा है, इसलिए यहाँ इन दोनों से कोई चेतावनी नहीं मिलती। VIF की list में पहला मान const column का है, उसे features की तरह न पढ़ें।

अगर समस्या दिखे तो?

समस्यासंभावित उपाय
ऊँचा VIFजुड़े हुए features को हटाएँ या मिलाएँ।
Variance स्थिर नहींy को transform करें, या robust errors इस्तेमाल करें: fit(cov_type="HC3")
मुड़े हुए residualsवर्ग (squared) वाला term जोड़ें या किसी feature को transform करें।
महत्वपूर्ण: इन सीमाओं (thresholds) को मार्गदर्शक समझें, कानून नहीं।

Logit: हाँ/ना वाले नतीजे का model

जब target सिर्फ 0 या 1 हो (जैसे pass या fail), तब सीधी line वाला OLS गलत औज़ार है। Logistic regression class 1 की probability को S-आकार के curve से model करता है। इसका output हमेशा 0 और 1 के बीच रहता है, इसलिए इसे probability की तरह पढ़ा जा सकता है।

Example 10 — Logit, probabilities और odds ratio
import pandas as pd import numpy as np import statsmodels.api as sm df = pd.DataFrame({ "hours": [1, 2, 3, 4, 5, 6, 7, 8], "passed": [0, 0, 0, 1, 0, 1, 1, 1], }) y = df["passed"] # 0 या 1 X = sm.add_constant(df[["hours"]]) results = sm.Logit(y, X).fit(disp=0) probs = results.predict(X) # 0 से 1 के बीच labels = (probs >= 0.5).astype(int) # class decision print(probs.round(3).tolist()) print(labels.tolist()) odds_ratios = np.exp(results.params) # log-odds से odds ratio print(odds_ratios.round(3))

Terminal Output:

[0.011, 0.039, 0.127, 0.345, 0.655, 0.873, 0.961, 0.989] [0, 0, 0, 0, 1, 1, 1, 1] const 0.003 hours 3.605 dtype: float64
⚠️ Common Mistake

0.5 को ही एकमात्र cut-off मान लेना। अपनी समस्या के हिसाब से cut-off चुनें।

Odds Ratios और GLM

Logit के coefficients log-odds में होते हैं, जिन्हें पढ़ना कठिन है। उन्हें np.exp() से exponentiate करने पर odds ratio मिलता है।

Odds ratioमतलब
1 से ऊपरClass 1 की odds ज्यादा
1 के बराबरकोई असर नहीं
1 से नीचेClass 1 की odds कम

ऊपर के example में hours का odds ratio लगभग 3.6 आया, यानी हर अतिरिक्त घंटा pass होने की odds को लगभग 3.6 गुना कर देता है।

GLM: कई तरह के नतीजों के लिए एक ढाँचा

Generalized Linear Model (GLM) एक distribution family और एक link function को मिलाता है। Family अपने target के हिसाब से चुनें:

Target का प्रकारFamily
Continuous, normal errorssm.families.Gaussian()
Yes / Nosm.families.Binomial()
Counts (0, 1, 2, ...)sm.families.Poisson()
Example 11 — Poisson GLM (counts के लिए)
import pandas as pd import statsmodels.api as sm df = pd.DataFrame({ "temp": [20, 22, 24, 26, 28, 30, 32, 34], "visits": [3, 4, 4, 6, 7, 9, 12, 14], }) y = df["visits"] # counts X = sm.add_constant(df[["temp"]]) glm = sm.GLM(y, X, family=sm.families.Poisson()) results = glm.fit() print(results.params.round(4))

Terminal Output:

const -1.1885 temp 0.1132 dtype: float64

रोज़ के visits जैसी गिनती वाली चीज़ों के लिए Poisson सही रहता है।

Time Series की बुनियाद

Statsmodels में time series के लिए tsa module है। समय के क्रम में रखे data में trend, seasonality और याददाश्त होती है, इसलिए rows एक-दूसरे से स्वतंत्र नहीं होतीं। यह हिस्सा सबसे आम औज़ारों का छोटा परिचय है।

Series plot करें → Decompose करें → Stationarity जाँचें → ARIMA fit करें → Forecast
Toolकाम
seasonal_decomposeTrend, seasonal और बाकी हिस्से में बाँटना
adfullerAugmented Dickey-Fuller stationarity test
ARIMAAR, differencing (I) और MA terms वाला model
plot_acf / plot_pacfAutocorrelation देखकर orders चुनना
Example 12 — ARIMA (एक नकली monthly series पर)
import pandas as pd from statsmodels.tsa.arima.model import ARIMA from statsmodels.tsa.stattools import adfuller # series: date से indexed एक pandas Series (नकली monthly data) idx = pd.date_range("2024-01-01", periods=24, freq="MS") series = pd.Series( [112, 118, 132, 129, 121, 135, 148, 148, 136, 119, 104, 118, 115, 126, 141, 135, 125, 149, 170, 170, 158, 133, 114, 140], index=idx, ) print("ADF p-value:", round(adfuller(series)[1], 4)) model = ARIMA(series, order=(1, 1, 1)) results = model.fit() forecast = results.forecast(steps=6) print(forecast.round(1))

Terminal Output:

ADF p-value: 0.019 2026-01-01 154.4 2026-02-01 152.3 2026-03-01 152.6 2026-04-01 152.6 2026-05-01 152.6 2026-06-01 152.6 Freq: MS, Name: predicted_mean, dtype: float64

यह series सिर्फ समझाने के लिए बनाई गई है। यहाँ ADF का p-value छोटा (0.019) आया है, यानी इस नकली series को stationary माना जा सकता है। असली काम में अपना date-indexed data लें और d का चुनाव plots व इस तरह की जाँचों के आधार पर करें।

महत्वपूर्ण: order=(p, d, q) में p = autoregressive terms, d = differencing के कदम और q = moving-average terms हैं।

Hypothesis Tests

Statsmodels regression fit किए बिना भी क्लासिक tests सीधे चला सकता है। हर test एक test statistic और एक p-value लौटाता है।

सवालFunction
क्या sample का औसत किसी मान से अलग है?statsmodels.stats.weightstats.ztest
क्या दो groups के औसत अलग हैं?ttest_ind (weightstats)
क्या 3 या ज्यादा groups अलग हैं?anova_lm (stats.anova)
क्या दो proportions अलग हैं?proportions_ztest
Example 13 — t-test और ANOVA
from statsmodels.stats.weightstats import ttest_ind from statsmodels.stats.anova import anova_lm import statsmodels.formula.api as smf import pandas as pd # Do group means group_a = [78, 82, 75, 88, 91, 69, 84] group_b = [70, 65, 72, 68, 74, 60, 71] t_stat, p_value, df_used = ttest_ind(group_a, group_b) print("t-test p-value:", round(p_value, 5)) # ANOVA (3 groups) df = pd.DataFrame({ "score": [78, 82, 75, 70, 65, 72, 88, 91, 85], "school": ["A"] * 3 + ["B"] * 3 + ["C"] * 3, }) fit = smf.ols("score ~ C(school)", data=df).fit() print(anova_lm(fit))

Terminal Output:

t-test p-value: 0.00325 df sum_sq mean_sq F PR(>F) C(school) 2.0 541.555556 270.777778 23.660194 0.001425 Residual 6.0 68.666667 11.444444 NaN NaN

दोनों p-values छोटे हैं, यानी groups के औसत में अंतर का सबूत मिलता है।

याद रखें: Null hypothesis आम तौर पर "कोई अंतर नहीं" कहती है। छोटा p-value उसके खिलाफ सबूत है।

Common Mistakes और Troubleshooting

लक्षणसंभावित कारणहल
Results में intercept नहींadd_constant भूल गए (array API)X = sm.add_constant(X)
dtype object वाली ValueErrorX में text columnspd.get_dummies या C(...)
Results में NaNData में missing valuesdropna() या values भरें
Logit ठीक से converge नहीं हो रहाSeparation या unscaled dataFeatures को scale करें; data जाँचें
y, X का क्रम गलतsm.OLS(X, y) लिखाsm.OLS(y, X)
नए data पर predict failColumns training X से अलगColumns मिलाएँ और constant जोड़ें
❌ Fit से पहले summary() call करना

सिर्फ fit किए गए results object में summary() होता है, model object में नहीं।

❌ Correlation को causation लिख देना

अपने निष्कर्षों में यह भेद हमेशा रखें।

Debugging Challenge: 3 bugs ढूँढें

नीचे के code में क्या गलत है?
import statsmodels.api as sm y = df["score"] X = df[["hours"]] results = sm.OLS(X, y).fit() print(results.summary)

क्रम, constant और summary call पर ध्यान दें। (df पिछले example वाला है।)

जवाब: (1) sm.OLS(X, y) की जगह sm.OLS(y, X) होना चाहिए। (2) add_constant नहीं लगा। (3) summary को summary() की तरह call करना है। गलत code में कोई error नहीं आता, पर नतीजे गलत या अधूरे आते हैं, और यही इसे खतरनाक बनाता है। सही code:

import statsmodels.api as sm y = df["score"] X = sm.add_constant(df[["hours"]]) # 2. constant जोड़ा results = sm.OLS(y, X).fit() # 1. order सही: (y, X) print(results.summary()) # 3. () के साथ call

(यह वही summary है जो Example 2 में दिखा था, इसलिए यहाँ दोबारा output दिखाना जरूरी नहीं।)

Mini-Project: Exam Scores को समझाना

लक्ष्य: OLS से समझें कि पढ़ाई के घंटे और नींद के घंटे exam score से कैसे जुड़े हैं, फिर model की जाँच करें। नीचे 12 rows का छोटा dataset बनाया गया है, आप अपना data भी इस्तेमाल कर सकते हैं।

Data load करें → Clean करें → OLS fit करें → Interpret करें → जाँचें
Example 14 — Mini-project
import pandas as pd import statsmodels.formula.api as smf df = pd.DataFrame({ "score": [52, 55, 61, 64, 70, 71, 78, 83, 60, 66, 74, 80], "hours": [1, 2, 3, 4, 5, 6, 7, 8, 2, 4, 6, 7], "sleep": [6, 7, 5, 6, 8, 7, 6, 8, 5, 7, 8, 7], }) df = df.dropna() results = smf.ols("score ~ hours + sleep", data=df).fit() print(results.params.round(3)) print(results.conf_int().round(3)) print("Adj R-squared:", round(results.rsquared_adj, 4)) only_hours = smf.ols("score ~ hours", data=df).fit() print("Adj R-squared (hours only):", round(only_hours.rsquared_adj, 4)) new = pd.DataFrame({"hours": [6], "sleep": [7]}) print(results.predict(new).round(2))

Terminal Output:

Intercept 50.364 hours 4.399 sleep -0.404 dtype: float64 0 1 Intercept 42.642 58.085 hours 3.768 5.029 sleep -1.740 0.933 Adj R-squared: 0.9695 Adj R-squared (hours only): 0.9711 0 73.93 dtype: float64

इन नतीजों में sleep का confidence interval 0 को शामिल करता है (लगभग -1.74 से 0.93), इसलिए 5% स्तर पर sleep का असर पक्का नहीं कहा जा सकता। और hours-only model का adjusted R-squared थोड़ा ज्यादा है, जो बताता है कि sleep जोड़ने से model बेहतर नहीं हुआ। यह नकली, बहुत छोटा data है, इसलिए इससे असली दुनिया का निष्कर्ष न निकालें।

आपके Tasks

  • hours के coefficient को एक वाक्य में समझाएँ।
  • क्या sleep का coefficient 5% स्तर पर significant है? Confidence interval से कारण दें।
  • Adjusted R-squared की तुलना सिर्फ hours वाले model से करें।
  • Residuals बनाम fitted values का plot बनाएँ। कोई pattern दिखता है?
  • 6 घंटे की पढ़ाई और 7 घंटे की नींद वाले student का score predict करें।

Practice Questions

पहले कागज़ पर जवाब लिखें, फिर नीचे के Answer Key से मिलाएँ।

Part A: समझ

  1. Statsmodels और scikit-learn में से कौन सी library मुख्य रूप से explain और test करने के लिए बनी है?
  2. sm.OLS(y, X) में target कौन सा argument है?
  3. सही या गलत: Array API intercept अपने-आप जोड़ देता है।
  4. Residual क्या नापता है?

Part B: Application

  1. Slope का p-value 0.003 है। इसका मतलब है: (a) कोई सबूत नहीं, (b) शून्य असर के खिलाफ मजबूत सबूत, (c) पक्का कारण।
  2. खाली जगह भरें: Models की तुलना के लिए adjusted R-squared, AIC या ______ चुनें।
  3. score को hours और category school से समझाने वाला formula लिखें।
  4. कौन सा function Logit coefficients को odds ratios में बदलता है?

Part C: Problem solving

  1. Residual plot में फनल का आकार दिखा। समस्या का नाम और एक उपाय बताएँ।
  2. एक feature का VIF 15 आया। यह क्या बताता है?
  3. GLM में गिनती वाले data के लिए कौन सी family चलती है?
  4. ऊपर के debugging challenge के 3 bugs ढूँढें।

Answer Key (स्पष्टीकरण के साथ)

#उत्तरक्यों
1Statsmodelsयह reports, tests और intervals देता है।
2y (पहला)क्रम OLS(y, X) है।
3गलतsm.add_constant(X) इस्तेमाल करें।
4असली माइनस अनुमानितयह एक row की model-गलती है।
5(b)छोटा p-value "कोई असर नहीं" के खिलाफ सबूत है, कारण साबित नहीं करता।
6BICAIC या BIC जितना कम, उतना बेहतर।
7score ~ hours + C(school)C() category दर्शाता है।
8np.exp(results.params)Log-odds को exponentiate करने से odds ratio मिलता है।
9Heteroskedasticityy को transform करें या HC3 जैसे robust errors इस्तेमाल करें।
10मजबूत multicollinearityजुड़े हुए features को हटाएँ या मिलाएँ।
11PoissonPoisson गिनती वाले data को model करता है।
12क्रम, constant, summary()OLS(y, X), add_constant और summary() कोष्ठक के साथ।

Quick Exercise 🧠

Array API में sm.OLS(...) के अंदर सही क्रम कौन सा है?

A) sm.OLS(y, X)
B) sm.OLS(X, y)
C) sm.OLS(X)

सही उत्तर: A — पहले target y, फिर features X

Glossary और Knowledge Map

Termमतलब
Coefficientकिसी variable का अनुमानित असर
Residualअसली मान माइनस fitted मान
p-valueअगर null hypothesis सही होती तो इतने (या उससे ज्यादा) चरम नतीजे की संभावना
Confidence intervalParameter के संभावित मानों का दायरा
VIFMulticollinearity का माप
Odds ratioLogit coefficient का exponent
Statsmodels → Setup और APIs | OLS और summary | Diagnostics | Logit, GLM, ARIMA

Quick Revision

Conceptमतलब
StatsmodelsModels + statistical evidence देने वाली Python library।
Array API / Formula APIsm.OLS(y, X) बनाम smf.ols("y ~ x", data=df)
add_constantArray API में intercept के लिए 1 वाला column जोड़ता है।
OLSSquared residuals का जोड़ कम करने वाली सीधी line।
summary()Overview, coefficient table और diagnostics वाली report।
p-valueछोटा हो तो "कोई असर नहीं" के खिलाफ सबूत।
Adj. R-squared, AIC, BICModels की तुलना के बेहतर माप।
VIFFeatures के आपसी जुड़ाव की जाँच।
Logit0/1 target के लिए probability model।
GLMFamily चुनकर कई तरह के target के लिए एक ढाँचा।
ARIMATime series का model, order=(p, d, q)।

FAQ — Statsmodels in Hindi

1. Statsmodels क्या है?

Statsmodels एक Python library है जो statistical models बनाने (estimate करने), statistical tests चलाने और data को explore करने के काम आती है। यह सिर्फ prediction नहीं देती, बल्कि standard errors, p-values और confidence intervals वाली detailed report भी देती है।

2. Statsmodels और scikit-learn में क्या अंतर है?

Statsmodels का मुख्य लक्ष्य नतीजों को समझाना और test करना है, जबकि scikit-learn का मुख्य लक्ष्य prediction है। Statsmodels में detailed summary report, p-values और confidence intervals built-in मिलते हैं। दोनों एक-दूसरे के पूरक हैं, इसलिए जहाँ interpretation जरूरी हो वहाँ Statsmodels चुनें।

3. Statsmodels install कैसे करें?

Terminal में pip install statsmodels चलाएँ। साथ में pip install pandas matplotlib भी कर सकते हैं। Install के बाद Python में import statsmodels चलाकर print(statsmodels.__version__) से जाँच लें। ModuleNotFoundError आए तो python -m pip install statsmodels चलाएँ।

4. Array API और Formula API में क्या फर्क है?

Array API (statsmodels.api as sm) में आप y और X arrays देते हैं और constant खुद जोड़ते हैं। Formula API (statsmodels.formula.api as smf) में आप "score ~ hours" जैसा formula column names के साथ लिखते हैं और intercept अपने-आप जुड़ जाता है।

5. add_constant क्यों जरूरी है?

Model y = b0 + b1*x में b0 (intercept) निकालने के लिए X में 1 वाला एक column चाहिए। Array API में add_constant के बिना line को origin से गुजरने के लिए मजबूर कर दिया जाता है, जिससे नतीजे गलत आ सकते हैं।

6. OLS क्या है?

OLS का मतलब Ordinary Least Squares है। यह वह सीधी line ढूँढता है जिससे data points की squared दूरियों का कुल जोड़ सबसे कम हो।

7. summary() कैसे पढ़ें?

summary() में तीन हिस्से होते हैं: ऊपर model का overview (R-squared, F-statistic, AIC, BIC), बीच में coefficient table (coef, std err, t, P>|t|, confidence interval) और नीचे diagnostics (Omnibus, Durbin-Watson, Jarque-Bera)। पढ़ने का सही क्रम है: पहले coefficient table, फिर p-values, फिर R-squared और आखिर में diagnostics।

8. p-value का क्या मतलब है?

p-value बताती है कि अगर असली coefficient शून्य होता, तो ऐसा नतीजा आना कितना चौंकाने वाला होता। आम तौर पर 0.05 से कम p-value को "कोई असर नहीं" के खिलाफ सबूत माना जाता है। लेकिन statistical significance का मतलब यह नहीं कि असर बड़ा या महत्वपूर्ण भी है, और यह कारण (cause) साबित नहीं करती।

9. R-squared और adjusted R-squared में क्या अंतर है?

R-squared बताता है कि y के बदलाव का कितना हिस्सा model समझा पा रहा है (0 से 1 के बीच)। Features जोड़ने से यह हमेशा बढ़ता है, चाहे feature बेकार ही क्यों न हो। Adjusted R-squared features की संख्या के हिसाब से इसे सुधारता है, इसलिए models की तुलना के लिए ज्यादा भरोसेमंद है।

10. VIF और multicollinearity क्या है?

जब features आपस में बहुत ज्यादा जुड़े (correlated) हों, तो coefficients अस्थिर हो जाते हैं। इसे multicollinearity कहते हैं और इसे Variance Inflation Factor (VIF) से नापते हैं। आम नियम के अनुसार लगभग 5 से 10 से ऊपर के मान को चेतावनी माना जाता है, पर इसे कानून नहीं, सिर्फ मार्गदर्शक समझें।

11. Logit कब इस्तेमाल करें?

जब target सिर्फ दो नतीजों वाला (0 या 1) हो, जैसे pass या fail, तब सीधी line वाला OLS गलत औज़ार है। तब Logit (logistic regression) इस्तेमाल करें, जो class 1 की probability को S-आकार के curve से model करता है।

12. Statsmodels में time series और ARIMA कैसे चलाते हैं?

Statsmodels का tsa module time series के लिए है। आम क्रम है: series plot करें, seasonal_decompose से trend और seasonality अलग करें, adfuller से stationarity जाँचें, फिर ARIMA(series, order=(p, d, q)) fit करें और forecast निकालें।

Summary

Statsmodels = ऐसे statistical models बनाने की Python library, जो prediction के साथ p-values, confidence intervals और tests देकर नतीजों को समझाती है।

इस lesson में आपने Statsmodels का परिचय, install और दो APIs, data की तैयारी, OLS regression और summary() पढ़ना, p-value और R-squared, residuals और VIF जैसी जाँचें, predictions, Logit, GLM, ARIMA, hypothesis tests और एक mini-project सीखा।

अब mini-project और practice questions हल करें। अगले कदम के रूप में scikit-learn से prediction वाला पक्ष और Statsmodels का official documentation पढ़ें। Data को सुरक्षित रखना सीखना हो तो MySQL Introduction in Hindi lesson देखें, और इस विषय का पूरा रास्ता Data Analyst Tutorial in Hindi पर मिलेगा।

Related Articles — Python Hindii

🧑‍💻 Python Coding Lab

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