2.1.9 · D4Data Preprocessing & Feature Engineering

Exercises — Log and power transformations

2,786 words13 min readBack to topic

This is a self-test page for the parent topic (2.1.9). Every problem below has a fully worked solution hidden inside a collapsible [!recall]- callout — try first, then reveal. Problems climb from L1 Recognition (spot the right tool) to L5 Mastery (combine everything into a pipeline decision).

Before we start, a few pieces of notation used throughout (nothing here is assumed):

The picture below shows what all these transforms have in common: they take a long right tail and squeeze it while stretching the small values apart.

Figure — Log and power transformations

Look at the red log curve: near it climbs steeply (small values get spread apart), and for large it flattens (big values get squeezed together). That single shape is the engine behind every problem on this page.


Level 1 — Recognition

You have a feature temp_anomaly with values [-8.2, -3.1, 0.5, 2.3, 7.8]. A teammate writes np.log(temp_anomaly). What breaks, and which of {Log, Box-Cox, Yeo-Johnson} is the only valid choice?

Recall Solution

is only defined for strictly positive inputs. Here and are negative, and of a negative number is undefined (you get NaN). Box-Cox also requires , so it is out too. The only tool that legally accepts negatives is Yeo-Johnson — it has a separate branch for . See 2.1.08-Handling-Outliers for the sibling problem of extreme values.

Answer: Yeo-Johnson.

L1.2 — Name the

Match each Box-Cox to the plain-English transform it equals: .

Recall Solution

Plug into (with meaning ):

  • → essentially no transform (linear shift).
  • square root shape.
  • log.
  • reciprocal shape.

L1.3 — Why does Box-Cox become log at ?

The formula has a in the denominator — so at you divide by zero. Yet the definition says it "equals " there. Show why by taking the limit .

Recall Solution

At the top is and the bottom is : a form. That's exactly the case L'Hôpital's rule was built for — when top and bottom both vanish, the ratio's limit equals the ratio of their derivatives (with respect to ).

  • Derivative of the top w.r.t. : write , whose derivative is .
  • Derivative of the bottom w.r.t. : just .

So That is why the and the are in the formula: they glue the power family smoothly onto the log at , leaving no gap. Without them the curve would jump.


Level 2 — Application

L2.1 — Log10 of housing prices

Compute for . Round to 2 decimals.

Recall Solution

. Answer: . (This is why log compresses: a quarter-million becomes a number near 5.)

L2.2 — Box-Cox by hand

Apply Box-Cox with to . Formula: .

Recall Solution

Rewrite . Now . So . Answer: . (The parent note's used a slightly rounded intermediate; the exact value is .)

L2.3 — Yeo-Johnson on a negative value

Apply Yeo-Johnson with to . For :

Recall Solution

Here and . . . Answer: .

L2.4 — The forgotten edge case: Yeo-Johnson at ,

The formula in L2.3 divides by . What happens at , and what does the transform become for a negative there? Evaluate it for .

Recall Solution

At the denominator — division by zero, another gap, exactly like Box-Cox at . Taking the limit (same L'Hôpital move) collapses the negative branch to This is the fourth line of the full Yeo-Johnson definition, the mirror-image partner of the log case. For : . Answer: at the negative branch is ; for this gives .


Level 3 — Analysis

L3.1 — Log vs. sqrt: which is gentler?

Data [1, 4, 100] is right-skewed. Compute the ratio (max − min) after vs after . Which compresses the tail more, and why might "more" be too much?

Recall Solution
  • : → spread .
  • : → spread . Log compresses more (spread vs ). But "more" isn't always better: over-compressing can flatten real structure the model needs. When skew is only moderate, preserves more relative differences — hence the parent's rule "moderately skewed → ". Answer: log compresses more; use when you don't want that much bending.

L3.2 — Reading a skewness table

Given the candidate scan below, pick and justify.

Recall Solution

We want skewness closest to (most symmetric). → smallest absolute value is at . But note gives (still small) and is far more interpretable (it's plain log). In practice you'd interpolate: the optimum sits between and , near where skewness crosses zero. Answer: optimum near ; among the listed values, is most symmetric.


Level 4 — Synthesis

L4.1 — Round-trip a log prediction

You trained on -price. The model predicts . What is the raw-dollar point prediction before any correction?

Recall Solution

Inverse of natural log is : . . Answer: \hat y \approx \242{,}801$.

L4.2 — Jensen bias correction

Continuing L4.1: residual variance in log-space is . Apply the bias correction . By what percentage does the corrected mean exceed the naive point estimate? And why is the factor ?

Recall Solution

Where the factor comes from. In log-space the residual is a symmetric bell (a normal) with mean and variance . The dollar prediction is , so is log-normal. We want its average, . Look at the figure: is a curved-up (convex) function. Jensen's inequality says that for a convex curve, the average of the curve sits above the curve of the average — pushing bumps up more than dips pull down. So ; the naive under-shoots. The exact gap for a normal is the standard result so the correction factor over the naive estimate is — bigger variance, bigger upward push, exactly as the convex picture predicts.

Figure — Log and power transformations

The number. Correction factor . So the corrected mean is larger than the naive point estimate. Numerically: 242801 \times 1.08329 = \263{,}028+8.33%\approx $263{,}028$.**

L4.3 — Invert Box-Cox

A Box-Cox model () outputs . Recover using .

Recall Solution

. Answer: . (Check forward: . ✓)


Level 5 — Mastery

L5.1 — Design a leak-free pipeline

You have income (all positive, right-skewed) as target and a train/test split. Order these into a correct, leak-free sequence, and state where is learned: {transform test, split, learn λ on train, transform train, fit model, inverse-transform predictions}.

Recall Solution

Correct order:

  1. Split into train / test.
  2. Learn on train only — via MLE (maximum likelihood estimation: pick the under which the training data looks most normal; scipy.stats.boxcox does this). This is the one place a parameter is fit.
  3. Transform train with that .
  4. Fit model on transformed train.
  5. Transform test using the same (never refit).
  6. Inverse-transform predictions back to dollars (with Jensen correction if reporting means).

The leak everyone fears is computing on all data before splitting — that lets the test distribution whisper into training. Learning on train only is correct, not a mistake. Mirrors the fit-on-train rule from 2.1.05-Feature-Scaling.

L5.2 — Transform or switch models?

Your only model option becomes a decision tree. Your teammate still wants to Box-Cox the features "for normality." Should you? Explain in one line what trees care about.

Recall Solution

No — skip it for pure tree models. Trees split on thresholds ("is ?"), which depend only on the rank order of values. Any monotonic transform (log, Box-Cox with the ranks preserved) leaves every possible split point equivalent, so the tree's decisions are unchanged. Transforms matter for distance/linearity-based models, not rank-based ones. (Contrast with 2.2.03-Polynomial-Features, which do change what trees and linear models can express.) Answer: don't transform for a lone decision tree — no benefit.

L5.3 — Choose the transform, end to end

A feature is a proportion , e.g. click-through rate, and you're feeding a linear model. Log? Box-Cox? Something else? Transform .

Recall Solution

Neither log nor Box-Cox is ideal: they don't respect the ceiling at . For proportions use the logit: , which maps onto the whole real line — exactly what a linear model wants. For : . Answer: use logit; .


Recall Self-test checklist (reveal to grade yourself)

Legal transform for negatives ::: Yeo-Johnson (log & Box-Cox need ) Why Box-Cox = log at ::: L'Hôpital limit of gives ::: Box-Cox on ::: Yeo-Johnson on ::: Yeo-Johnson , ::: Inverse-log of ::: \approx \242{,}801e^{\sigma^2/2}\sigma^2=0.16+8.33%\approx $263{,}028e^{\sigma^2/2}e^Ze^{\mu}\lambda=0.5x'=6x=16\log(1+x)x=0\lambda(0.2)\approx -1.386$