[英]numpy.ndarray sent as argument doesn't need loop for iteration?
In this code np.linspace()
assigns to inputs
200 evenly spaced numbers from -20 to 20. 在此代码中,
np.linspace()
向inputs
200分配从-20到20的均匀间隔的数字。
This function works. 此功能有效。 What I am not understanding is how could it work.
我不了解的是它如何工作。 How can
inputs
be sent as an argument to output_function()
without needing a loop to iterate over the numpy.ndarray? 如何将
inputs
作为参数发送到output_function()
而不需要循环遍历numpy.ndarray?
def output_function(x):
return 100 - x ** 2
inputs = np.linspace(-20, 20, 200)
plt.plot(inputs, output_function(inputs), 'b-')
plt.show()
numpy
works by defining operations on vectors the way that you really want to work with them mathematically. numpy
工作方式是定义对向量的运算,而这正是您真正想在数学上使用它们的方式。 So, I can do something like: 因此,我可以做类似的事情:
a = np.arange(10)
b = np.arange(10)
c = a + b
And it works as you might hope -- each element of a
is added to the corresponding element of b
and the result is stored in a new array c
. 它可以按您希望的那样工作-将
a
每个元素添加到b
的对应元素中,并将结果存储在新数组c
。 If you want to know how numpy accomplishes this, it's all done via the magic methods in the python data model. 如果您想知道numpy是如何做到这一点的,那么都可以通过python数据模型中的magic方法来完成。 Specifically in my example case, the
__add__
method of numpy's ndarray
would be overridden to provide the desired behavior. 特别是在我的示例案例中,numpy的
ndarray
的__add__
方法将被覆盖以提供所需的行为。
What you want to use is numpy.vectorize
which behaves similarly to the python builtin map
. 您要使用的是
numpy.vectorize
,其行为类似于python内置map
。
Here is one way you can use numpy.vectorize
: 这是使用
numpy.vectorize
一种方法:
outputs = (np.vectorize(output_function))(inputs)
You asked why it worked, it works because numpy arrays can perform operations on its array elements en masse, for example: 您问它为什么起作用,之所以起作用,是因为numpy数组可以对其数组元素进行整体操作,例如:
a = np.array([1,2,3,4]) # gives you a numpy array of 4 elements [1,2,3,4]
b = a - 1 # this operation on a numpy array will subtract 1 from every element resulting in the array [0,1,2,3]
Because of this property of numpy arrays you can perform certain operations on every element of a numpy array very quickly without using a loop (like what you would do if it were a regular python array). 由于numpy数组具有此属性,因此您可以非常快速地对numpy数组的每个元素执行某些操作,而无需使用循环(就像在常规python数组中一样)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.