如何在 Python 中计算 cohen's d?

新手上路,请多包涵

我需要计算 cohen’s d 以确定实验的效果大小。我可以使用声音库中的任何实现吗?如果没有,什么是好的实施?

原文由 Bengt 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.9k
2 个回答

从 Python3.4 开始,您可以使用 statistics 模块 计算点差和平均指标。有了这个,科恩的 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

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

原文由 Bengt 发布,翻译遵循 CC BY-SA 3.0 许可协议

在两组大小相等的特殊情况下,上述实现是正确的。基于在 维基百科Robert Coe 的文章 中找到的公式的更通用的解决方案是下面显示的第二种方法。请注意,分母是合并标准差,通常仅当两组的总体标准差相等时才适用:

 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

原文由 skynaut 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题