Skip to content

Instantly share code, notes, and snippets.

@jcheong0428
Last active December 20, 2021 03:31
Show Gist options
  • Save jcheong0428/4e11b983ac1d24b967321332fc281ef5 to your computer and use it in GitHub Desktop.
Save jcheong0428/4e11b983ac1d24b967321332fc281ef5 to your computer and use it in GitHub Desktop.
sim_mat4.py
"""Nonparametric permutation testing Monte Carlo"""
np.random.seed(0)
rhos = []
n_iter = 5000
true_rho, _ = stats.spearmanr(upper(m1), upper(m2))
# matrix permutation, shuffle the groups
m_ids = list(m1.columns)
m2_v = upper(m2)
for iter in range(n_iter):
np.random.shuffle(m_ids) # shuffle list
r, _ = stats.spearmanr(upper(m1.loc[m_ids, m_ids]), m2_v)
rhos.append(r)
perm_p = ((np.sum(np.abs(true_rho) <= np.abs(rhos)))+1)/(n_iter+1) # two-tailed test
f,ax = plt.subplots()
plt.hist(rhos,bins=20)
ax.axvline(true_rho, color = 'r', linestyle='--')
ax.set(title=f"Permuted p: {perm_p:.3f}", ylabel="counts", xlabel="rho")
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment