Free tutorials & notes in Hindi & English · Clean code examples 🧰 मुफ़्त PDF और फ़ोटो टूल्स →
⚙️ Week 8 – Advanced ML  ·  दिन 49

दिन 49: Time Series और Forecasting

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

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

  • Time-series data ख़ास क्यों है
  • Trend, seasonality और decomposition
  • Baselines: naive और seasonal-naive
  • Lag और calendar features के साथ ML forecasting
  • Holt-Winters और समय-आधारित validation

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

Delhi के schools और hospitals छुट्टियाँ, masks और extra staff plan करने के लिए 30 दिन का air-quality अनुमान चाहते हैं। Retailers अगले महीने की demand, banks अगले हफ़्ते की cash निकासी। ये सब forecasting समस्याएँ हैं – और नियम सामान्य ML से अलग हैं क्योंकि भविष्य कभी अतीत में leak नहीं होना चाहिए।

Series देखें

Python
import pandas as pd
import matplotlib.pyplot as plt
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date").asfreq("D")
print(w.shape, "| missing days:", w["aqi"].isna().sum())
m = w["aqi"].resample("MS").mean()
fig, ax = plt.subplots(figsize=(10, 3.6))
ax.plot(w.index, w["aqi"], color="#cbd5e1", lw=0.7, label="daily")
ax.plot(m.index, m.values, color="#dc2626", marker="o", lw=2, label="monthly mean")
ax.set_title("Delhi AQI 2022–2024: strong yearly seasonality"); ax.legend(); plt.show()
(1096, 2) | missing days: 0
2022 से 2024 तक Delhi का daily और monthly AQI
हर साल वही आकार: सर्दी में ख़राब, मानसून में साफ़।

Trend + seasonality + noise

Python
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")
weekly = w["aqi"].resample("W").mean()
dec = seasonal_decompose(weekly, model="additive", period=52)
fig = dec.plot(); fig.set_size_inches(10, 6.5); fig.suptitle("Decomposition of weekly AQI", y=1.01)
plt.tight_layout(); plt.show()
print("seasonal swing (max − min):", round(dec.seasonal.max() - dec.seasonal.min()), "AQI points")
seasonal swing (max − min): 242 AQI points
Weekly AQI का trend, seasonal और residual में decomposition
Seasonality हावी; trend लगभग सपाट; residual रोज़ का शोर।

समय से split करें, कभी random नहीं

Python
import pandas as pd
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")
train, test = w.loc[:"2023-12-31", "aqi"], w.loc["2024-01-01":, "aqi"]
print("train:", train.index.min().date(), "→", train.index.max().date(), len(train))
print("test :", test.index.min().date(), "→", test.index.max().date(), len(test))
train: 2022-01-01 → 2023-12-31 730 test : 2024-01-01 → 2024-12-31 366
⚠️ Random splits भविष्य leak करते हैं

train_test_split से model 15 March से सीखकर 14 March predict कर सकता है – असल ज़िंदगी में असंभव। हमेशा अतीत पर train और भविष्य पर test करें (या TimeSeriesSplit लें)।

पहले baselines

Python
import numpy as np
import pandas as pd
from sklearn.metrics import mean_absolute_error, mean_absolute_percentage_error
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")["aqi"]
test = w.loc["2024"]
preds = {"naive (last value of 2023)": pd.Series(w.loc["2023-12-31"], index=test.index),
         "mean of 2022–23": pd.Series(w.loc[:"2023"].mean(), index=test.index),
         "seasonal naive (same day last year)": w.shift(365).loc["2024"]}
for name, p in preds.items():
    print(f"{name:36s} MAE {mean_absolute_error(test, p):6.1f}   MAPE {mean_absolute_percentage_error(test, p) * 100:5.1f}%")
naive (last value of 2023) MAE 106.3 MAPE 102.2% mean of 2022–23 MAE 71.9 MAPE 56.9% seasonal naive (same day last year) MAE 34.0 MAPE 23.2%
🧠 MAPE

Mean absolute percentage error: “औसतन हम 18% ग़लत हैं”। Managers के लिए आसान, पर असली values शून्य के पास हों (0 units sales) तो अस्थिर।

Lag features के साथ machine learning

Python
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")
f = pd.DataFrame(index=w.index)
f["aqi"] = w["aqi"]
f["lag_365"] = w["aqi"].shift(365)                   # same day last year
f["lag_30"] = w["aqi"].shift(30)                     # a month ago (known 30 days ahead)
f["roll_30_lag_30"] = w["aqi"].shift(30).rolling(30).mean()
f["doy_sin"] = np.sin(2 * np.pi * w.index.dayofyear / 365.25)
f["doy_cos"] = np.cos(2 * np.pi * w.index.dayofyear / 365.25)
f["weekday"] = w.index.dayofweek
f = f.dropna()
tr, te = f.loc[:"2023"], f.loc["2024"]
feats = [c for c in f.columns if c != "aqi"]
model = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0).fit(tr[feats], tr["aqi"])
pred = pd.Series(model.predict(te[feats]), index=te.index)
print("training rows:", len(tr), "| features:", feats)
print(f"ML forecast MAE {mean_absolute_error(te['aqi'], pred):.1f}")
pred.to_frame("pred").assign(actual=te["aqi"]).to_csv("aqi_forecast_2024.csv")
training rows: 365 | features: ['lag_365', 'lag_30', 'roll_30_lag_30', 'doy_sin', 'doy_cos', 'weekday'] ML forecast MAE 26.8
💡 सिर्फ़ वही लें जो पता होगा

30 दिन आगे के forecast में कल का AQI उपलब्ध नहीं – इसलिए सबसे छोटा lag 30 दिन। Lags को forecast horizon से मिलाना leakage से बचने का time-series रूप है।

Holt-Winters exponential smoothing

Python
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from sklearn.metrics import mean_absolute_error
w = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")["aqi"]
monthly = w.resample("MS").mean()
train, test = monthly.loc[:"2023"], monthly.loc["2024"]
hw = ExponentialSmoothing(train, trend=None, seasonal="additive", seasonal_periods=12).fit()
fc = hw.forecast(12)
snaive = monthly.shift(12).loc["2024"]
print(f"monthly MAE → Holt-Winters {mean_absolute_error(test, fc):.1f} | seasonal naive {mean_absolute_error(test, snaive):.1f}")
plt.figure(figsize=(10, 3.8))
plt.plot(monthly.index, monthly, color="#64748b", marker="o", label="actual")
plt.plot(fc.index, fc, color="#dc2626", marker="o", ls="--", label="Holt-Winters forecast 2024")
plt.axvspan(test.index.min(), test.index.max(), color="#fee2e2", alpha=0.5)
plt.title("Forecasting 2024 monthly AQI from 2022–23 only"); plt.legend(); plt.show()
monthly MAE → Holt-Winters 4.0 | seasonal naive 4.7
Monthly AQI के असली values और 2024 का Holt-Winters forecast
सिर्फ़ 2022–23 पर train होकर model 2024 की सर्दी का उछाल अच्छे से predict करता है।

Time-series cross-validation

Python
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
idx = np.arange(12)
for i, (tr, te) in enumerate(TimeSeriesSplit(n_splits=4, test_size=2).split(idx), 1):
    print(f"fold {i}: train months {tr.min()}–{tr.max()}  →  test months {te.tolist()}")
fold 1: train months 0–3 → test months [4, 5] fold 2: train months 0–5 → test months [6, 7] fold 3: train months 0–7 → test months [8, 9] fold 4: train months 0–9 → test months [10, 11]
Methodकिसके लिए अच्छा
Seasonal naiveहमेशा – हराने वाली baseline
Holt-Winters / ETSसाफ़ trend + seasonality, कम series
ARIMA / SARIMAClassic statistical forecasting, short-term
ProphetHolidays (Diwali!) वाली business series, आसान
ML with lags (boosting)कई जुड़ी series, weather, promotions जैसे extra features

🏅 आज के Job Skills

✔ Time series को decompose करना✔ समय से split और validate करना✔ Naive और seasonal-naive baselines को हराना✔ Lag features और Holt-Winters से forecast

Practice tasks

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

Task 1: Holt-Winters से 2024 का monthly average temperature forecast करें और seasonal naive से तुलना करें।
Solution देखें
Python
import pandas as pd
from statsmodels.tsa.holtwinters import ExponentialSmoothing
from sklearn.metrics import mean_absolute_error
t = pd.read_csv("delhi_weather.csv", parse_dates=["date"]).set_index("date")["avg_temp_c"].resample("MS").mean()
fc = ExponentialSmoothing(t.loc[:"2023"], seasonal="additive", seasonal_periods=12).fit().forecast(12)
print("HW", round(mean_absolute_error(t.loc["2024"], fc), 2), "| seasonal naive", round(mean_absolute_error(t.loc["2024"], t.shift(12).loc["2024"]), 2))
HW 0.28 | seasonal naive 0.45
Task 2: 2024 की weekly BazaarKart revenue बनाएँ और आख़िरी 8 हफ़्ते 4-week moving average से forecast करें। Festive peak के बाद वाले हफ़्तों को यह ज़्यादा क्यों forecast करता है?
Solution देखें
Python
import pandas as pd
s = pd.read_csv("sales_data.csv", parse_dates=["order_date"]); s["rev"] = s["quantity"] * s["unit_price"] * (1 - s["discount"])
wk = s.set_index("order_date")["rev"].resample("W").sum()
ma = wk.shift(1).rolling(4).mean()
print(pd.DataFrame({"actual": wk, "moving_avg_forecast": ma}).tail(8).round(0))
actual moving_avg_forecast order_date 2024-11-17 149198.0 248842.0 2024-11-24 212992.0 235032.0 2024-12-01 174036.0 239370.0 2024-12-08 110144.0 237219.0 2024-12-15 147478.0 161593.0 2024-12-22 86928.0 161162.0 2024-12-29 96331.0 129647.0 2025-01-05 30867.0 110220.0
Task 3: 7-दिन-आगे forecast के लिए ML model में lag-7 feature जोड़ें। MAE कितना सुधरा?

Quick quiz

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

1. Time series में train_test_split क्यों नहीं?
अतीत पर train, भविष्य पर test।
2. Seasonal naive क्या predict करता है?
जैसे पिछले साल का वही दिन।
3. Lag-30 feature मतलब…
shift(30)।
4. MAPE = 12% मतलब…
Mean absolute percentage error।
5. Holt-Winters क्या model करता है?
हर हिस्से का exponential smoothing।

Interview corner

💼 Interview Corner

Time-series validation कैसे अलग है?

Data समय से split होना चाहिए – पहले के periods पर train, बाद के पर test – expanding या rolling windows (TimeSeriesSplit) से। Features सिर्फ़ forecast के समय उपलब्ध जानकारी लें।

Forecasting के लिए कौन सी baselines लेते हैं?

Naive (आख़िरी value), seasonal naive (पिछले season का वही period) और moving average। Complex model तभी काम का है जब इन्हें साफ़ हराए।

सारांश

  • Time series = trend + seasonality + noise।
  • समय से split करें; naive और seasonal-naive baselines को हराएँ।
  • Horizon से मिले lags + calendar features वाला ML अच्छा काम करता है।
  • Holt-Winters मज़बूत सरल seasonal model है; MAE और MAPE बताएँ।
➡️ आगे

Day 50: अपना model deploy करें – joblib से save करें और Streamlit व Flask से predictions दें।

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

Stationarity क्या है?
ऐसी series जिसका mean और variance समय के साथ न बदले। ARIMA को यह चाहिए (differencing लें); ML और Holt-Winters trend और seasonality सीधे संभालते हैं।
क्या Diwali को feature बना सकते हैं?
हाँ – Indian retail और pollution data के लिए holiday flags या “Diwali तक के दिन” ताक़तवर features हैं। Prophet holiday lists सीधे support करता है।
← Data Science (60 Days)
🔗

Share this topic with a friend

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

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

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

अगला topicदिन 50: Models Save और Deploy (Streamlit, Flask) आपकी प्रगति: 49 / 60 (82%) · Lesson 50 / 60 आगे बढ़ें →

यह lesson कैसा लगा?

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

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

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

▶ CodingEasily on YouTube

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

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

▶ Channel subscribe करें