Numpy,python:广播时自动扩展数组的维度 [英] Numpy, python: automatically expand dimensions of arrays when broadcasting

查看:82
本文介绍了Numpy,python:广播时自动扩展数组的维度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下 Numpy 数组广播的练习.

Consider the following exercise in Numpy array broadcasting.

import numpy as np
v = np.array([[1.0, 2.0]]).T # column array

A2 = np.random.randn(2,10) # 2D array
A3 = np.random.randn(2,10,10) # 3D

v * A2 # works great

# causes error: 
v * A3 # error

我了解 Numpy 广播规则,并且熟悉 Matlab 中的 bsxfun 功能.我理解为什么尝试将 (2,1) 数组广播到 (2,N,N) 数组失败,并且我必须在此之前将 (2,1) 数组重塑为 (2,1,1) 数组广播通过.

I know the Numpy rules for broadcasting, and I'm familiar with bsxfun functionality in Matlab. I understand why attempting to broadcast a (2,1) array into a (2,N,N) array fails, and that I have to reshape the (2,1) array into a (2,1,1) array before this broadcasting goes through.

我的问题是:有没有什么方法可以告诉 Python 在尝试广播时自动填充数组的维数,而我不必专门告诉它必要的维数?

My question is: is there any way to tell Python to automatically pad the dimensionality of an array when it attempts to broadcast, without me having to specifically tell it the necessary dimension?

不想将 (2,1) 向量与要广播的多维数组显式耦合---否则我可以做一些愚蠢而丑陋的事情,比如 mult_v_A = lambda v,A: v.reshape([v.size] + [1]*(A.ndim-1)) * A.我不知道A"数组是 2D、3D 还是 N-D.

I don't want to explicitly couple the (2,1) vector with the multidimensional array it's going to be broadcast against---otherwise I could do something stupid and absurdly ugly like mult_v_A = lambda v,A: v.reshape([v.size] + [1]*(A.ndim-1)) * A. I don't know ahead of time if the "A" array will be 2D or 3D or N-D.

Matlab 的 bsxfun 广播功能会根据需要隐式填充尺寸,所以我希望我可以在 Python 中做一些事情.

Matlab's bsxfun broadcasting functionality implicitly pads the dimensions as needed, so I'm hoping there's something I could do in Python.

推荐答案

这很丑陋,但是这行得通:

It's ugly, but this will work:

(v.T * A3.T).T

如果你不给它任何参数,转置会反转形状元组,所以你现在可以依靠广播规则来发挥它们的魔力.最后一个转置将所有内容恢复到正确的顺序.

If you don't give it any arguments, transposing reverses the shape tuple, so you can now rely on the broadcasting rules to do their magic. The last transpose returns everything to the right order.

这篇关于Numpy,python:广播时自动扩展数组的维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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