【发布时间】:2014-05-29 21:28:03
【问题描述】:
如果可能的话,有没有人知道在 Python 中计算经验/样本协变函数的好方法?
这是book 的屏幕截图,其中包含协方差图的良好定义:
如果我理解正确,对于给定的滞后/宽度 h,我应该得到由 h(或小于 h)分隔的所有点对,乘以它的值,并且对于这些点中的每一个,计算其平均值,在这种情况下,定义为 m(x_i)。但是,根据 m(x_{i}) 的定义,如果我想计算 m(x1),我需要获得距离 x1 距离 h 内的值的平均值。这看起来像一个非常密集的计算。
首先,我理解正确吗?如果是这样,假设二维空间计算这个的好方法是什么?我尝试在 Python 中编写代码(使用 numpy 和 pandas),但这需要几秒钟,我什至不确定它是否正确,这就是为什么我不会在此处发布代码的原因。这是另一个非常天真的实现的尝试:
from scipy.spatial.distance import pdist, squareform
distances = squareform(pdist(np.array(coordinates))) # coordinates is a nx2 array
z = np.array(z) # z are the values
cutoff = np.max(distances)/3.0 # somewhat arbitrary cutoff
width = cutoff/15.0
widths = np.arange(0, cutoff + width, width)
Z = []
Cov = []
for w in np.arange(len(widths)-1): # for each width
# for each pairwise distance
for i in np.arange(distances.shape[0]):
for j in np.arange(distances.shape[1]):
if distances[i, j] <= widths[w+1] and distances[i, j] > widths[w]:
m1 = []
m2 = []
# when a distance is within a given width, calculate the means of
# the points involved
for x in np.arange(distances.shape[1]):
if distances[i,x] <= widths[w+1] and distances[i, x] > widths[w]:
m1.append(z[x])
for y in np.arange(distances.shape[1]):
if distances[j,y] <= widths[w+1] and distances[j, y] > widths[w]:
m2.append(z[y])
mean_m1 = np.array(m1).mean()
mean_m2 = np.array(m2).mean()
Z.append(z[i]*z[j] - mean_m1*mean_m2)
Z_mean = np.array(Z).mean() # calculate covariogram for width w
Cov.append(Z_mean) # collect covariances for all widths
但是,现在我已经确认我的代码中存在错误。我知道,因为我使用了变异函数来计算协变异函数(covariogram(h) = covariogram(0) - variogram(h)),我得到了一个不同的图:
它应该是这样的:
最后,如果您知道用于计算经验协变函数的 Python/R/MATLAB 库,请告诉我。至少,这样我可以验证我做了什么。
【问题讨论】:
-
如所写,
m的等式没有意义。如果您对i求和,那么在总和之外(即在m(x_i)中)按i进行索引并不意味着任何事情;也就是说,右侧没有i。 -
对。我也觉得这很混乱。如果您阅读了我最后添加的参考资料(这是books.google.com/… 的确切页面),那么总和似乎是位于距离 h 内的点上,而不是在同一个 i 上。也就是说,第一个等式中的 N(h) 与第二个等式中的 N(h) 不同。正如我所说,这本书的符号比维基百科更好。
-
我认为这并不像您想象的那么难,但是如果没有正确的方程式,就很难知道。我也不完全想读一本书的章节来找出正确的方程式。我会等一下,但最终我会投票关闭,因为不清楚。不过,基本上,您只想对成对度量求和,这在 numpy.xml 中可能很容易做到。但首先你需要知道你需要做什么。
-
好吧,我可以尝试改变方程式。顺便说一句,如果您单击我之前评论中的链接,它会导致等式。让我知道如何改进问题,而不是投票结束。
-
另外,你有多少分?即,计算所有点间距离是否有意义?
标签: python numpy covariogram