Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dot product of two vectors in tensorflow

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?

like image 367
user6952886 Avatar asked Nov 18 '16 06:11

user6952886


People also ask

How do you find the dot product of two matrices in TensorFlow?

js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf. dot() function is used to compute the dot product of two given matrices or vectors, t1 and t2.

What is the dot product of a vector and a tensor?

The tensor product of two vectors represents a dyad, which is a linear vector transformation. A dyad is a special tensor – to be discussed later –, which explains the name of this product. Because it is often denoted without a symbol between the two vectors, it is also referred to as the open product.

What is a dot product of two vectors in Python?

Dot product of two vectors in python For two scalars, their dot product is equivalent to a simple multiplication. Example: import numpy as np a1 = 10 b1 = 5 print(np.dot(a1,b1))

What is TensorFlow Matmul?

Multiplies matrix a by matrix b , producing a * b . The inputs must, following any transpositions, be tensors of rank >= 2 where the inner 2 dimensions specify valid matrix multiplication arguments, and any further outer dimensions match.


2 Answers

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 
like image 181
Ishant Mrinal Avatar answered Sep 22 '22 19:09

Ishant Mrinal


In addition to tf.reduce_sum(tf.multiply(x, y)), you can also do tf.matmul(x, tf.reshape(y, [-1, 1])).

like image 24
yuefengz Avatar answered Sep 20 '22 19:09

yuefengz