首页 > 解决方案 > 是否有与 R 中的 powertransform 等效的 Python 函数

问题描述

R中是否有等效于powertransform的python函数?

这是在 R 中:powerTransform(X, family = "bcnPower")

我知道并使用了以下功能/包:


    from scipy.stats import skew,boxcox_normmax
    from scipy.special import boxcox, inv_boxcox
    from  scipy.stats import yeojohnson_normmax
    from scipy.stats import boxcox_llf
    from sklearn.preprocessing import power_transform
    from sklearn.preprocessing import PowerTransformer

我正在尝试使用 python 转换列表(向量)。


from scipy.stats import boxcox_normmax
vec =""" 4  5  5  6  5  5  3  7  7  6  5  5  8  8  3  2  3  5 10  6  7  5  2  3  1  3  4  4  5  2  5  4  5  6  5  4  2  6  3 10  4  7  5  2
7  7  3 11  5  4  4  2  2  4  6  3  4  5  6  5  8  7  4  3  5  7  3  3  6  5  3  6  6  3  9  7  9  7  2  4  2  6  4  2  5  3  4  2
7  3  7  5  5  1  5  7  1  4  5  7"""
vec = list(map(int,vec.split()))
print("min  val :",min(vec))
print(boxcox_normmax(vec,method="all"))

最小值:1

[0.62926218 0.58382934]


powerTransform(vec, family="bcnPower")

估计的转换功率,λ [1] 0.5831778

位置 gamma 固定在其下限 [1] 0.1

我想要给出相同输出参数和结果的python函数。

如果没有这样的功能,我可以实现这样的功能吗?如何实现?

标签: pythonrscikit-learnscipytransformation

解决方案


在 Python 中:

from sklearn.preprocessing import PowerTransformer
import pandas as pd
vec = """ 4  5  5  6  5  5  3  7  7  6  5  5  8  8  3  2  3  5 10  6  7  5  2  3  1  3  4  4  5  2  5  4  5  6  5  4  2  6  3 10  4  7  5  2
7  7  3 11  5  4  4  2  2  4  6  3  4  5  6  5  8  7  4  3  5  7  3  3  6  5  3  6  6  3  9  7  9  7  2  4  2  6  4  2  5  3  4  2
7  3  7  5  5  1  5  7  1  4  5  7"""
vec = list(map(int, vec.split()))
pt = PowerTransformer(method='box-cox', standardize=False)
data = pd.DataFrame(vec)
pt.fit(data)
print('Lambda =',pt.lambdas_)
print('First 10 elements:',pt.transform(data)[:10].reshape(1, -1))

#Lambda = [0.58382935]
#First 10 elements: [[2.13498738 2.67039083 2.67039083 3.16269828 2.67039083 2.67039083
#  1.54007639 3.62183527 3.62183527 3.16269828]]

power_transform如果您设置standardize=False.

在 R 中:

p = powerTransform(vec, family = "bcPower")
p$lambda
#      vec 
#0.5838294 
bcPower(vec, lambda=p$lambda)[1:10]
# [1] 2.134987 2.670391 2.670391 3.162698 2.670391 2.670391 1.540076
# [8] 3.621836 3.621836 3.162698

推荐阅读