本文介绍了在python中以scipy / numpy计算2D矩阵的z分数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

假设我拥有数组:

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

,我想计算每一行的z得分。我想出的解决方案是:

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])

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

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

此外,在使用具有欧式距离或欧式距离的分层聚类之前,对z分数进行数字化总是很好吗?有人可以讨论相对优点/缺点吗?

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?

谢谢。

推荐答案

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

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

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

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

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))

这篇关于在python中以scipy / numpy计算2D矩阵的z分数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 07:01