生成重新映射的numpy数组作为视图. [英] Generating a remapped numpy array as a view.

查看:83
本文介绍了生成重新映射的numpy数组作为视图.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题的玩具箱:

我有一个大小为numpy的数组,例如1000:

I have a numpy array of size, say, 1000:

import numpy as np
a = np.arange(1000)

我还有一个投影数组" p ,它是从 a 到另一个数组 b 的映射:

I also have a "projection array" p which is a mapping from a to another array b:

p = np.random.randint(0,1000,(1000,1000))

使用花式索引"很容易从 a 中获得 b :

It is easy to get b from a using "fancy indexing":

b = a[p]

但是 b 并不是一个视图,正如之前的一些问题/答案和numpy文档所指出的那样.

But b is not a view, as noted by several previous questions/answers and the numpy documentation.

不幸的是,在我的情况下,只有 a 中的值会在长时间的模拟过程中发生变化,并且在每次迭代中都使用奇特的索引来获取 b 变得非常昂贵.我只从 b 中读取内容,而不修改它.

Unfortunately, in my case only the values in a change over the course of a long simulation and using fancy indexing at each iteration to obtain b becomes very costly. I only read from b and do not modify it.

我知道尚无法通过精美索引来解决此问题.

I understand it is not possible (yet) to solve this with fancy indexing.

我想知道是否有人遇到类似的问题/瓶颈并想出其他解决方法?

I was wondering if anyone had a similar problem/bottleneck and came up with some other workaround?

推荐答案

您的要求不切实际,这就是为什么麻木的人没有实现它.您可以使用以下方法自己做:

What your asking for isn't practical and that's why the numpy folks haven't implemented it. You could do it yourself with something like:

class FancyView(object):
    def __init__(self, array, index):
        self._array = array
        self._index = index.copy()
    def __array__(self):
        return self._array[self._index]
    def __getitem__(self, index):
        return self._array[self._index[index]]

b = FancyView(a, p)

但是请注意,每次将b用作数组时,都会调用昂贵的a[p]操作.没有其他实践方法可以做出这种观点". Numpy可以使用视图进行基本切片,因为它可以控制跨步,但是它无法使用跨步来做类似的事情.

But notice that the expensive a[p] operation will get called every time you use b as an array. There is no other practice way of making a 'view' of this kind. Numpy can get away with using views for basic slicing because it can manipulate the strides, but there is no way to do something like this using strides.

如果只需要b的一部分,则可以通过索引精美视图而不是将其用作数组来节省一些时间.

If you only need parts of b you might be able to get some time savings by indexing the fancy view instead of using it as an array.

这篇关于生成重新映射的numpy数组作为视图.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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