Saturday, June 13, 2020

numpy create ufunc

Creating Our Own ufunc 


We create our own Numpy ufunc (Universal function) like any other normal Python function. It is very simple to create our own ufunc. We just need to add this function to our Numpy ufunc library using frompyfunc() method.


The following arguments are provided to frompyfunc() method,

  • function - the function name
  • inputs - the number of input arguments (arrays).
  • outputs - the number of output arrays.

For example,

import numpy as np

def multiply(x, y):
  return x*y

multiply = np.frompyfunc(multiply, 2, 1)

print(multiply([1, 2, 3, 4], [5, 6, 7, 8]))

#Output
[5 12 21 32]

Testing if a function is a ufunc


An ufunc type returns <class 'numpy.ufunc'>

import numpy as np

def multiply(x, y):
  return x*y

multiply = np.frompyfunc(multiply, 2, 1)

print(type(np.multiply))

#Output
<class 'numpy.ufunc'>

Applications of user-created ufunc


User defined ufunc can be useful for 

  • Numpy Broadcasting
  • N-dimensional looping
  • Automatic type-conversions with minimal memory usage 
  • Optional output arrays

numpy.frompyfunc()


The syntax of numpy.frompyfunc is

numpy.frompyfunc(func, nin, nout) 

It allows us to define an arbitrary Python function as Numpy ufunc,

Here, the following parameters are defined as,

  • func (A python function object) represents an arbitrary python function. 
  • nin (int) represents a number of input arguments to that function.
  • nout (int) represents a number of objects returned by that function. This function returns a ufunc function object.
for example,

import numpy as np 
  
# create an array of numners 
arr = np.array([34, 67, 89, 15, 33, 27]) 
  
# python str function as ufunc 
string_producer = np.frompyfunc(str, 1, 1) 
  
print("Actual array-", arr) 
print("Array After converting to a string\n", string_producer(arr)) 

#Output
Actual array- [34 67 89 15 33 27]
Array After converting to a string
 ['34' '67' '89' '15' '33' '27']