2D阵列AND阵列在numpy中看起来有不同的索引

时间:2014-09-24 18:04:29

标签: python arrays numpy

作为一个大型项目的一部分,我需要能够做出正交的"投影"在每个N维中的标量场。 (实际上,我想在每个维度中采用数据的均值,除了"维度和#34;)。下面是相关代码的简化(但完整且可运行)的摘录.... 除了,当投影尺寸是第0或第1轴时。在这种情况下,代码的行为就好像已经交换了这两个维度。我需要帮助来理解为什么会发生这种情况,以及最好的方法是协调这种行为,以便无论索引哪个维度,程序都能保持一致。

from pylab import *
import scipy.interpolate

def projectAxis(d,projection_dim,nDim) :
    """calculate (and plot) the mean across all axes, except for the
    projection dimension

    """
    all_axes_except_projection_dim = range(nDim)
    all_axes_except_projection_dim.remove(projection_dim)
    plot(mean(d,axis=tuple(all_axes_except_projection_dim)))
    ylim(0,1); yticks([0,1]);

def test(nDim,varies_in_dim,col=1) :
    """Generate a gradient in nDim-dimensional space, and project it in
    each dimension. """

    ## generate 1000 randomly distributed coordinates
    xs = np.random.rand(1000,nDim) 
    ## generate a value to be associated with each coordinate.  The
    ## value is assigned such that it correlates (exactly) with a
    ## particular dimension / axis of the data. The particular
    ## dimension is assigned by the parameter 'varies_in_dim'.
    z = xs[:,varies_in_dim] 

    ## interpolate, to create a regular n-dimensional mesh
    lattice_width = 11 
    m_points = [linspace(0,1,lattice_width)]*nDim
    interpolation_points = tuple(np.meshgrid(*m_points))
    zi = scipy.interpolate.griddata(xs, z, interpolation_points, method='nearest')

    def plotProjection(axis,nDim) :
        projectAxis(zi,axis,nDim)
        if col == 3 :
            ylabel('axis=%d' %(axis))
            gca().yaxis.set_label_position("right")

    # if there are sufficient dimensions to display
    # variation in the specified dimension...
    if nDim > varies_in_dim :
        for d in xrange(4) :
            if nDim > d :
                subplot2grid((rows,cols),(d,col))
                plotProjection(d,nDim)
                if d == 0 :
                    title('%d-D space' %(nDim))


figure(figsize=(7,8))
rows,cols = 4,4
varies_in_dim = 1
suptitle('Data should only substantially vary along axis %d' %(varies_in_dim) )

test(2,varies_in_dim,col=0)
test(3,varies_in_dim,col=1)
test(4,varies_in_dim,col=2)
test(5,varies_in_dim,col=3)

show()

使用varies_in_dim = 2(或更高的值)运行时,输出就是我所期望的。对于每个测试用例(3,4或5维空间),显示变化的唯一投影是第二维(其中维度从0开始索引)。以下是varies_in_dim = 2的输出,这是正确的:

Correct output for variation in dimension 2

但是当varies_in_dim = 1时,输出显示尺寸0的变化...反之亦然:当varies_in_dim = 0时,输出显示尺寸1的变化。下图显示{{1的输出}},其中错误地显示了在维度0中发生的变化

enter image description here

我错过了什么?如何重新组织我的计划以保持一致的工作?

0 个答案:

没有答案