Apply both vectorized and non-vectorized function in numpy array

I have a function that does this: it takes a given numpy array Aand a given function funcand applies this function to each element of the array.

def transform(A, func):
    return func(A)

Aand funcshipped outside, and I have no control over them. I would like the functions to work if they are vectorized functions such as transform(A, np.sin), but I also want to be able to accept a normal numpy function, for example. lambdas like it transform(A, lambda x: x^2 if x > 5 else 0). Of course, the second is not vectorized, so I will need to call np.vectorize()before applying it. Like this: transform(A, np.vectorize(lambda x: x^2 if x > 5 else 0))... But I do not want to put this burden on users. I would like to get a unified approach to all functions. I just get the function outside and apply it.

Is there a way to decide which function requires vectorization and which does not? Sort of:

def transform(A, func):
    if requires_vectorization(func):  # how to do this???
        func = np.vectorize(func)
    return func(A)   

Or do I just need to vectorize everything by default.

def transform(A, func):
    func = np.vectorize(func)  # is this correct and efficient?
    return func(A)   

Is this a good decision? In other words, won't the call np.vectorizeto an already vectorized function hinder it ? Or is there an alternative?

+4
1

EAFP, A , :

import numpy as np

def transform(A, func):
    try:
        return func(A)
    except TypeError:
        return np.vectorize(func)(A)

:

import math

A = np.linspace(0, np.pi, 5)

print(transform(A, np.sin))     # vectorized function
# [  0.00000000e+00   7.07106781e-01   1.00000000e+00   7.07106781e-01
#    1.22464680e-16]

print(transform(A, math.sin))   # non-vectorized function
# [  0.00000000e+00   7.07106781e-01   1.00000000e+00   7.07106781e-01
#    1.22464680e-16]

np.vectorize ?

, . np.vectorize , Python, "" numpy, C. :

, . for.

, all-caps.

:

In [1]: vecsin = np.vectorize(np.sin)

In [2]: %%timeit A = np.random.randn(10000);
np.sin(A)
   ....: 
1000 loops, best of 3: 243 µs per loop

In [3]: %%timeit A = np.random.randn(10000);
vecsin(A)
   ....: 
100 loops, best of 3: 11.7 ms per loop

In [4]: %%timeit A = np.random.randn(10000);
[np.sin(a) for a in A]
   ....: 
100 loops, best of 3: 12.5 ms per loop

np.vectorize to np.sin 50 , , Python.

Edit:

"" . , try/except :

In [5]: %%timeit A = np.random.randn(10000);
transform(A, np.sin)
   ...: 
1000 loops, best of 3: 241 µs per loop
+2

Source: https://habr.com/ru/post/1623343/


All Articles