本文介绍了通过.reshape(generator)将一维数组广播到变化的nD数组的特定维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个nD形状的大矩阵(2,2,2,... n),该矩阵经常变化.

I have a large matrix of the shape (2,2,2,...n) of nD dimensions, which often varies.

但是,我也收到输入数据,该输入数据始终是形状为(2,)的一维数组.

However I am also receiving incoming data which is always a 1D array of shape (2,).

现在,我想通过整形将以前的nD尺寸矩阵与1D阵列相乘...,并且我还有一个索引",特别是要广播和修改的尺寸.

Now I want to multiply my former matrix of nD dimensions with my 1D array via reshape... and I also have an 'index' of which dimensions I want to broadcast and modify in particular.

因此,我正在执行以下操作(循环内):

Thus I'm doing the following (within a loop):

matrix_nd *= array_1d.reshape(1 if i!=index else dimension for i, dimension in enumerate(matrix_nd.shape))

但是,此生成器作为输入似乎无效.请注意,维度将始终等于2,并且只能在我们的序列中放置一次.

However this generator as input does not seem to be valid.Note that the dimension would always equal to 2 and only be placed once within our sequence.

例如,如果我们有一个形状为(2,2,2,2,2,2)且索引为3的5D矩阵;我们想将一维数组重塑为(1,1,1,2,1).

For example, if we have a 5D matrix of shape (2,2,2,2,2) and an index of 3; we would want to reshape the 1D array to a (1,1,1,2,1).

有什么想法吗?

谢谢.

所以事实证明,我的整个方法是错误的:得到我想要的元组似乎仍然将(2,)一维数组广播到所有维度.

So it turns out my entire approach is wrong:Getting the tuple that I was after still seems to broadcast the (2,) 1D array to all dimensions.

例如:我有(2,2,2)的numpy数组test_nd.shape,它看起来像这样:

For example:I have numpy array test_nd.shape of (2,2,2) and which looks like this:

array([[[1, 1],
  [1, 1]],
 [[1, 1],
  [1, 1]]])

然后我将一个(2,)一维数组重塑为仅向第3维广播:

I then reshape a (2,) 1D array to be broadcasted to the 3rd dimensions only:

toBroadcast = numpy.asarray([0,0]).reshape(1,1,2)

在哪里广播,其格式为array([[[0, 0]]])

Where toBroadcast has the form array([[[0, 0]]])

但是... test_nd*toBroadcast返回以下结果:

However... test_nd*toBroadcast returns the following result:

array([[[0, 0],
      [0, 0]],
     [[0, 0],
      [0, 0]]])

似乎已经广播到了各个方面.有什么想法吗?

It seems to have been broadcasting to all the dimensions. Any ideas?

推荐答案

您可以定义类似

def broadcast_axis(data, ndims, axis):
    newshape = [1] * ndims
    newshape[axis] = -1
    return data.reshape(*newshape)

并像使用它

vector = broadcast_axis(vector, matrix.ndim, 3)

这篇关于通过.reshape(generator)将一维数组广播到变化的nD数组的特定维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 15:01