Dot product of two vectors in tensorflow

前端 未结 9 1128
悲&欢浪女
悲&欢浪女 2021-01-01 12:36

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=(

相关标签:
9条回答
  • 2021-01-01 12:50

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

    0 讨论(0)
  • 2021-01-01 12:53
    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)
    
    0 讨论(0)
  • 2021-01-01 12:55

    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

    0 讨论(0)
提交回复
热议问题