简体   繁体   English

使用 numpy 在 for 循环内部和外部向向量添加标量有区别吗?

[英]Is there a difference between adding a scalar to a vector inside a for loop and outside it, using numpy?

I was trying to take advantage of the Broadcasting property of Python while replacing the for loop of this snippet:我试图在替换此代码段的 for 循环时利用 Python 的 Broadcasting 属性:

import numpy as np
B = np.random.randn(10,1)
k = 25
for i in range(len(B)):
  B[i][0]= B[i][0] + k

with this:有了这个:

for i in range((lenB)):
  B=B+k

I observed that I was getting different results.我观察到我得到了不同的结果。 When I tried outside the loop, B = B+k, gave the same results as what I was expecting with B[i][0] = B[i][0] + k当我在循环外尝试时,B = B+k,给出了与我期望的 B[i][0] = B[i][0] + k 相同的结果

Why is this so?为什么会这样? Does Broadcasting follow different rules inside loops?广播在循环内是否遵循不同的规则?

In your 2nd option you ment to do the following:在您的第二个选项中,您需要执行以下操作:

B=B+k

As you see, you don't need the for loop and it is MUCH faster than looping over the " vector " ( numpy array).正如你看到的,你不需要for循环,这是远远快于循环在“矢量”( numpy阵列)。

It is some form of "Vectorization" calculation instead of iterative calculation which is better in terms of complexity and readability.它是某种形式的“矢量化”计算,而不是迭代计算,在复杂性和可读性方面更好。 Both will yield the same result.两者都会产生相同的结果。

You can see a lot of examples on Vectorization vs Iteration, including running time, here .你可以看到很多的例子在矢量VS迭代,包括运行时间, 在这里

And you can see a great video of Andrew Ng going over numpy broadcasting property.您可以看到Andrew Ng 介绍numpy 广播属性的 精彩视频

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM