Apply the Yeo-Johnson power transform for a given lambda

Why it matters Power transforms like Yeo-Johnson are a standard preprocessing step for skewed income, spend and count features before linear models.

Yeo-Johnson makes skewed data more Gaussian like Box-Cox does, but it also works for zero and negative values.

Write yeo_johnson(x, lam). x is a 1D sequence, lam a float. Return a float array where for x >= 0: ((x + 1)^lam - 1) / lam, or log(1 + x) when lam is 0; and for x < 0: -((1 - x)^(2 - lam) - 1) / (2 - lam), or -log(1 - x) when lam is 2. Treat |lam| < 1e-12 as 0 and |lam - 2| < 1e-12 as 2.

Signaturedef yeo_johnson(x, lam)

Example

x [-1, 0, 1, 3], lam 0.5 gives [-1.21895, 0.0, 0.828427, 2.0].

Understand the idea

Many real features are skewed: most people spend a little, a few spend a lot. A power transform bends the number line so that big values are pulled in and the shape looks closer to a bell curve. Yeo-Johnson is the version that is happy with zero and negative inputs.

Worked example with lam = 0.5: x = 3 gives ((3 + 1)^0.5 - 1) / 0.5 = (2 - 1) / 0.5 = 2. x = 0 gives 0. x = -1 uses the mirrored branch: -((1 + 1)^1.5 - 1) / 1.5 = -(2.828 - 1) / 1.5 = -1.219.

Rule: for x >= 0, ((x + 1)^lam - 1) / lam (log(1 + x) if lam = 0). For x < 0, -((1 - x)^(2 - lam) - 1) / (2 - lam) (-log(1 - x) if lam = 2).

lam = 1 leaves data unchanged, lam below 1 squashes a right tail. In practice lam is chosen by maximum likelihood on training data and then reused on test data.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: exampleyeo_johnson([-1, 0, 1, 3], 0.5)
  • Sample 2: lambda 0yeo_johnson([-2, 0, 2, 9], 0.0)
  • Test 3: lambda 2yeo_johnson([-3, -0.5, 1], 2.0)
  • Test 4: lambda 1 identityyeo_johnson([-4, -1, 0, 2.5], 1.0)