2.1.1 · HinglishData Preprocessing & Feature Engineering

Types of data (numerical, categorical, ordinal, text)

3,518 words16 min readRead in English

2.1.1 · AI-ML › Data Preprocessing & Feature Engineering

Overview

Data types ko samajhna feature engineering ki buniyad hai. Har ML algorithm apne input data ke baare mein kuch assumptions karta hai—galat type do toh model ya toh crash karega ya chup-chaap bakwaas results dega. Yeh note explain karta hai ki har data type kya represent karta hai, kyun yeh distinction algorithms ke liye matter karti hai, aur kaise har type ko pehchano aur handle karo.


Core Data Types

1. Numerical Data

WHY yeh distinction matter karti hai:

  • Continuous data → gradient-based models ke liye normalize/standardize karo (large-scale features ko dominate karne se rokta hai)
  • Discrete data → kabhi kabhi better hota hai categorical treat karna agar values kam hoon (e.g., "number of bedrooms: 1, 2, 3" tree models ke liye one-hot encoded better kaam kare)

Hum data ko transform karna chahte hain taaki uska mean = 0, standard deviation = 1 ho.

Step 1: Mean hatao (centering) jahan mean hai.

WHY? Centering distribution ko shift karta hai taaki uska center zero par aa jaye. Isse location bias remove hoti hai.

Step 2: Standard deviation se scale karo jahan standard deviation hai.

WHY? se divide karne par spread (variance) 1 ho jaata hai. Ab saare features same scale par hain.

Kab use karo: Linear regression, logistic regression, SVMs, neural networks (koi bhi algorithm jo distance metrics ya gradient descent use kare).

Step 1: Mean calculate karo

WHY yeh step? Hume distribution ka center chahiye taaki use zero par shift kar sakein.

Step 2: Standard deviation calculate karo

WHY yeh step? Standard deviation spread measure karta hai. Hum ise scale normalize karne ke liye use karte hain.

Step 3: Har value ko scale karo

WHY yeh step? Ab har value represent karta hai "mean se kitne standard deviations door"—ek universal scale.

Result: Scaled values: [-1.09, 0.62, -0.41, 1.64, -0.75] Saari values ab mean ≈ 0, std ≈ 1 hain, jo unhe doosre scaled features ke saath comparable banata hai.


2. Categorical Data

KEY INSIGHT: Tum "colors ka mean" ya "USA - India" calculate nahi kar sakte. Yeh labels hain, numbers nahi.

Problem: ML algorithms ko numbers chahiye. Categories ko numbers mein kaise convert karein bina fake order imply kiye?

Solution: Har category ke liye ek binary column banao.

Step 1: Saari unique categories list karo Categories: {Cat A, Cat B, Cat C}

Step 2: Har sample ke liye ek binary vector banao

  • Agar sample Cat A hai: [1, 0, 0]
  • Agar sample Cat B hai: [0, 1, 0]
  • Agar sample Cat C hai: [0, 0, 1]

WHY yeh kaam karta hai: Har category ko apna dimension milta hai. Koi bhi category numeric space mein doosre ke "paas" nahi hoti. Koi bhi do one-hot vectors ke beech distance same hota hai (Euclidean space mein √2).

Mathematical representation: categories ke liye, category ko encode karo as: jahan 1 position par hai.

Transaction Payment Method
1 UPI
2 Credit Card
3 UPI
4 Cash

Step 1: Unique categories identify karo Categories: {UPI, Credit Card, Cash} → 3 categories

WHY yeh step? Hume jaanna hai ki kitne binary columns banana hain.

Step 2: Binary columns banao Columns banao: is_UPI, is_CreditCard, is_Cash

Step 3: Har row encode karo

Transaction is_UPI is_CreditCard is_Cash
1 1 0 0
2 0 1 0
3 1 0 0
4 0 0 1

WHY yeh encoding?

  • Transaction 1 UPI hai → UPI column on karo, baaki off karo
  • Koi bhi category numerically doosre ke "beech" nahi hai
  • UPI se Cash ki distance = UPI se Credit Card ki distance = √2

Tree models ke liye alternative: Label encoding (UPI=0, Credit Card=1, Cash=2) theek kaam karta hai kyunki trees individual values par split karte hain, distances par nahi.

Kyun sahi lagta hai: "Maine text ko numbers mein convert kar diya, model handle kar lega!"

Kyun galat hai: Model ab sochta hai ki Cash (2) Credit Card (1) se "double" hai, aur Credit Card UPI aur Cash ke "beech" hai. Woh jaisi weights seekhega Cash ke liye, jo aisi mathematical relationships imply karta hai jo exist hi nahi karti.

Fix: One-hot encoding use karo algorithms ke liye jo numeric relationships assume karte hain (linear models, neural nets). Label encoding SIRF tree-based models ke liye use karo (jo "is equal to X" par split karte hain) ya ordinal data ke liye.

Steel-man the mistake: Label encoding memory bachata hai (1 column vs. k columns) aur kaam kar sakta hai agar model fake ordering ignore karna seekh le. Lekin yeh risky hai—jab one-hot safer hai toh bias kyun introduce karo?


3. Ordinal Data

KEY DISTINCTION categorical se: Order matter karta hai. PhD > Master's meaningful hai. Lekin High School se Bachelor's ka "gap" ≠ Master's se PhD ka gap.

Constraint: Hume order preserve karna hai:

Solution: Categories ko integers mein map karo order respect karte hue: jahan

WHY yeh kaam karta hai: Algorithms jo comparisons use karte hain (tree splits: "is education ≥ 2?") ordering preserve karte hain. Distance-based algorithms (KNN, linear models) uniform spacing assume karenge—acceptable hai agar ordinal gaps roughly similar hain, nahi toh problematic hai.

Employee Education
A Bachelor's
B PhD
C High School
D Master's

Step 1: Ordering define karo High School < Bachelor's < Master's < PhD

WHY yeh step? Encoding se pehle hume explicitly order specify karna hoga.

Step 2: Integer codes assign karo

  • High School → 0
  • Bachelor's → 1
  • Master's → 2
  • PhD → 3

Step 3: Encoding apply karo

Employee Education_Encoded
A 1
B 3
C 0
D 2

WHY yeh encoding?

  • Ek decision tree split kar sakta hai: "education_encoded ≥ 2" → Master's aur PhD capture karta hai
  • Order preserved hai: 0 < 1 < 2 < 3 reality se match karta hai
  • Linear model equal spacing assume karega (problem agar PhD "bahut zyada" impactful hai Master's se)

Spacing ke baare mein kab concern karo: Agar salary predict kar rahe ho aur PhD holders Bachelor's holders se 3× earn karte hain (3× increment nahi), toh consider karo:

  • Multiple binary features banana: has_bachelors, has_masters, has_phd
  • Target encoding use karna (har category ki mean target value se replace karo)

4. Text Data

KEY CHALLENGE: Text high-dimensional, variable-length, aur context-dependent hota hai. "Bank" (financial institution) vs. "river bank" ke liye context samajhna padta hai.

Goal: Ek document ko fixed-length vector of numbers mein convert karo.

Step 1: Vocabulary build karo (saare documents mein saare unique words ka set)

WHY? Hume ek fixed set of dimensions chahiye. Vocabulary size = number of dimensions.

Step 2: Har document ke liye, har word ke occurrences count karo jahan

WHY yeh kaam karta hai: Har document space mein ek point ban jaata hai. Similar documents (similar words use karte hue) is space mein paas hote hain.

Mathematical form: Vocabulary of size ke liye, document hai:

Limitation: Word order ignore karta hai. "Dog bites man" = "Man bites dog" (same BoW vector).

  1. "The movie was good"
  2. "The movie was bad"
  3. "Great movie"

Step 1: Vocabulary build karo Unique words extract karo: {the, movie, was, good, bad, great} Vocabulary size = 6

WHY yeh step? Hamare feature space dimensions define karta hai.

Step 2: Har document ke liye word occurrences count karo

Document 1: "The movie was good"

  • the: 1, movie: 1, was: 1, good: 1, bad: 0, great: 0
  • Vector: [1, 1, 1, 1, 0, 0]

WHY yeh step? Text ko numbers mein convert karta hai counting ke zariye.

Document 2: "The movie was bad"

  • the: 1, movie: 1, was: 1, good: 0, bad: 1, great: 0
  • Vector: [1, 1, 1, 0, 1, 0]

Document 3: "Great movie"

  • the: 0, movie: 1, was: 0, good: 0, bad: 0, great: 1
  • Vector: [0, 1, 0, 0, 0, 1]

Result Matrix:

the movie was good bad great
D1 1 1 1 1 0 0
D2 1 1 1 0 1 0
D3 0 1 0 0 0 1

Interpretation:

  • D1 aur D2 similar hain ("the movie was" share karte hain) → dot product = 3
  • D3 different hai (alag words) → D1 ke saath dot product = 1

Real use ke liye next step: Stop words hatao ("the", "was"), common words ko down-weight karne ke liye TF-IDF apply karo.

Kyun sahi lagta hai: "Model unknown words ko ignore kar lega."

Kyun galat hai: Agar test set mein "excellent" extensively use hoti hai positive reviews indicate karne ke liye, toh model use all-zeros dekhta hai (missing signal). Performance drop hoti hai kyunki tum key information ke liye blind ho.

Fix:

  1. Training ke dauran: Vocabulary mein ek <UNK> (unknown) token rakho
  2. Testing ke dauran: Unseen words ko <UNK> se map karo
  3. Better: Subword tokenization use karo (BPE, WordPiece) taaki "excellent" "excell" + "ent" mein toot jaaye, learned pieces reuse karte hue
  4. Best: Pre-trained embeddings use karo (Word2Vec, BERT) jo already millions of words jaante hain

Steel-man the mistake: Unknowns ignore karna simple hai aur kabhi kabhi kaam karta hai agar test set training se similar ho. Lekin production mein language evolve hoti hai—nayi slang, product names, events. Unknowns handle karna robustness ke liye critical hai.


Advanced Considerations

80/20 Rule: 80% performance 4 core types ko correctly handle karne se aati hai. Yahan time lagao exotic feature engineering se pehle.


Data Type Decision Tree

Is the data text in sentences?
├─ YES → Text Data (BoW, TF-IDF, embedings)
└─ NO → Is it numbers?
    ├─ YES → Can you compute meaningful average?
    │   ├─ YES → Numerical (continuous or discrete)
    │   └─ NO → Probably categorical (e.g., zip codes look numeric but aren't)
    └─ NO → Is there a meaningful order?
        ├─ YES → Ordinal (education, ratings)
        └─ NO → Categorical (colors, countries)

Connections

  • Normalization and Scaling → Min-max, z-score, robust scaling mein deep dive
  • One-Hot Encoding vs Label Encoding → Kaunsi encoding strategy kab use karni hai
  • TF-IDF and Text Vectorization → Advanced text feature extraction
  • Feature Engineering from Datetime → Timestamps se features extract karna
  • Handling High-Cardinality Categorical → Embeddings, target encoding, hashing
  • Curse of Dimensionality → Kyun one-hot encoding feature space explode kar sakti hai
  • Feature Scaling Impact on Gradient Descent → Mathematical proof ki scaling kyun matter karti hai


Recall Ek 12-Saal-Ke Bacche Ko Explain Karo

Socho tum apna school ka saman organize kar rahe ho.

Numerical data pencils count karne jaisi hai—tum keh sakte ho "mere paas 5 pencils hain" aur math kar sakte ho (3 aur jodne par = 8 total). Tum apni class ka average nikaal sakte ho.

Categorical data tumhari pencil colors jaisi hai—red, blue, green. Tum nahi keh sakte "red + blue = ?" ya "average color." Yeh bas alag types hain, koi math nahi.

Ordinal data medal rankings jaisi hai: bronze < silver < gold. Ek order hai (gold behtar hai), lekin tum nahi keh sakte "gold exactly silver se double as good hai." Order matter karta hai, lekin ranks ke beech spacing equal nahi hoti.

Text data tumhari diary entries jaisi hai—poore sentences aur paragraphs. Computers English seedhi nahi samajhte, isliye hume pehle use numbers mein convert karna padta hai. Hum count kar sakte hain ki words kitni baar aate hain: "homework" 3 baar aata hai, "fun" 0 baar aata hai (sadly!).

Yeh kyun matter karta hai? Agar tum calculator ko words do, woh toot jaata hai. Agar tum apni pencil colors ko numbers ki tarah treat karo ("red = 1, blue = 2"), calculator sochta hai blue "twice" red hai, jo bakwaas hai. Data type ko tool se match karo!


#flashcards/ai-ml

ML mein char fundamental data types kaun se hain? :: Numerical (continuous/discrete), Categorical (no order), Ordinal (ordered categories), Text (natural language)

Gradient descent algorithms ke liye numerical features scale kyun karne chahiye?
Kyunki large scales wale features (e.g., price in lakhs vs age in years) gradient ko dominate karte hain, causing slow convergence aur small-scale features ki poor learning. Scaling saare features ko equal footing par laata hai.
Z-score normalization ka formula kya hai?
jahan mean hai, standard deviation hai. Yeh data ko mean=0, std=1 par transform karta hai.
Linear models mein categorical data ke liye one-hot encoding, label encoding se preferred kyun hai?
Label encoding (A=0, B=1, C=2) mathematical relationships imply karta hai (C is "twice" B) jo exist nahi karte. One-hot encoding orthogonal binary vectors create karta hai saari categories ke beech equal distances ke saath, fake ordering avoid karte hue.
Label encoding, one-hot encoding ki jagah kab acceptable hai?
Tree-based models ke liye (decision trees, random forests, XGBoost) kyunki woh "equals" conditions par split karte hain, mathematical relationships par nahi. Kisi bhi model mein ordinal data ke liye bhi acceptable hai.
Categorical aur ordinal data mein kya difference hai?
Categorical mein koi meaningful order nahi hota (colors, countries). Ordinal mein meaningful order hota hai lekin uneven spacing hoti hai (ratings: poor < fair < good < excellent, lekin levels ke beech gaps necessarily equal nahi hote).
Bag-of-Words text ko numbers mein kaise convert karta hai?
Unique words ki vocabulary build karo, phir har document ko word counts ka vector represent karo. Vector dimension = vocabulary size, har element = us document mein us word ka count.
Bag-of-Words representation ki main limitation kya hai?
Yeh word order aur context ignore karta hai. "Dog bites man" aur "man bites dog" identical BoW vectors produce karte hain despite having opposite meanings.
Zip codes ko numerical data treat karna problematic kyun ho sakta hai?
Zip codes numeric lagte hain lekin categorical regions represent karte hain. Average zip code compute karna ya yeh assume karna ki "zip 40001 zip 40002 ke paas hai" meaningless hai. Unhe categorical treat karna chahiye ya features ke roop mein encode karna chahiye.
Data type handling ke liye 80/20 rule kya hai?
80% model performance 4 core data types (numerical, categorical, ordinal, text) ko correctly handle karne se aati hai. Exotic feature engineering mein invest karne se pehle yeh fundamentals master karo.
BoW models mein test data ke unseen words kaise handle karo?
Training ke dauran vocabulary mein ek <UNK> (unknown) token rakho, unseen test words ko <UNK> se map karo. Better: subword tokenization ya pre-trained embeddings use karo jo rare/new words handle karte hain.
High-cardinality categorical data kya hai aur iske liye one-hot encoding problematic kyun hai?
Data jisme hazaaron/millions unique categories hoti hain (e.g., user IDs). One-hot encoding massive sparse matrices create karta hai jo memory explode kar deti hain aur model performance hurt karti hain. Iske bajaaye embeddings ya target encoding use karo.
Datetime ko numerical ki jagah features ke roop mein kab extract karna chahiye?
Jab cyclical patterns matter karte hain (hour of day, day of week) ya categorical effects exist karte hain (is_weekend, is_holiday). Raw timestamps as numbers in meaningful patterns ko kho dete hain.
Standardization mathematically kya achieve karta hai?
Data ko aur wala transform karta hai, features ko original units se regardless comparable banata hai. Formula:
Kisi bhi do one-hot encoded vectors ke beech distance same kyun hota hai?
Har one-hot vector mein exactly ek 1 aur baaki 0s hote hain. Koi bhi do aise vectors ke beech Euclidean distance hai, yeh ensure karte hue ki koi bhi category doosre ke "paas" nahi hoti.

Concept Map

includes

includes

includes

includes

splits into

splits into

normalized by

if few values

z-score mean 0 std 1

foundation of

Data Types

Numerical Data

Categorical Data

Ordinal Data

Text Data

Continuous

Discrete

Standard Scaling

ML Algorithm Choice