Implement a Yeo-Johnson Power Transformer with Grid Search
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement two helper functions and a column-wise transformer for the Yeo-Johnson power transform:
- `yeo_johnson(x, lmbda)` applies the transform with a fixed lambda.
- `yeo_johnson_log_likelihood(x, lmbda)` returns the profile log-likelihood of a lambda for a 1-D sample.
- `PowerTransformer(method, lambdas, standardize)` works column by column. `fit` learns one lambda per column from training data, and `transform` applies the stored parameters to any data.
The implementation must follow these rules:
- `yeo_johnson` is the standard Yeo-Johnson transform. For x ≥ 0 it computes `((x + 1)**λ - 1) / λ`, and uses `log1p(x)` at λ = 0. For x < 0 it computes `-((1 - x)**(2 - λ) - 1) / (2 - λ)`, and uses `-log1p(-x)` at λ = 2. NaN passes through.
- `yeo_johnson_log_likelihood` drops NaNs and returns `-n/2 · log(var(t)) + (λ - 1) · Σ sign(x) · log1p(|x|)`, where `t` is the transformed sample and `var` is the population variance. This matches `scipy.stats.yeojohnson_llf`.
- `fit` sets `lambdas_[j]` for each column to the first argmax of the log-likelihood over the sorted unique grid (default `np.linspace(-2, 2, 81)`), with NaNs ignored. A column with fewer than 2 distinct values gets `1.0`.
- With `method="log1p"`, every lambda is `0.0`. Negative values raise `ValueError` in both `fit` and `transform`.
- With `standardize=True`, `fit` stores `mean_` and `scale_` (the population standard deviation of the transformed training data, NaNs ignored) and `transform` applies them. A zero scale maps the output to `0.0`, and NaN stays NaN.
- A DataFrame input returns a DataFrame with the same index and columns. An `ndarray` input returns a `float64` ndarray. The input is never mutated.
Example:
```python
x = np.array([-1.0, 0.0, 3.0])
yeo_johnson(x, 0.0) # [-1.5, 0.0, log(4)]
yeo_johnson(x, 2.0) # [-log(2), 0.0, 7.5]
yeo_johnson(x, 1.0) # [-1.0, 0.0, 3.0]
```
```hint Mask by sign
Start from an output array full of NaN and fill the x ≥ 0 and x < 0 positions separately. Check what a NaN does in each comparison, and test your λ = 0 and λ = 2 branches against the example.
```
```hint The second likelihood term
The variance term alone rewards any lambda that squeezes the data together. Work out what the second term corrects for, and compute it from the original x values.
```
```hint Constant columns after standardizing
In floating point, the standard deviation of identical values can come out as a tiny positive number. Decide how `fit` recognizes a constant column so the zero-scale rule actually applies.
```
### Constraints & Assumptions
- `X` is 2-D with n rows and d numeric columns, given as a NumPy array or a pandas DataFrame.
- NaN can appear anywhere, in the training data and in data passed to `transform`.
- The default grid has 81 points from -2 to 2, a step of 0.05. A custom `lambdas` grid may be unsorted or contain repeats.
### What a Strong Answer Covers
- Both branches of the transform, the two log special cases, and NaN handling that keeps NaN out of both branches.
- A log-likelihood with the Jacobian term and population variance, and why that term makes different lambdas comparable.
- Lambda selection with the stated tie rule, plus the constant-column and `log1p` cases.
- Standardization parameters learned on training data only, including the zero-scale case.
- Output types that match the input, with the input left unmodified.
### Follow-up Questions
- Why would you replace the grid search with a continuous optimizer, and which one would you use?
- What numerical issues arise for large |x| or extreme λ, and how would you guard against them?
- How would this transformer fit into a cross-validated scikit-learn pipeline without leakage?
Overview: Implement the Yeo-Johnson power transform in NumPy and a column-wise transformer that picks one lambda per feature by grid search over the profile log-likelihood. It tests careful handling of NaNs, constant columns, standardization and leakage-free fit and transform.