【发布时间】:2014-02-27 05:46:50
【问题描述】:
我需要计算cohen's d 以确定实验的效果大小。我可以使用的声音库中是否有任何实现?如果没有,什么是好的实现?
【问题讨论】:
-
我很好奇您提出问题并立即回答...
-
我定期这样做,it's OK。我自己找到了答案,但我怀疑其他人可能能够提供更好的答案。所以让选票决定哪一个是。
标签: python python-3.x statistics
我需要计算cohen's d 以确定实验的效果大小。我可以使用的声音库中是否有任何实现?如果没有,什么是好的实现?
【问题讨论】:
标签: python python-3.x statistics
在两个组大小相等的特殊情况下,上述实现是正确的。基于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)))
输出将是:
第一种方法 = -0.559662109472 第一种方法不正确,因为 nx 不等于 ny。 d 通过更通用的第二种方法 = -0.572015604666
【讨论】:
从 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
所以我们观察到中等效果。
【讨论】:
在 Python 2.7 中,您可以使用 numpy 并注意一些注意事项,正如我在改编 Bengt 从 Python 3.4 的答案时发现的那样。
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
【讨论】:
std 函数与 ddof 参数一起存在,并且在 1.7.1 和当前 1.9.1 版本中需要用“-1”覆盖默认值。