from numpy import std, mean, sqrt
#correct if the population S.D. is expected to be equal for the two groups.
def cohen_d(x,y):
nx = len(x)
ny = len(y)
dof = nx + ny - 2
return (mean(x) - mean(y)) / sqrt(((nx-1)*std(x, ddof=1) ** 2 + (ny-1)*std(y, ddof=1) ** 2) / dof)
#dummy data
x = [2,4,7,3,7,35,8,9]
y = [i*2 for i in x]
# extra element so that two group sizes are not equal.
x.append(10)
#correct only if nx=ny
d = (mean(x) - mean(y)) / sqrt((std(x, ddof=1) ** 2 + std(y, ddof=1) ** 2) / 2.0)
print ("d by the 1st method = " + str(d))
if (len(x) != len(y)):
print("The first method is incorrect because nx is not equal to ny.")
#correct for more general case including nx !=ny
print ("d by the more general 2nd method = " + str(cohen_d(x,y)))
在两组大小相等的特殊情况下,上述实现是正确的。基于Wikipedia和Robert Coe's article中的公式的更一般的解决方案是下面所示的第二种方法。注意分母是集合标准差,通常只有当两组的总体标准差相等时才适用:
输出为:
d按第1种方法=-0.559662109472 第一种方法不正确,因为nx不等于ny。 d采用更通用的第2种方法=-0.572015604666
在Python2.7中,可以使用
numpy
和一些注意事项,正如我在改编Python3.4中的Bengt答案时发现的那样。from __future__ import division
ddof=1
函数中使用std
指定方差的除法参数,即numpy.std(c0, ddof=1)
。numpy的标准偏差默认行为是除以n
,而使用ddof=1
则除以n-1
。代码
然后输出为:
从Python3.4开始,您可以使用^{} module 来计算扩展和平均度量。有了这个,科恩的d可以很容易地计算出来:
输出:
所以我们观察到一个中等效应。
相关问题 更多 >
编程相关推荐