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]