我需要计算cohen's d以确定实验的效果大小。我可以使用的声音库中是否有任何实现?如果没有,那么什么是好的实施?
答案 0 :(得分:13)
在两组具有相同大小的特殊情况下,上述实施是正确的。基于Wikipedia和Robert Coe's article中找到的公式的更一般的解决方案是下面显示的第二种方法。请注意,分母是汇总标准差,通常只有在两组人口标准差相等的情况下才适用:
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)))
输出将是:
d由第一种方法= -0.559662109472 第一种方法不正确,因为nx不等于ny。 d由更一般的第二种方法= -0.572015604666
答案 1 :(得分:10)
自Python3.4起,您可以使用statistics
module来计算点差和平均指标。有了它,Cohen的d可以很容易地计算出来:
from statistics import mean, stdev
from math import sqrt
# test conditions
c0 = [2, 4, 7, 3, 7, 35, 8, 9]
c1 = [i * 2 for i in c0]
cohens_d = (mean(c0) - mean(c1)) / (sqrt((stdev(c0) ** 2 + stdev(c1) ** 2) / 2))
print(cohens_d)
输出:
-0.5567679522645598
所以我们观察到中等效果。
答案 2 :(得分:2)
在Python 2.7中,你可以使用numpy
和一些注意事项,正如我在调整Python 3.4中的Bengt答案时所发现的那样。
from __future__ import division
ddof=1
函数中指定与std
的方差的除法参数,即numpy.std(c0, ddof=1)
。 numpy的标准偏差默认行为除以n
,而ddof=1
则除以n-1
。代码
from __future__ import division #Ensure division returns float
from numpy import mean, std # version >= 1.7.1 && <= 1.9.1
from math import sqrt
import sys
def cohen_d(x,y):
return (mean(x) - mean(y)) / sqrt((std(x, ddof=1) ** 2 + std(y, ddof=1) ** 2) / 2.0)
if __name__ == "__main__":
# test conditions
c0 = [2, 4, 7, 3, 7, 35, 8, 9]
c1 = [i * 2 for i in c0]
print(cohen_d(c0,c1))
输出将是:
-0.556767952265