【发布时间】:2013-08-03 00:57:43
【问题描述】:
pandas 中 R 的 scale 函数的有效等效项是什么?例如
newdf <- scale(df)
用熊猫写的?有没有使用transform 的优雅方式?
【问题讨论】:
-
对
pandas的一个不错的功能请求可能类似于R 的sweep函数。
pandas 中 R 的 scale 函数的有效等效项是什么?例如
newdf <- scale(df)
用熊猫写的?有没有使用transform 的优雅方式?
【问题讨论】:
pandas 的一个不错的功能请求可能类似于R 的sweep 函数。
缩放在机器学习任务中非常常见,因此在 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。
【讨论】:
我不知道 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))吗?
if c: x -= x.mean(); if sc: x /= np.sqrt(x.pow(2).sum().div(x.count() - 1))