栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

沿给定轴将numpy ndarray与1d数组相乘

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

沿给定轴将numpy ndarray与1d数组相乘

解决方案代码-

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,9,(2,1)).ravel()In [152]: whosVariable   Type       Data/Info-------------------------------a          ndarray    4x2x3: 24 elems, type `int32`, 96 bytesb          ndarray    2: 2 elems, type `int32`, 8 bytesIn [153]: given_axis = 1

现在,我们要沿进行元素乘法

given axis = 1
。让我们来创建
dim_array

In [154]: dim_array = np.ones((1,a.ndim),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, type `int32`, 96 bytesb ndarray    2: 2 elems, type `int32`, 8 bytesb_reshaped   ndarray    1x2x1: 2 elems, type `int32`, 8 bytesdim_array    ndarray    3: 3 elems, type `int32`, 12 bytesgiven_axis   int        1mult_out     ndarray    4x2x3: 24 elems, type `int32`, 96 bytes


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/419958.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号