在 Python 中的 scipy/numpy 中计算 2D 矩阵的 z 分数

发布于 2024-09-04 16:01:11 字数 394 浏览 0 评论 0原文

如何在 Python 中计算矩阵的 z 分数?

假设我有数组:

a = array([[   1,    2,    3],
           [  30,   35,   36],
           [2000, 6000, 8000]])

并且我想计算每行的 z 分数。我想出的解决方案是:

array([zs(item) for item in a])

其中 zs 位于 scipy.stats.stats 中。有没有更好的内置矢量化方法来做到这一点?

另外,在使用欧几里德距离或塞几里德距离的层次聚类之前对数字进行 z 评分总是好的吗?有人可以讨论相对优点/缺点吗?

谢谢。

How can I compute the z-score for matrices in Python?

Suppose I have the array:

a = array([[   1,    2,    3],
           [  30,   35,   36],
           [2000, 6000, 8000]])

and I want to compute the z-score for each row. The solution I came up with is:

array([zs(item) for item in a])

where zs is in scipy.stats.stats. Is there a better built-in vectorized way to do this?

Also, is it always good to z-score numbers before using hierarchical clustering with euclidean or seuclidean distance? Can anyone discuss the relative advantages/disadvantages?

thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

夜访吸血鬼 2024-09-11 16:01:11

scipy.stats.stats.zs 的定义如下:

def zs(a):
    mu = mean(a,None)
    sigma = samplestd(a)
    return (array(a)-mu)/sigma

因此,要将其扩展为在 ndarray 的给定轴上工作,您可以这样做:

import numpy as np
import scipy.stats.stats as sss
def my_zs(a,axis=-1):
    b=np.array(a).swapaxes(axis,-1)    
    mu = np.mean(b,axis=-1)[...,np.newaxis]
    sigma = sss.samplestd(b,axis=-1)[...,np.newaxis]
    return (b-mu)/sigma


a = np.array([[   1,    2,    3],
           [  30,   35,   36],
           [2000, 6000, 8000]])    
result=np.array([sss.zs(item) for item in a])

my_result=my_zs(a)
print(my_result)
# [[-1.22474487  0.          1.22474487]
#  [-1.3970014   0.50800051  0.88900089]
#  [-1.33630621  0.26726124  1.06904497]]
assert(np.allclose(result,my_result))

scipy.stats.stats.zs is defined like this:

def zs(a):
    mu = mean(a,None)
    sigma = samplestd(a)
    return (array(a)-mu)/sigma

So to extend it to work on a given axis of an ndarray, you could do this:

import numpy as np
import scipy.stats.stats as sss
def my_zs(a,axis=-1):
    b=np.array(a).swapaxes(axis,-1)    
    mu = np.mean(b,axis=-1)[...,np.newaxis]
    sigma = sss.samplestd(b,axis=-1)[...,np.newaxis]
    return (b-mu)/sigma


a = np.array([[   1,    2,    3],
           [  30,   35,   36],
           [2000, 6000, 8000]])    
result=np.array([sss.zs(item) for item in a])

my_result=my_zs(a)
print(my_result)
# [[-1.22474487  0.          1.22474487]
#  [-1.3970014   0.50800051  0.88900089]
#  [-1.33630621  0.26726124  1.06904497]]
assert(np.allclose(result,my_result))
所谓喜欢 2024-09-11 16:01:11

下一个版本中提供的 scipy 新 zscore 采用任意数组维度

http://projects.scipy .org/scipy/changeset/6169

the new zscore of scipy, available in the next release takes arbitrary array dimension

http://projects.scipy.org/scipy/changeset/6169

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文