多尺度图相关 (MGC)#
通过 scipy.stats.multiscale_graphcorr
,我们可以测试高维和非线性数据的独立性。在开始之前,让我们导入一些有用的包
>>> import numpy as np
>>> import matplotlib.pyplot as plt; plt.style.use('classic')
>>> from scipy.stats import multiscale_graphcorr
让我们使用一个自定义绘图函数来绘制数据关系
>>> def mgc_plot(x, y, sim_name, mgc_dict=None, only_viz=False,
... only_mgc=False):
... """Plot sim and MGC-plot"""
... if not only_mgc:
... # simulation
... plt.figure(figsize=(8, 8))
... ax = plt.gca()
... ax.set_title(sim_name + " Simulation", fontsize=20)
... ax.scatter(x, y)
... ax.set_xlabel('X', fontsize=15)
... ax.set_ylabel('Y', fontsize=15)
... ax.axis('equal')
... ax.tick_params(axis="x", labelsize=15)
... ax.tick_params(axis="y", labelsize=15)
... plt.show()
... if not only_viz:
... # local correlation map
... plt.figure(figsize=(8,8))
... ax = plt.gca()
... mgc_map = mgc_dict["mgc_map"]
... # draw heatmap
... ax.set_title("Local Correlation Map", fontsize=20)
... im = ax.imshow(mgc_map, cmap='YlGnBu')
... # colorbar
... cbar = ax.figure.colorbar(im, ax=ax)
... cbar.ax.set_ylabel("", rotation=-90, va="bottom")
... ax.invert_yaxis()
... # Turn spines off and create white grid.
... for edge, spine in ax.spines.items():
... spine.set_visible(False)
... # optimal scale
... opt_scale = mgc_dict["opt_scale"]
... ax.scatter(opt_scale[0], opt_scale[1],
... marker='X', s=200, color='red')
... # other formatting
... ax.tick_params(bottom="off", left="off")
... ax.set_xlabel('#Neighbors for X', fontsize=15)
... ax.set_ylabel('#Neighbors for Y', fontsize=15)
... ax.tick_params(axis="x", labelsize=15)
... ax.tick_params(axis="y", labelsize=15)
... ax.set_xlim(0, 100)
... ax.set_ylim(0, 100)
... plt.show()
让我们先看一些线性数据
>>> rng = np.random.default_rng()
>>> x = np.linspace(-1, 1, num=100)
>>> y = x + 0.3 * rng.random(x.size)
模拟关系可在下方绘制
>>> mgc_plot(x, y, "Linear", only_viz=True)

现在,我们可以在下方看到测试统计量、p值和MGC图的可视化。最佳尺度在图上显示为一个红色“x”
>>> stat, pvalue, mgc_dict = multiscale_graphcorr(x, y)
>>> print("MGC test statistic: ", round(stat, 1))
MGC test statistic: 1.0
>>> print("P-value: ", round(pvalue, 1))
P-value: 0.0
>>> mgc_plot(x, y, "Linear", mgc_dict, only_mgc=True)

由此可见,MGC能够确定输入数据矩阵之间的关系,因为p值非常低,并且MGC测试统计量相对较高。MGC图表示**强线性关系**。直观地说,这是因为拥有更多邻居将有助于识别\(x\)和\(y\)之间的线性关系。在这种情况下,最佳尺度**等同于全局尺度**,在图上用红点标记。
非线性数据集也可以进行相同的操作。以下\(x\)和\(y\)数组来自非线性模拟
>>> unif = np.array(rng.uniform(0, 5, size=100))
>>> x = unif * np.cos(np.pi * unif)
>>> y = unif * np.sin(np.pi * unif) + 0.4 * rng.random(x.size)
模拟关系可在下方绘制
>>> mgc_plot(x, y, "Spiral", only_viz=True)

现在,我们可以在下方看到测试统计量、p值和MGC图的可视化。最佳尺度在图上显示为一个红色“x”
>>> stat, pvalue, mgc_dict = multiscale_graphcorr(x, y)
>>> print("MGC test statistic: ", round(stat, 1))
MGC test statistic: 0.2 # random
>>> print("P-value: ", round(pvalue, 1))
P-value: 0.0
>>> mgc_plot(x, y, "Spiral", mgc_dict, only_mgc=True)

由此可见,MGC再次能够确定一种关系,因为p值非常低,并且MGC测试统计量相对较高。MGC图表示**强非线性关系**。在这种情况下,最佳尺度**等同于局部尺度**,在图上用红点标记。