tf.transpose - Use TensorFlow's transpose operation to transpose a TensorFlow matrix tensor
tf.transpose - Use TensorFlow's transpose operation to transpose a TensorFlow matrix tensor
This video will show you how to use TensorFlow’s transpose operation to transpose a TensorFlow matrix tensor.
First, we import TensorFlow as tf.
import tensorflow as tf
Next, we print out what version of TensorFlow we are using.
print(tf.__version__)
We are using TensorFlow 1.10.0.
Let’s start out by creating a simple 5x2 TensorFlow constant tensor.
example_tensor = tf.constant(
[
[1.1, 2.2],
[3.3, 4.4],
[5.5, 6.6],
[7.7, 8.8],
[9.9, 0.0]
])
So we use tf.constant, then we have our data structure.
We can notice that every single number has a decimal point, so we’re going to be using floating point numbers, and the numbers go from 0.0 all the way to 9.9.
So one, two, three, four, five rows, and two columns.
We assign that to the Python variable example_tensor.
Let’s print our tensor to see what we have.
print(example_tensor)
We see that it’s a TensorFlow tensor, the shape is 5x2, and the data type is float32.
Note that since we aren’t running the tensor in a TensorFlow session, we can’t see the values at this time.
Let’s now use TensorFlow’s transpose operation to transpose our matrix.
transposed_tensor = tf.transpose(example_tensor)
So tf.transpose, we pass in our example_tensor, and we assign the result to transposed_tensor Python variable.
Let’s print our transposed matrix to see what we have.
print(transposed_tensor)
We see that it’s still a tensor, we see that the shape is now 2x5 whereas before it was 5x2, and the data type stayed the same.
Like before, we don’t see the values yet because we’re not running it in a TensorFlow session.
Now that we have all the TensorFlow variables we want, let’s launch the graph in a session so that we can evaluate the tensors.
sess = tf.Session()
Now that we have the session, let’s initialize all the global variables in the graph.
sess.run(tf.global_variables_initializer())
First, let’s print the example tensor in a TensorFlow session.
print(sess.run(example_tensor))
We see that it is one, two, three, four, five rows, and two columns, and all of our numbers are there.
Next, let’s print the transposed matrix in a TensorFlow session, and we see that it has been transposed.
print(sess.run(transposed_tensor))
Before, we had five rows and two columns.
Now, we have five columns and two rows.
The first element of each of these rows is now an element in the first row, the second element of each of these rows is now an element in the second row, and all of our numbers are still there, 0.0 all the way to 9.9.
Perfect - We were able to use TensorFlow’s transpose operation to transpose a TensorFlow matrix tensor.
Receive the Data Science Weekly Newsletter every Thursday
Easy to unsubscribe at any time. Your e-mail address is safe.