2.1.1 · D4Data Preprocessing & Feature Engineering

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

2,566 words12 min readBack to topic

This page tests the ideas from Types of data (numerical, categorical, ordinal, text) with a graded ladder: L1 Recognition → L2 Application → L3 Analysis → L4 Synthesis → L5 Mastery. Each problem states itself cleanly, then hides a full worked solution inside a collapsible callout so you can self-test. Numeric answers are machine-verified.

Before anything numeric, one reminder of the two formulas we lean on, so no symbol appears unearned.


Level 1 — Recognition

Problem 1.1

Classify each feature as numerical-continuous, numerical-discrete, categorical, or ordinal: (a) Blood type (A, B, AB, O) (b) Number of siblings (c) Body temperature in °C (d) Movie star-rating (1★ to 5★) (e) City of birth.

Recall Solution

(a) Categorical — the letters are labels; A minus B is meaningless, and there is no natural order. (b) Numerical-discrete — a count; you can have 0, 1, 2 siblings but never 2.5. (c) Numerical-continuous — temperature can be 36.7, 36.71, … any value in a range. (d) Ordinal — ordered (5★ > 3★) but the gap 1★→2★ need not equal 4★→5★. (e) Categorical — city names are labels with no inherent numeric order.

Problem 1.2

True or false: "Because education is stored as the integers 0,1,2,3, it is numerical data and we may take its mean." Explain.

Recall Solution

False. The integers are an ordinal encoding we imposed; the underlying data is ordinal. A mean of would claim "the average employee is three-quarters of the way from Bachelor's to Master's" — but the gaps between education levels are not guaranteed equal, so that number is not meaningful. Ordinal codes support (rank comparisons), not arithmetic like or averaging with unit meaning.


Level 2 — Application

Problem 2.1

Standard-scale the exam scores [40, 50, 60, 70, 80]. Report , , and all five z-scores.

Recall Solution

Step 1 — mean. WHAT: find the balance point. WHY: centering needs it. Step 2 — standard deviation. WHAT: measure spread. The gaps from 60 are . Step 3 — z-scores. WHAT: express each value as "'s from mean". Notice the middle value maps to exactly (it is the mean) and the set is symmetric — a good sanity check.

Problem 2.2

One-hot encode the color column [Red, Green, Red, Blue]. Write the three binary columns for each row, then compute the Euclidean distance between the Red row and the Blue row.

Recall Solution

Step 0 — WHY one-hot at all? Color is categorical: Red, Green, Blue are labels with no order and no arithmetic ("Red Blue" is meaningless). A distance-based model still needs numbers, so we must convert without smuggling in a fake order. One-hot does this by giving every category its own axis, so no category sits "between" or "twice" another.

Step 1 — unique categories. WHAT: list them. WHY: the count tells us how many binary columns (axes) we need. {Red, Green, Blue} → 3 columns is_Red, is_Green, is_Blue.

Step 2 — encode. WHAT: for each row, switch on the column matching its label, all others off. WHY: this places each row on exactly one axis, at distance 1 from the origin.

Row is_Red is_Green is_Blue
Red 1 0 0
Green 0 1 0
Red 1 0 0
Blue 0 0 1

Step 3 — distance Red vs Blue. WHAT: measure how far apart two rows are. WHY the Euclidean formula? Distance-based models (KNN, k-means, linear models via inner products) compare rows using straight-line distance — the same Pythagoras that measures gaps on a map — so this is exactly the number the model "feels". Red, Blue, differences : What this means: every distinct pair of one-hot vectors is apart — Red-to-Blue equals Red-to-Green equals Green-to-Blue. That equal-distance property is the whole point: the model can't infer a false "Red is nearer Green than Blue".

Read the figure below carefully. Each arrow is one category living on its own axis; notice the three dashed edges connecting their tips are all the same length . That visual symmetry is the geometric proof that one-hot introduces no ordering — no vertex is special.

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

Level 3 — Analysis

Problem 3.1

A teammate label-encodes payment method as UPI=0, Card=1, Cash=2 and feeds it to linear regression. The learned model is . Interpret what the model believes about Cash vs UPI, and explain in one sentence why this is a modelling error.

Recall Solution

With code (UPI): . With code (Card): . With code (Cash): . The model believes payment methods sit on an evenly spaced number line where Cash contributes exactly twice the "distance" of Card from UPI, and that Card is numerically between UPI and Cash. Error: payment method is categorical — there is no real ordering or spacing, so the constant per step encodes a relationship that does not exist. One-hot encoding (see One-Hot Encoding vs Label Encoding) removes this by giving each method its own free weight.

Problem 3.2

You must encode a US-state feature with 50 distinct values for a linear model. Compare one-hot vs ordinal encoding in terms of (i) columns produced and (ii) risk of fake ordering. Which concept does one-hot's cost illustrate?

Recall Solution

(i) One-hot: 50 categories → 50 binary columns (or 49 if you drop one as a reference). Ordinal: 1 column of integers . (ii) Ordinal risk: it silently asserts Alabama(0) < … < Wyoming(49) with equal spacing — meaningless for states, so a linear model learns a false trend. One-hot avoids that but explodes the feature count. Blowing up to 50 sparse dimensions is exactly the Curse of Dimensionality; for very large label sets see Handling High-Cardinality Categorical.


Level 4 — Synthesis

Problem 4.1

A dataset has three raw features per house: price_lakhs (continuous), bedrooms ∈ {1,2,3} (discrete), condition ∈ {Poor<Fair<Good} (ordinal). Design a preprocessing pipeline for a neural network, choosing an encoding for each and justifying it. Then state the final feature-vector length for one house.

Recall Solution

First, the principle for discrete counts: a count like bedrooms can safely stay numeric when its effect on the target is roughly monotone and evenly spaced — i.e. each extra unit adds a similar amount (then one column suffices and preserves ordering). It should be one-hot instead when (a) it has few distinct values and (b) the effect is likely non-linear or non-monotone — e.g. price per bedroom may rise from 1→2 but flatten or dip from 2→3 (a 3-bed built as tiny rooms). With only 3 levels here, one-hot costs just 2 extra columns while freeing the model from assuming equal per-bedroom steps, so the low cost buys real flexibility. (If bedrooms ranged 1–15 and priced roughly linearly, keeping it numeric-and-scaled would be the principled choice.) With that settled:

  • price_lakhs → standard scaling. WHY: a neural net trains by gradient descent; a large-scale feature would dominate the gradient. Scaling to balances features — see Feature Scaling Impact on Gradient Descent. → 1 column.
  • bedrooms → one-hot (per the principle above: 3 levels, plausibly non-linear effect). → 3 columns.
  • condition → ordinal (0,1,2). WHY: the order Poor<Fair<Good is real and monotone with quality, so a single ranked column carries the signal compactly. → 1 column.

Final length: features per house.

Problem 4.2

Standard-scale price_lakhs = [50, 75, 60, 90, 55] (the parent-note dataset) and give the scaled value for the 90-lakh house, using for .

Recall Solution

Mean: . Std: gaps ; squares ; sum . 90-lakh house: . This matches the parent note's worked example ().


Level 5 — Mastery

Problem 5.1

A signup_datetime column (e.g. 2024-03-15 14:30) is currently treated as text. Explain (a) why raw datetime text is a poor feature, (b) which data types you would derive from it, and (c) how you would encode a day_of_week feature so a linear model does not think Sunday(6) is "far" from Monday(0).

Recall Solution

(a) As raw text, the model sees an opaque string; string comparison does not expose that March is near April, or that 14:30 is "afternoon". No arithmetic or ordering is usable — see Feature Engineering from Datetime. (b) Derive: hour (numerical-discrete/continuous), day_of_week (categorical or cyclic), month (categorical/cyclic), is_weekend (binary categorical), days_since_signup (numerical-continuous). (c) Plain ordinal codes 0..6 make Sunday(6) look 6 units from Monday(0) even though they are adjacent in a week. Cyclic encoding fixes this: map each day to a point on a circle, Now Sunday and Monday become neighbouring points on the circle, so their distance is small — order-wraps correctly.

Study the figure below. All seven days sit on one unit circle. Trace the green chord (Sunday→Monday): it is short because the two points are neighbours even though their raw codes 6 and 0 are far apart. Now trace the orange chord (Sunday→Wednesday): it is much longer, matching their true 3-day gap. The picture shows exactly why a straight number line lies about weekdays but the circle tells the truth — the wrap from 6 back to 0 is a tiny step, not a leap.

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

Problem 5.2

For the cyclic day encoding above, compute the Euclidean distance between Sunday () and Monday (), and between Sunday () and Wednesday (). Verify that Monday is closer to Sunday than Wednesday is.

Recall Solution

Each day is the point on a unit circle, so two days separated by steps subtend an angle , and the chord length is . Sun→Mon: they are step apart on the wrapped week (). , distance . Sun→Wed: steps apart. , distance . Since , Monday is indeed closer to Sunday than Wednesday is — the wrap-around now behaves correctly, unlike the naive codes where wrongly beat .

Recall Quick self-check ladder

On each line below, cover the part after the dash, answer aloud, then reveal.

  • One-hot distance between any two distinct categories —
  • Scaled value of the 90-lakh house in [50,75,60,90,55] —
  • Why we cyclic-encode day_of_week — so Sunday(6) stays adjacent to Monday(0), not 6 units away
  • Which features in the L4 pipeline get standard-scaled — only the continuous ones (price), not one-hot columns

Connections