Python 中不同样本量的卡方检验

Chi square test with different sample sizes in Python

我有两组数据如下图。每个数据集都有不同的长度

X_data1Y_data1(黑色合并数据)的长度为 40,而 X_data2Y_data2(红色)的长度为 18k。

我想对这两个数据进行如下卡方拟合优度检验

from scipy import stats
stats.chisquare(f_obs=Y_data1, f_exp=Y_data2)

但是我不能,因为矢量大小不一样,我收到一个错误。

~/opt/miniconda3/lib/python3.9/site-packages/scipy/stats/stats.py in chisquare(f_obs, f_exp, ddof, axis) 6850 6851 """ -> 6852 return power_divergence(f_obs, f_exp=f_exp, ddof=ddof, axis=axis, 6853 lambda_="pearson")
6854

~/opt/miniconda3/lib/python3.9/site-packages/scipy/stats/stats.py in power_divergence(f_obs, f_exp, ddof, axis, lambda_) 6676 if f_exp is not None: 6677 f_exp = np.asanyarray(f_exp) -> 6678 bshape = _broadcast_shapes(f_obs_float.shape, f_exp.shape) 6679 f_obs_float = _m_broadcast_to(f_obs_float, bshape) 6680 f_exp = _m_broadcast_to(f_exp, bshape)

~/opt/miniconda3/lib/python3.9/site-packages/scipy/stats/stats.py in _broadcast_shapes(shape1, shape2) 184 n = n1 185 else: --> 186 raise ValueError(f'shapes {shape1} and {shape2} could not be ' 187 'broadcast together') 188 shape.append(n)

ValueError: shapes (40,) and (18200,) could not be broadcast together

Python 有什么方法可以比较这两个数据吗?

除非 f_expf_obs 的长度相同,否则您无法执行此操作。您可以通过在 Y_data1 的 x-axis 上插入 Y_data2 来实现您的目标。您可以按如下方式进行:

from scipy.interpolate import InterpolatedUnivariateSpline 
spl = InterpolatedUnivariateSpline(X_data2, Y_data2)
new_Y_data2 = spl(X_data1)

由于 Y_data1new_Y_data2 现在的长度相同,您可以在 stats.chisquare 中使用它们,如下所示:

from scipy import stats
stats.chisquare(f_obs=Y_data1, f_exp=new_Y_data2)