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=(
In addition to tf.reduce_sum(tf.multiply(x, y))
, you can also do tf.matmul(x, tf.reshape(y, [-1, 1]))
.
import tensorflow as tf
x = tf.Variable([1, -2, 3], tf.float32, name='x')
y = tf.Variable([-1, 2, -3], tf.float32, name='y')
dot_product = tf.reduce_sum(tf.multiply(x, y))
sess = tf.InteractiveSession()
init_op = tf.global_variables_initializer()
sess.run(init_op)
dot_product.eval()
Out[46]: -14
Here, x and y are both vectors. We can do element wise product and then use tf.reduce_sum to sum the elements of the resulting vector. This solution is easy to read and does not require reshaping.
Interestingly, it does not seem like there is a built in dot product operator in the docs.
Note that you can easily check intermediate steps:
In [48]: tf.multiply(x, y).eval()
Out[48]: array([-1, -4, -9], dtype=int32)
you can use tf.matmul and tf.transpose
tf.matmul(x,tf.transpose(y))
or
tf.matmul(tf.transpose(x),y)
depending on the dimensions of x and y