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?
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.
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.
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))
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.
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
In addition to tf.reduce_sum(tf.multiply(x, y))
, you can also do tf.matmul(x, tf.reshape(y, [-1, 1]))
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With