gpt4 book ai didi

python - R.scale() 和 sklearn.preprocessing.scale() 的区别

转载 作者:太空狗 更新时间:2023-10-30 01:07:56 27 4
gpt4 key购买 nike

我目前正在将我的数据分析从 R 转移到 Python。在 R 中缩放数据集时,我会使用 R.scale(),据我所知,它会执行以下操作:(x-mean(x))/sd(x)

为了替换该函数,我尝试使用 sklearn.preprocessing.scale()。根据我对描述的理解,它做同样的事情。尽管如此,我运行了一个小测试文件并发现,这两种方法都有不同的返回值。显然标准差不一样...有人能解释为什么标准差彼此“偏离”吗?

MWE:

# import packages
from sklearn import preprocessing
import numpy
import rpy2.robjects.numpy2ri
from rpy2.robjects.packages import importr
rpy2.robjects.numpy2ri.activate()
# Set up R namespaces
R = rpy2.robjects.r


np1 = numpy.array([[1.0,2.0],[3.0,1.0]])
print "Numpy-array:"
print np1

print "Scaled numpy array through R.scale()"
print R.scale(np1)
print "-------"
print "Scaled numpy array through preprocessing.scale()"
print preprocessing.scale(np1, axis = 0, with_mean = True, with_std = True)
scaler = preprocessing.StandardScaler()
scaler.fit(np1)
print "Mean of preprocessing.scale():"
print scaler.mean_
print "Std of preprocessing.scale():"
print scaler.std_

输出: Output generated by the MWE

最佳答案

这似乎与标准偏差的计算方式有关。

>>> import numpy as np
>>> a = np.array([[1, 2],[3, 1]])
>>> np.std(a, axis=0)
array([ 1. , 0.5])
>>> np.std(a, axis=0, ddof=1)
array([ 1.41421356, 0.70710678])

来自 numpy.std documentation ,

ddof : int, optional

Means Delta Degrees of Freedom. The divisor used in calculations is N - ddof, where N represents the number of elements. By default ddof is zero.

显然,R.scale() 使用 ddof=1,但是 sklearn.preprocessing.StandardScaler() 使用 ddof= 0

编辑:(解释如何使用备用 ddof)

在不访问 StandardScaler() 对象本身的变量的情况下,似乎没有直接的方法来使用替代 ddof 计算 std。

sc = StandardScaler()
sc.fit(data)
# Now, sc.mean_ and sc.std_ are the mean and standard deviation of the data
# Replace the sc.std_ value using std calculated using numpy
sc.std_ = numpy.std(data, axis=0, ddof=1)

关于python - R.scale() 和 sklearn.preprocessing.scale() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27296387/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com