Python - 卡方检验

卡方检验是一种统计方法,用于确定两个分类变量之间是否存在显著相关性。这两个变量应来自同一人群,并且应具有分类性,如是/否、男/女、红/绿等。例如,我们可以建立一个数据集,观察人们的冰淇淋购买模式,并尝试将一个人的性别与他们喜欢的冰淇淋口味联系起来。如果发现相关性,我们可以通过了解访问人数的性别来规划合适的口味库存。

我们使用 numpy 库中的各种函数进行卡方检验。

from scipy import stats import numpy as np import matplotlib.pyplot as plt x = np.linspace(0, 10, 100) fig,ax = plt.subplots(1,1) linestyles = [':', '--', '-.', '-'] deg_of_freedom = [1, 4, 7, 6] for df, ls in zip(deg_of_freedom, linestyles): ax.plot(x, stats.chi2.pdf(x, df), linestyle=ls) plt.xlim(0, 10) plt.ylim(0, 0.4) plt.xlabel('Value') plt.ylabel('Frequency') plt.title('Chi-Square Distribution') plt.legend() plt.show()

输出如下 −

chisquare.png