Saturday, April 11, 2020

Comparison of np.dot and operator *

np.dot calculate the dot product of two arrays. For 2-D arrays, the matrix multiplication result is returned.

 The * operator calculate the element-wise multiplication. It will expand its dimension (called broadcasting) if the dimension does not match.

The best way to explain this is through some actual code


import numpy as np
# Example 1
vec1 = np.array([1, 2])
vec2 = np.array([2, 3])
vec1*vec2
# Return
# array([2, 6])
np.dot(vec1, vec2)
# Return
# 8
# Example 2
vec3 = np.array([[1, 2], [3, 4]])
vec4 = np.array([1, 2])
vec3*vec4
# Return
# array([[1, 4], [3, 8]])
np.dot(vec3, vec4)
# Return
# array([5, 11])
# Example 3
vec5 = np.array([[1, 2, 3], [4, 5, 6]])
vec6 = np.array([1, 2])
vec5.T*vec6
# Return
# array([[1, 8], [2, 10], [3, 12]])
np.dot(vec5.T, vec6)
# Return
# array([9, 12, 15])
view raw gistfile1.txt hosted with ❤ by GitHub

No comments:

Post a Comment