python – 沿给定轴乘以1d数组的numpy ndarray

python – 沿给定轴乘以1d数组的numpy ndarray,第1张

概述看来我迷失在可能愚蠢的东西中.  我有一个n维numpy数组,我想将它与一个维度(可以改变!)的向量(1d数组)相乘. 举个例子,假设我想将第二个数组乘以第一个数组的0轴的1d数组,我可以这样做: a=np.arange(20).reshape((5,4))b=np.ones(5)c=a*b[:,np.newaxis] 很简单,但我想将这个想法扩展到n维(对于a,而b总是1d)和任何轴.换句话 看来我迷失在可能愚蠢的东西中.
我有一个n维numpy数组,我想将它与一个维度(可以改变!)的向量(1d数组)相乘.
举个例子,假设我想将第二个数组乘以第一个数组的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

谢谢.

解决方法 解决方案代码
import numpy as np# Given axis along which elementwise multiplication with broadcasting # is to be performedgiven_axis = 1# Create an array which would be used to reshape 1D array,b to have # singleton dimensions except for the given axis where we would put -1 # signifying to use the entire length of elements along that axis  dim_array = np.ones((1,a.ndim),int).ravel()dim_array[given_axis] = -1# Reshape b with dim_array and perform elementwise multiplication with # broadcasting along the singleton dimensions for the final outputb_reshaped = b.reshape(dim_array)mult_out = a*b_reshaped

示例运行步骤的演示 –

In [149]: import numpy as npIn [150]: a = np.random.randint(0,9,(4,2,3))In [151]: b = np.random.randint(0,(2,1)).ravel()In [152]: whosVariable   Type       Data/Info-------------------------------a          ndarray    4x2x3: 24 elems,type `int32`,96 bytesb          ndarray    2: 2 elems,8 bytesIn [153]: given_axis = 1

现在,我们想沿给定的轴= 1执行元素乘法.让我们创建dim_array:

In [154]: dim_array = np.ones((1,int).ravel()     ...: dim_array[given_axis] = -1     ...: In [155]: dim_arrayOut[155]: array([ 1,-1,1])

最后,重塑b&执行元素乘法:

In [156]: b_reshaped = b.reshape(dim_array)     ...: mult_out = a*b_reshaped     ...:

再次查看whos信息并特别注意b_reshaped& mult_out:

In [157]: whosVariable     Type       Data/Info---------------------------------a            ndarray    4x2x3: 24 elems,96 bytesb            ndarray    2: 2 elems,8 bytesb_reshaped   ndarray    1x2x1: 2 elems,8 bytesdim_array    ndarray    3: 3 elems,12 bytesgiven_axis   int        1mult_out     ndarray    4x2x3: 24 elems,96 bytes
总结

以上是内存溢出为你收集整理的python – 沿给定轴乘以1d数组的numpy ndarray全部内容,希望文章能够帮你解决python – 沿给定轴乘以1d数组的numpy ndarray所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1206985.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存