When working with arrays of numpy, we should avoid looping as much as possible, using vectorization functions to avoid loops.
However, applying a custom function directly above the NumPy array will cause an error, and we need to convert the function to vectorization.
def Theta (x): """ Scalar implemenation of the Heaviside step function. """ if x >= 0: return 1 else: return 0Theta (Array ([-3,-2,-1,0,1,2,3]))
Error message:
---------------------------------------------------------------------------valueerror Traceback (most Recent call last) in <module>()----> 1 Theta (Array ([ -3,-2,-1,0,1,2,3])) in Theta (x) 3 Scalar implemenation of the Heaviside step function. 4 "" " ----> 5 if x >= 0: 6 return 1 7 else:ValueError:The Truth Value of an array with more than one element is ambiguous. Use A.any () or A.all ()
To get the theta of the vectors, we can use the NumPy function vectorize. In many cases it can automatically vectorize a function:
Theta_vec = vectorize (Theta) Theta_vec (Array ([-3,-2,-1,0,1,2,31, 1, 1, 1])
We can also use this function to accept the vector input from the beginning (more work is needed but also better):
def Theta (x): """ Vector-aware implemenation of the Heaviside step function. """ return 1 * (x >= 0) Theta (Array ([-3,-2,-1,0,1,2,31, 1, 1, 1])# The scalar is still going to work. Theta ( -1.2), Theta(2.6 1)
Vectorization of functions in Python numpy conversion