Dot product of two vectors in tensorflow

user6952886 picture user6952886 · Nov 18, 2016 · Viewed 56.6k times · Source

I was wondering if there is an easy way to calculate the dot product of two vectors (i.e. 1-d tensors) and return a scalar value in tensorflow.

Given two vectors X=(x1,...,xn) and Y=(y1,...,yn), the dot product is dot(X,Y) = x1 * y1 + ... + xn * yn

I know that it is possible to achieve this by first broadcasting the vectors X and Y to a 2-d tensor and then using tf.matmul. However, the result is a matrix, and I am after a scalar.

Is there an operator like tf.matmul that is specific to vectors?

Answer

Ishant Mrinal picture Ishant Mrinal · Aug 23, 2017

One of the easiest way to calculate dot product between two tensors (vector is 1D tensor) is using tf.tensordot

a = tf.placeholder(tf.float32, shape=(5))
b = tf.placeholder(tf.float32, shape=(5))

dot_a_b = tf.tensordot(a, b, 1)

with tf.Session() as sess:
    print(dot_a_b.eval(feed_dict={a: [1, 2, 3, 4, 5], b: [6, 7, 8, 9, 10]}))
# results: 130.0