如何在Python中计算cohen的d?

2024-09-28 22:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要计算cohen's d来确定实验的效果大小。我可以用一个声音库来实现吗?如果不是,那么什么才是一个好的实现呢?


Tags: 声音效果cohen
3条回答

在两组大小相等的特殊情况下,上述实现是正确的。基于WikipediaRobert 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按第1种方法=-0.559662109472 第一种方法不正确,因为nx不等于ny。 d采用更通用的第2种方法=-0.572015604666

在Python2.7中,可以使用numpy和一些注意事项,正如我在改编Python3.4中的Bengt答案时发现的那样。

  1. 确保除法始终返回浮点值:from __future__ import division
  2. 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

从Python3.4开始,您可以使用^{} module来计算扩展和平均度量。有了这个,科恩的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

所以我们观察到一个中等效应。

相关问题 更多 >