【问题标题】:implementing R scale function in pandas in Python?在 Python 中的 pandas 中实现 R 缩放函数?
【发布时间】:2013-08-03 00:57:43
【问题描述】:

pandas 中 R 的 scale 函数的有效等效项是什么?例如

newdf <- scale(df)

用熊猫写的?有没有使用transform 的优雅方式?

【问题讨论】:

标签: python numpy pandas


【解决方案1】:

缩放在机器学习任务中非常常见,因此在 scikit-learn 的 preprocessing 模块中实现。您可以将 pandas DataFrame 传递给它的 scale 方法。

唯一的“问题”是返回的对象不再是DataFrame,而是numpy数组;如果你想将它传递给机器学习模型(例如 SVM 或逻辑回归),这通常不是一个真正的问题。如果您想保留 DataFrame,则需要一些解决方法:

from sklearn.preprocessing import scale
from pandas import DataFrame

newdf = DataFrame(scale(df), index=df.index, columns=df.columns)

另见here

【讨论】:

    【解决方案2】:

    我不知道 R,但从阅读文档看来,下面的方法可以解决问题(尽管以一种不太通用的方式)

    def scale(y, c=True, sc=True):
        x = y.copy()
    
        if c:
            x -= x.mean()
        if sc and c:
            x /= x.std()
        elif sc:
            x /= np.sqrt(x.pow(2).sum().div(x.count() - 1))
        return x
    

    对于更通用的版本,您可能需要进行一些类型/长度检查。

    编辑:在elif sc: 子句中添加了对分母的解释

    来自 R 文档:

     ... If ‘scale’ is
     ‘TRUE’ then scaling is done by dividing the (centered) columns of
     ‘x’ by their standard deviations if ‘center’ is ‘TRUE’, and the
     root mean square otherwise.  If ‘scale’ is ‘FALSE’, no scaling is
     done.
    
     The root-mean-square for a (possibly centered) column is defined
     as sqrt(sum(x^2)/(n-1)), where x is a vector of the non-missing
     values and n is the number of non-missing values.  In the case
     ‘center = TRUE’, this is the same as the standard deviation, but
     in general it is not.
    

    np.sqrt(x.pow(2).sum().div(x.count() - 1)) 行使用以下定义计算均方根:首先对 x 求平方(pow 方法),然后沿行求和,然后除以每列中的非 NaN 计数(@ 987654328@方法)。

    附带说明一下,我之所以不只是在居中后简单地计算 RMS,是因为 std 方法调用 bottleneck 以便在您想要计算标准偏差的特殊情况下更快地计算该表达式而不是更一般的 RMS。

    您可以改为在居中后计算 RMS,这可能值得一个基准测试,因为现在我正在写这篇文章,我实际上并不确定哪个更快,我还没有对其进行基准测试。

    【讨论】:

    • 你能解释一下/= np.sqrt(x.pow(2).sum().div(x.count() - 1))吗?
    • 根据R docs计算的均方根如果居中则为标准差,所以可以去掉中间的if语句,留下if c: x -= x.mean(); if sc: x /= np.sqrt(x.pow(2).sum().div(x.count() - 1))
    • @Closed 当然。我是这样评论的。
    • 糟糕!我误读了第一次。继续,好先生:)。
    • 这不完全是 R 的规模。 R'scale 采用逐行均值和逐行 std.deviations 但您采用整个数组的标准差和整个数组的均值。
    猜你喜欢
    • 2022-01-13
    • 2012-04-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    相关资源
    最近更新 更多