How to calculate vector dot products using Python NumPy?
We can use the following Python code to calculate the dot product of two vectors.
import numpy
a = numpy.random.randint(low=1, high=10, size=(1, 3))
b = numpy.random.randint(low=1, high=10, size=(1, 3))
c = numpy.random.randint(low=1, high=10, size=(3, 1))
d = numpy.random.randint(low=1, high=10, size=(3, 1))
r1 = numpy.dot(numpy.squeeze(a), numpy.squeeze(b))
r2 = numpy.dot(numpy.squeeze(c), numpy.squeeze(d))
print("a: \n", a)
print("b: \n", b)
print("r1 = a . b: \n", r1)
print("c: \n", c)
print("d: \n", d)
print("r2 = c . d: \n", r2)
Here, a and b are two row vectors of the same dimension. And c and d are two column vectors of the same dimension. The elements of the vectors a, b, c, and d are random integers. We are using the numpy.random.randint() function to create the row vectors and the column vectors. The generated random integers will be within the range [low, high).
And the size argument specifies the shape of the vector. For example, size(1, 3) indicates that the created vector will have 3 elements in a single row. In other words, the created vector will be a 3-dimensional row vector. And size=(3, 1) specifies that the created vector will have 3 elements in a single column. In other words, the created vector will be a 3-dimensional column vector.
Now, we are using the numpy.dot() function to calculate the dot product, inner product or scalar product of the vectors. Please note that we need to squeeze the ndarrays to remove axes of length one. So, after squeezing, [[1, 2, 3]] or [[1], [2], [3]] will become [1, 2, 3].
The output of the mentioned program will be:
a: [[9 3 2]] b: [[7 6 1]] r1 = a . b: 83 c: [[6] [8] [6]] d: [[2] [4] [9]] r2 = c . d: 98








































0 Comments