在numpy的列块操作 [英] Blockwise operations in Numpy

查看:288
本文介绍了在numpy的列块操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有任何方便实用程序上numpy的阵列做列块操作?

Are there any convenience utilities for doing blockwise operations on Numpy arrays?

我喜欢伊辛自旋重整化,你把一个矩阵成块,并返回每个块是由它的总和,平均或其他功能替代基质思维操作。

I am thinking of operations like Ising spin renormalization where you divide a matrix into blocks and return matrix where each block is replaced by its sum, average or other function.

推荐答案

您可能会寻找 superbatfish的 blockwise_view 。这将使用 np.lib.stride_tricks.as_strided 以创建哪些地方在他们自己的轴数组的块的阵列的景色。

You might be looking for superbatfish's blockwise_view. This uses np.lib.stride_tricks.as_strided to create a view of the array which places "blocks" of the array in their own axes.

例如,假设你有一个二维数组,例如,

For example, suppose you have a 2D array such as,

In [97]: arr = np.arange(24).reshape(6, 4)

In [98]: arr.shape
Out[98]: (6, 4)

In [99]: arr
Out[99]: 
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19],
       [20, 21, 22, 23]])

和你想砍了进入形状的4块(3,2)。你可以使用
blockwise_view < /一>把它转换成形状的四维阵列(4,3,2):

and you wish to "chop it" into 4 blocks of shape (3, 2). You could use blockwise_view to convert it into a 4D array of shape (4, 3, 2):

In [34]: blocked = blockwise_view(arr, (3, 2)); blocked
Out[34]: 
array([[[[ 0,  1],
         [ 4,  5],
         [ 8,  9]],

        [[ 2,  3],
         [ 6,  7],
         [10, 11]]],


       [[[12, 13],
         [16, 17],
         [20, 21]],

        [[14, 15],
         [18, 19],
         [22, 23]]]])

In [37]: blocked.shape
Out[37]: (2, 2, 3, 2)

现在,你可以重新塑造它,从一个块中的所有值都在近轴:

Now you could reshape it so all the values from one block are in the last axis:

In [41]: reshaped = blocked.reshape(-1, 3*2); reshaped
Out[41]: 
array([[ 0,  1,  4,  5,  8,  9],
       [ 2,  3,  6,  7, 10, 11],
       [12, 13, 16, 17, 20, 21],
       [14, 15, 18, 19, 22, 23]])

现在你可以沿着这条轴线综上所述,或采取其平均值或应用其他一些功能,每块的元素:

Now you can sum along that axis, or take its mean or apply some other function to the elements of each block:

In [103]: reshaped.sum(axis=-1)
Out[103]: array([ 27,  39,  99, 111])

In [104]: reshaped.mean(axis=-1)
Out[104]: array([  4.5,   6.5,  16.5,  18.5])

第一个答案,这只能适用于二维数组,
blockwise_view 可以应用到任意N维数组。它返回一个
2N维阵列,其中最初的N个轴索引的块。

Unlike my first answer, which can only be applied to 2D arrays, blockwise_view can be applied to arbitrary N-dimensional arrays. It returns a 2N-dimensional array where the first N axes index the blocks.

这篇关于在numpy的列块操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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