NumPy-什么是广播? [英] NumPy - What is broadcasting?

查看:98
本文介绍了NumPy-什么是广播?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不理解广播.该文档解释了广播规则,但似乎没有用英语对其进行定义.我的猜测是,广播是当NumPy用虚拟数据填充较小尺寸的数组以执行操作时.但这不起作用:

I don't understand broadcasting. The documentation explains the rules of broadcasting but doesn't seem to define it in English. My guess is that broadcasting is when NumPy fills a smaller dimensional array with dummy data in order to perform an operation. But this doesn't work:

>>> x = np.array([1,3,5])
>>> y = np.array([2,4])
>>> x+y
*** ValueError: operands could not be broadcast together with shapes (3,) (2,) 

该错误消息暗示我处在正确的轨道上.有人可以定义广播,然后提供一些简单的示例,说明何时可以正常工作,什么时候不可以工作?

The error message hints that I'm on the right track, though. Can someone define broadcasting and then provide some simple examples of when it works and when it doesn't?

推荐答案

术语广播描述了numpy在算术运算期间如何处理具有不同形状的数组.

The term broadcasting describes how numpy treats arrays with different shapes during arithmetic operations.

基本上,这是numpy可以扩展数组操作范围的方法.

It's basically a way numpy can expand the domain of operations over arrays.

广播的唯一要求是对齐数组尺寸的方式,以便:

The only requirement for broadcasting is a way aligning array dimensions such that either:

  • 对齐的尺寸相等.
  • 对齐的尺寸之一是1.

例如,如果:

x = np.ndarray(shape=(4,1,3))
y = np.ndarray(shape=(3,3))

您无法像这样对齐x和y:

You could not align x and y like so:

4 x 1 x 3
3 x 3

但是您可以这样:

4 x 1 x 3
    3 x 3

这样的操作结果如何?

假设我们有:

How would an operation like this result?

Suppose we have:

x = np.ndarray(shape=(1,3), buffer=np.array([1,2,3]),dtype='int')
array([[1, 2, 3]])

y = np.ndarray(shape=(3,3), buffer=np.array([1,1,1,1,1,1,1,1,1]),dtype='int')
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

操作x + y将导致:

array([[2, 3, 4],
       [2, 3, 4],
       [2, 3, 4]])

我希望你能赶上潮流.如果没有,您可以随时在此处查看官方文档.

I hope you caught the drift. If you did not, you can always check the official documentation here.

干杯!

这篇关于NumPy-什么是广播?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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