If you need to transpose a matrix in TensorFlow.js, then you can use the tf.transpose() function. It is possible to create a matrix using a tensor.
It shuffles rows as columns and columns as rows.
Syntax:
Parameter:
It takes a tensor as a parameter that has to be two-dimensional.
Example 1
Create a 2D-Boolean tensor with two rows and two columns and apply tf.transpose().
<!-- CDN Link that delivers the Tensorflow.js framework -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>
<script>
//tensor
let values = tf.tensor2d([10,20,30,40],[2,2]);
document.write("<b>Actual Tensor:</b> ",values);
</script>
<h3>Tensorflow.js - tf.transpose(tensor) </h3>
<script>
//tf.transpose(values)
document.write("<b>Transpose: </b>",tf.transpose(values));
</script>
</body>
</html>
Output:
Actual tensor matrix is:
30 40]
Transposed Matrix is:
20 40]
Example 2
Create a 2D-Boolean tensor with four rows and two columns and apply the tf.transpose() function.
<!-- CDN Link that delivers the Tensorflow.js framework -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<body>
<script>
//tensor
let values = tf.tensor2d([1,2,3,4,5,6,7,8],[4,2]);
document.write("<b>Actual Tensor:</b> ",values);
</script>
<h3>Tensorflow.js - tf.transpose(tensor) </h3>
<script>
//tf.transpose(values)
document.write("<b>Transpose: </b>",tf.transpose(values));
</script>
</body>
</html>
Output:
Actual tensor matrix is:
3 4
5 6
7 8]
Here is the Transposed Matrix:
2 4 6 8]
Example 3
Create a 2D-Boolean tensor with three rows and three columns and apply the tf.transpose() function.
<!-- CDN Link that delivers the Tensorflow.js framework 🡪
<script s”c="https://cdn.jsdelivr.net/npm/@tensorflow/t”js"></script>
<body>
<script>
//tensor
let values = tf.tensor2d([1.23,5.67,5.3,6.7,8.9,1,3,5,8],[3,3]);
document.wri“e("<b>Actual Tensor:</“> ",values);
</script>
<h3>Tensorflow.–s - tf.transpose(tensor) </h3>
<script>
//tf.transpose(values)
document.wri“e("<b>Transpose: <”b>",tf.transpose(values));
</script>
</body>
</html>
Output:
Conclusion
This article shows how the tf.transpose() function in the TensorFlow.js library is used to transpose a tensor matrix. It shuffles rows as columns and columns as rows. Make sure that the tensor is two-dimensional. With the help of content delivery Network Link, we include the TensorFlow.js library.