我有两个数组。x是自变量,counts是x出现次数的数量,就像一个直方图。我知道可以通过定义一个函数来计算平均值:
def mean(x,counts):
return np.sum(x*counts) / np.sum(counts)
有没有一般的函数可以从由x和counts定义的分布中计算每个时刻?我还想计算方差。
我有两个数组。x是自变量,counts是x出现次数的数量,就像一个直方图。我知道可以通过定义一个函数来计算平均值:
def mean(x,counts):
return np.sum(x*counts) / np.sum(counts)
有没有一般的函数可以从由x和counts定义的分布中计算每个时刻?我还想计算方差。
moment
函数来自于scipy
。它可以计算数据的第n个中心矩。
您也可以定义自己的函数,可能看起来像这样:
def nmoment(x, counts, c, n):
return np.sum(counts*(x-c)**n) / np.sum(counts)
c
代表取力矩的点,n代表阶数。因此,要计算方差可以使用nmoment(x, counts, np.average(x, weights=counts), 2)
。请保留HTML标签。counts
是什么?难道moment不应该是np.mean((x-c)^n)
吗? - wsdzbmimport scipy as sp
from scipy import stats
stats.moment(counts, moment = 2) #variance
stats.moment返回第n个中心矩。
np.average
、np.std
、np.var
等。
mean
也可以写成np.average(x, weights=counts)
。 - Alex Riley