我似乎迷失在一件可能很愚蠢的事情中。我有一个n维的numpy数组,我想沿着某个维度(可以改变!)将它与一个向量(1d数组)相乘。)。举个例子,假设我想将一个2d数组乘以第一个数组的轴0上的一个1d数组,我可以这样做:
a=np.arange(20).reshape((5,4))
b=np.ones(5)
c=a*b[:,np.newaxis]
字符串
很简单,但我想把这个想法扩展到n维(对于a,而b总是1d)和任何轴。换句话说,我想知道如何在正确的位置生成一个np.newaxis切片。假设a是3d的,我想沿着轴=1相乘,我想生成一个切片,它会正确地给予:
c=a*b[np.newaxis,:,np.newaxis]
型
也就是说,给定a的维数(比如说3),以及我想要相乘的轴(比如轴=1),我如何生成并传递切片:
np.newaxis,:,np.newaxis
型
- 谢谢-谢谢
6条答案
按热度按时间oo7oh9g91#
解决方案编码-
字符串
步骤演示示例运行-
型
现在,我们想沿着
given axis = 1
执行逐元素乘法。让我们创建dim_array
:型
最后,重塑
b
并执行元素乘法:型
再次查看
whos
信息,并特别注意b_reshaped
和mult_out
:型
klr1opcd2#
避免复制数据和浪费资源!
利用类型转换和视图,而不是实际将数据复制N次到具有适当形状的新数组中(如现有答案所做的那样),这是更有效的内存方式。下面是这样一个方法(基于@ShuxuanXU的代码):
字符串
pkwftd7m3#
您可以构建切片对象,并在其中选择所需的尺寸:
字符串
jtjikinw4#
我在做一些数值计算的时候也有类似的要求。
假设我们有两个数组(A和B)和一个用户指定的“轴”。A是一个多维数组。B是一个一维数组。
基本思想是扩展B,使A和B具有相同的形状。下面是解决方案代码
字符串
这里有一个例子
型
kadbb4595#
简化@Neinstein的解决方案,我得到了
字符串
此示例还避免了复制和浪费内存。通过将A中的期望轴交换到最后一个位置,执行乘法,然后将轴交换回原始位置,来避免显式广播。另外一个优点是numpy负责错误处理和类型转换。
6l7fqoea6#
你也可以使用一个简单的矩阵技巧
字符串
基本上就是在
a
和一个对角线是b
元素的矩阵之间做矩阵乘法。也许不是那么有效,但它是一个很好的单线解决方案