binom_test 可用于检查单个 Erdos-Renyi 图是否具有合理的参数边数。但您是在询问一组结果,以及这些结果是否具有正确的分布。
为此,您可以使用拟合优度检验,将经验分布与假设的零分布进行比较。存在各种 GoF 测试,但您需要一种用于离散数据的测试。 statsmodels 实现了 Χ2 平方检验以验证拟合优度(docs)。
我们需要一个零假设来使用这种类型的检验,这是一个二项分布:E-R 图有n*(n-1)/2 可能的边,它们被添加
独立概率p。很明显,这个分布是二项式的,所以你真正要做的就是检查随机数生成器是否正常。
无论如何,我们的空模型是边的分布为 ~Binom(n_edge, p),预期边数为 p * n*(n-1)/2。
这是应用测试的代码。
import networkx as nx
from statsmodels.stats import gof
from scipy import stats
# generate some graphs and measure edge count
p = 0.1
n = 100
n_edge = n*(n-1)/2
l = []
for i in xrange(1000):
g = nx.gnp_random_graph(n=n, p=p)
l.append(len(g.edges()))
## we use a chi square test of goodness of fit for the measured edge counts
# chi square: null hypothesis is that data l comes from the binom distribution.
# so if pval is > alpha we do not reject the null.
alpha = 0.001
chi2, pval, sig_test, msg = gof.gof_chisquare_discrete(stats.distributions.binom, (n_edge, p,), l, alpha, msg="Binom ")
print msg
print "\tpval: {:.3f}".format(pval)
print "\tgood fit to binom(N, p)? {}".format(pval > alpha)
这会产生如下输出:
>>> chisquare - test for Binom at arg = (4950, 0.1) with pval = 0.8129512780114826
>>> pval: 0.813
>>> good fit to binom(N, p)? True
所以边的分布确实是二项式的。