How to multiply k 2x2 Matrices by k 2x2 matrices in tensorflow?

Multi tool use
How to multiply k 2x2 Matrices by k 2x2 matrices in tensorflow?
I have 2 3D tensors in tensorflow, where the two tensors have the shape Kx2x2. The tensors represent a set of 2x2 matrices. Is there a way to multiply the 2x2 matrices in the first tensor with the corresponding matrix in the second so that I get a Kx2x2 tensor in the end?
3 Answers
3
You can use tf.matmul
.
tf.matmul
c = tf.matmul(a, b)
Ok. Maybe a bit more detail on the question should help. let a,b and c are Kx2x2 tensors. Now what I need is: c[i,:,:] = tf.matmul(a[i,:,:], b[i,:,:]) Then c[i,:,:] would be 2x2... However tensorflow does not allow to do such assignments and it would also be terribly slow...
– Todor Kostov
Jun 30 at 23:04
@TodorKostov See edit?
– coldspeed
Jun 30 at 23:16
Kosovo, just a heads up, you don't mention matrix multiplication anywhere. You just say you want to multiply two matrices together.
– Jay Calamari
Jul 1 at 19:48
You can do tf.matmul(a,b).
According to the tensorflow documentation,
tf.matmul returns:
A Tensor of the same type as a and b where each inner-most matrix is the product of the corresponding matrices in a and b.
output[..., i, j] = sum_k (a[..., i, k] * b[..., k, j]), for all indices i, j.
Note: This is matrix product, not element-wise product.
https://www.tensorflow.org/api_docs/python/tf/matmul
tf.matmul
is the correct operator for matrix multiplication. If the dimension of the tensor is over 2, the inner 2 specify the shape of the matrix. Hence the shape of two tensors must be [a1, a2, ..., an, x, y] and [a1, a2, ..., an, y, z], respectively ([K, 2, 2] in the OP's case).
tf.matmul
Sample Code
# Suppose X and Y are two tensors of the shape [K, 2, 2]
result = tf.matmul(X, Y)
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
No, in the question I asked about matrix multiplication. The documentation of tf.multiply states: "Returns x * y element-wise."
– Todor Kostov
Jun 30 at 22:57