Vector and matrix multiplication in TensorFlow __tesorflow

Source: Internet
Author: User

We only use the TensorFlow Tf.matmul () to do the operation between matrices, but require that each dimension of the matrix is greater than 2, if we multiply the vector and matrix, the function will be an error.

Specifically, we multiply a 2x2 matrix by using a vector of 2:

Import TensorFlow as tf
a = Tf.constant ([2, 3])
B = tf.constant ([[0, 1], [2, 3]])
C = Tf.matmul (A, b)
with Tf. Session () as Sess:
     print (Sess.run (c))
Will complain:
Valueerror:shape must be rank 2 but are rank 1 for ' Matmul_11 ' (op: ' Matmul ') with input shapes: [2], [2,2].

So how do you multiply a vector with a matrix?

We know that the essence of matrix multiplication is the linear combination of matrix vectors, using this property, we can multiply the matrix by point multiplication, from the realization of vector and matrix. Specifically as follows 1, matrix x vector

[[0, 1],      [2,
 [2, 3]]   X    3] 

Specific code implementation:

Import TensorFlow as tf
a = Tf.constant ([2, 3])
B = tf.constant ([[0, 1], [2, 3]])
mul =tf.reduce_sum (tf.multip Ly (A, B), Reduction_indices=1) with
TF. Session () as Sess:
print (Sess.run (mul))
The result:
[3 13]
2, vector x matrix
   [2, 3]  x  [[0, 1],      
              [2, 3]]     
This time you need to transpose the matrix, and then in the dot, then add the specific code as follows:

Import TensorFlow as tf
a = Tf.constant ([2, 3])
B = tf.constant ([[0, 1], [2, 3]])
mul =tf.reduce_sum (Tf.mul Tiply (A, tf.transpose (b, perm=[1, 0])), Reduction_indices=1) with
TF. Session () as Sess:
     print (Sess.run (mul))
Results:
[6 11]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.