w3resource

Compute Dot Product using np.dot and custom ufunc in NumPy

NumPy: Universal Functions Exercise-12 with Solution

Vectorized Operations with ufuncs:

Write a NumPy program that creates two 1D arrays and uses np.dot to compute the dot product. Verify the result using a custom ufunc.

Sample Solution:

Python Code:

import numpy as np

# Create two 1D NumPy arrays
array_1 = np.array([1, 2, 3])
array_2 = np.array([4, 5, 6])

# Compute the dot product using np.dot
dot_product = np.dot(array_1, array_2)

# Define a custom ufunc to compute the dot product
def custom_dot(x, y):
    return np.sum(np.multiply(x, y))

# Create a ufunc from the custom function using np.frompyfunc
custom_dot_ufunc = np.frompyfunc(custom_dot, 2, 1)

# Verify the dot product using the custom ufunc
verified_dot_product = custom_dot_ufunc(array_1, array_2)

# Print the original arrays, the np.dot result, and the verified result
print('Array 1:', array_1)
print('Array 2:', array_2)
print('Dot product using np.dot:', dot_product)
print('Dot product using custom ufunc:', verified_dot_product)

Output:

Array 1: [1 2 3]
Array 2: [4 5 6]
Dot product using np.dot: 32
Dot product using custom ufunc: [4 10 18]

Explanation:

  • Import Libraries:
    • Imported numpy as "np" for array creation and manipulation.
  • Create Two 1D NumPy Arrays:
    • Created two 1D NumPy arrays named ‘array_1’ with values [1, 2, 3] and array_2 with values [4, 5, 6].
  • Compute Dot Product with np.dot:
    • Used the np.dot function to compute the dot product of 'array_1' and 'array_2'.
  • Define Custom Function:
    • Define a custom function custom_dot that takes two inputs x and y, computes their element-wise multiplication, and returns the sum of the results.
  • Create ufunc from Custom Function:
    • Create a ufunc from the custom function using "np.frompyfunc". The function takes the custom function, the number of input arguments (2), and the number of output arguments (1).
  • Verify Dot Product with Custom ufunc:
    • Used the custom ufunc ‘custom_dot_ufunc’ to verify the dot product of 'array_1' and 'array_2'.
  • Finally print the original arrays, the result from np.dot, and the verified result from the custom ufunc.

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Compute Outer Subtraction of Two 1D Arrays Using np.subtract.outer.
Next: Divide each 2D slice of 3D array by 1D array using np.divide.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/python-exercises/numpy/compute-dot-product-using-np-dot-dot-and-custom-ufunc-in-numpy.php