如何在Python中使用零偏度日志转换 [英] How to use Zero-skewness log transform in Python
问题描述
如何在Python中进行零偏度日志转换?
How to do zero-skewness log transform in Python?
例如,在Stata中,它是在 lnskew0
中实现的(请参见 https://www.stata.com/manuals13/rlnskew0.pdf ).
For example in Stata it is implemented in lnskew0
(see https://www.stata.com/manuals13/rlnskew0.pdf).
我没有在Python中找到实现.有人知道实现吗?
I didn't find an implementation in Python. Is anyone aware of an implementation?
否则,首先尝试的是:
from scipy.stats import skew
import numpy as np
from scipy.optimize import root_scalar
def lnskew0(x):
def skew_ln(k):
return skew(np.log(x - k))
res = root_scalar(
skew_ln,
bracket=[-x.min(), x.max()*0.99999],
method='bisect'
)
return np.log(x - res.root)
在仅带正数的 numpy
数组上工作正常.Stata的 Inskew0
如何实现它也可以与负数一起使用?
Works fine on numpy
arrays with only positive numbers. How is Stata's lnskew0
implemented that it works with negative numbers as well?
推荐答案
我再次尝试了一下,使其也可以使用负数:
I gave it another try so that it works with negative numbers as well:
from scipy.stats import skew
import numpy as np
from scipy.optimize import root_scalar
def lnskew0(x):
x0 = x + 1
def skew_ln_pos(k):
with np.errstate(all='ignore'):
return skew(np.log(x0 - k))
res_pos = root_scalar(
skew_ln_pos,
bracket=[-150, 150],
method='bisect'
)
def skew_ln_neg(k):
with np.errstate(all='ignore'):
return skew(np.log(-x0 - k))
res_neg = root_scalar(
skew_ln_neg,
bracket=[-150, 150],
method='bisect'
)
res = (res_pos.root - 1, res_neg.root + 1)
lnskew0_res = (
np.log(x - res[0]),
np.log(-x - res[1])
)
whichmin = np.nanargmin([abs(skew(x)) for x in lnskew0_res])
return lnskew0_res[whichmin]
注意:它仍然有一个问题.需要手动选择 root_scalar
的括号.
Note: It still has one issue. The bracket of the root_scalar
needs to be choosen manually.
这篇关于如何在Python中使用零偏度日志转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!