Skip to content

ENH use log1p and expm1 in Yeo-Johnson transformation and its inverse #27868

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions sklearn/preprocessing/_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3304,27 +3304,32 @@ def _yeo_johnson_inverse_transform(self, x, lmbda):
"""Return inverse-transformed input x following Yeo-Johnson inverse
transform with parameter lambda.
"""
if lmbda == 1:
return x

x_inv = np.zeros_like(x)
pos = x >= 0

# when x >= 0
if abs(lmbda) < np.spacing(1.0):
x_inv[pos] = np.exp(x[pos]) - 1
x_inv[pos] = np.expm1(x[pos])
else: # lmbda != 0
x_inv[pos] = np.power(x[pos] * lmbda + 1, 1 / lmbda) - 1
x_inv[pos] = np.expm1(np.log1p(x[pos] * lmbda) / lmbda)

# when x < 0
if abs(lmbda - 2) > np.spacing(1.0):
x_inv[~pos] = 1 - np.power(-(2 - lmbda) * x[~pos] + 1, 1 / (2 - lmbda))
x_inv[~pos] = -np.expm1(np.log1p((lmbda - 2) * x[~pos]) / (2 - lmbda))
else: # lmbda == 2
x_inv[~pos] = 1 - np.exp(-x[~pos])
x_inv[~pos] = -np.expm1(-x[~pos])

return x_inv

def _yeo_johnson_transform(self, x, lmbda):
"""Return transformed input x following Yeo-Johnson transform with
parameter lambda.
"""
if lmbda == 1:
return x

out = np.zeros_like(x)
pos = x >= 0 # binary mask
Expand All @@ -3333,11 +3338,11 @@ def _yeo_johnson_transform(self, x, lmbda):
if abs(lmbda) < np.spacing(1.0):
out[pos] = np.log1p(x[pos])
else: # lmbda != 0
out[pos] = (np.power(x[pos] + 1, lmbda) - 1) / lmbda
out[pos] = np.expm1(lmbda * np.log1p(x[pos])) / lmbda

# when x < 0
if abs(lmbda - 2) > np.spacing(1.0):
out[~pos] = -(np.power(-x[~pos] + 1, 2 - lmbda) - 1) / (2 - lmbda)
out[~pos] = -np.expm1((2 - lmbda) * np.log1p(-x[~pos])) / (2 - lmbda)
else: # lmbda == 2
out[~pos] = -np.log1p(-x[~pos])

Expand Down