# Calculate the Trace of Matrix in TensorFlow – TensorFlow Tutorial

By | July 15, 2019

The trace of a matrix is basic operation in deep learning, in this tutorial, we will write some examples to show how to calculte it using tensorflow.

Understand The Trace of a Matrix for Beginners – Deep Learning Tutorial

## Preliminaries

import tensorflow as tf
import numpy as np

## Create 3*3 matrix

A = tf.constant([[1,2,3],[4,5,6],[7,8,9]], dtype=tf.float32)

Compute matrix A trace

A_tr = tf.trace(A)

## Output the trace value

init = tf.global_variables_initializer()
init_local = tf.local_variables_initializer()
with tf.Session() as sess:
sess.run([init, init_local])
np.set_printoptions(precision=4, suppress=True)
tr_a = (sess.run([A_tr]))
print tr_a

The value is: 15.0

If matrix A is not n * n?

## Create a matrix A 3 * 4

A = tf.constant([[1,2,3,5],[4,5,6,7],[7,8,9,8]], dtype=tf.float32)

## Compute its trace

A_tr_ = tf.trace(A)

The trace value is also 15.0

Meanwhile, if the dimension of matrix A is not 2, how about 2 * 3 * 4

## Create a 2 * 3 * 4 matrix

B = tf.Variable(tf.random_uniform([2,3,4], -0.01, 0.01), dtype=tf.float32)

## Compute matrix B trace

B_tr = tf.trace(B)

The value is:

[0.0093 0.0114]