Skip to content

Instantly share code, notes, and snippets.

@ugo-nama-kun
Last active September 15, 2021 07:37
Show Gist options
  • Save ugo-nama-kun/49e40adc24be0c4c1177c1ea7c0b3130 to your computer and use it in GitHub Desktop.
Save ugo-nama-kun/49e40adc24be0c4c1177c1ea7c0b3130 to your computer and use it in GitHub Desktop.
【統計】Cohen's d の計算方法
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)
@ugo-nama-kun
Copy link
Author

Picked-up from : https://stackoverflow.com/questions/21532471/how-to-calculate-cohens-d-in-python
The detail is explained in Wikipedia: https://en.wikipedia.org/wiki/Effect_size#Cohen's_d

#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)))

And a nutshell:
Screen Shot 2021-09-06 at 15 25 09

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment