如何进行矢量3D numpy的阵列 [英] How to vectorize 3D Numpy arrays

查看:180
本文介绍了如何进行矢量3D numpy的阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3D numpy的阵列像 A = np.zeros((100,100,20))。我想在每个 X,Y ,涉及遍布以Z 轴和结果的元素位置进行操作存储阵列中的如 b = np.zeros((100,100))上相应的 X,Y 位置

I have a 3D numpy array like a = np.zeros((100,100, 20)). I want to perform an operation over every x,y position that involves all the elements over the z axis and the result is stored in an array like b = np.zeros((100,100)) on the same corresponding x,y position.

现在我用我做一个循环:

Now i'm doing it using a for loop:

d_n = np.array([...]) # a parameter with the same shape as b
for (x,y), v in np.ndenumerate(b):
    C = a[x,y,:]

    ### calculate some_value using C
    minv = sys.maxint
    depth = -1
    C = a[x,y,:]
    for d in range(len(C)):
        e = 2.5 * float(math.pow(d_n[x,y] - d, 2)) + C[d] * 0.05
        if e < minv:
            minv = e
            depth = d

    some_value = depth
    if depth == -1:
        some_value = len(C) - 1
    ###

    b[x,y] = some_value

现在的问题是,这种操作的的慢于别人完成Python的方式,例如Ç= B * B (Ⅰ实际上异形这个功能和它的周围2个数量级比其他使用内置函数和量化功能numpy的慢的,在一个类似的元素的数量)

The problem now is that this operation is much slower than others done the pythonic way, e.g. c = b * b (I actually profiled this function and it's around 2 orders of magnitude slower than others using numpy built in functions and vectorized functions, over a similar number of elements)

如何提高这类函数映射的性能三维阵列到2D的?

推荐答案

什么通常是在3D图像要做的就是将以Z 轴交换到第一个索引:

What is usually done in 3D images is to swap the Z axis to the first index:

>>> a = a.transpose((2,0,1))
>>> a.shape
(20, 100, 100)

现在你可以很容易地遍历Z轴:

And now you can easily iterate over the Z axis:

>>> for slice in a:
       do something

这里将是您的每一个3D矩阵的你的 100×100 分数。此外,通过transpossing允许您直接通过索引第一轴来访问每个二维切片。例如 A [10] 会给你11 2D 100×100 片。

The slice here will be each of your 100x100 fractions of your 3D matrix. Additionally, by transpossing allows you to access each of the 2D slices directly by indexing the first axis. For example a[10] will give you the 11th 2D 100x100 slice.

奖励:如果您存储数据contiguosly,而不调换(或使用转换为一个连续的阵列 A = np.ascontiguousarray(a.transpose((2,0,1)))接入到你,因为他们在contiguosly内存映射二维切片会更快。

Bonus: If you store the data contiguosly, without transposing (or converting to a contiguous array using a = np.ascontiguousarray(a.transpose((2,0,1))) the access to you 2D slices will be faster since they are mapped contiguosly in memory.

这篇关于如何进行矢量3D numpy的阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆