How to Calculate NumPy Trace of a Matrix using np.trace ?

This recipe will cover diverse techniques on how to accurately calculate the NumPy trace of the matrix for all your data science tasks.| ProjectPro

NumPy, a fundamental library for numerical computing in Python, provides a powerful function for calculating the trace of a matrix - np.trace. The trace of a matrix is the sum of its diagonal elements. Check out this numpy code example to learn what np.trace is, and how to Calculate NumPy Trace of a Matrix using np.trace, and even touch upon an alternative method to trace a matrix in Python without using NumPy.

What is np.trace in NumPy?

np.trace is a function in the NumPy library that calculates the sum of the diagonal elements of a matrix. Mathematically, the trace of an n×n matrix A is denoted as Tr(A) and is calculated as:

trace of a matrix

Here, Aii  represents the elements on the main diagonal of matrix A. Numpy simplifies this calculation with the np.trace() function, making it a convenient tool for matrix manipulation.

This operation is particularly useful in various mathematical and scientific applications, such as linear algebra and statistics. 

Partial Trace with np.trace 

The np.trace function can also be used to calculate the partial trace of a matrix. For instance, consider a bipartite system with a composite Hilbert space. To find the partial trace of one subsystem, use the following formula:

Partial trace NumPy

How to Calculate the Trace of a Matrix in NumPy?

Calculating the trace of a matrix in NumPy is straightforward using the np.trace function. Let's see a step-by-step guide:

Step 1 - Importing Library

    import numpy as np

We have only imported numpy which is needed.

Step 2 - Creating Matrix

We have created a matrix on which we will perform operations.

    matrix = np.array([[1, 2, 3],

                       [4, 5, 6],

                       [7, 8, 9],

                       [10, 11, 12]])

Step 3 - Calculating Trace of Matrix

We know that the trace of a matrix is calculated by summing the values of diagonals. So we have done the same to find the trace.

    print("Calculate the tracre of the matrix: ", matrix.diagonal().sum())

So the output comes as

Calculate the trace of the matrix:  15

How to Trace a Matrix in Python Without NumPy?

While np.trace is a powerful tool, you can trace a matrix in Python without using NumPy, albeit with more manual steps. Here's an example using a simple loop:

In this non-NumPy approach, we use a loop to iterate over the diagonal elements and sum them up. While this method works, NumPy's np.trace offers a more concise and efficient solution for numerical operations involving matrices.

Practice more NumPy Operations with ProjectPro! 

The ability to efficiently manipulate and analyze matrices is crucial in various applications, from machine learning to scientific research. This recipe has covered all the significance of the NumPy trace function and how it simplifies matrix operations. However, theoretical knowledge alone is not sufficient for true mastery. Practical experience through real-world projects is the key to solidifying your understanding and honing your skills. ProjectPro has a repository of over 250 hands-on projects in data science and big data, providing a platform for learners to apply their knowledge in a practical setting. Engaging in ProjectPro's projects not only reinforce your theoretical understanding but also help you gain insights into solving real-world problems. The platform offers a diverse range of projects, ensuring that you encounter challenges that mimic those found in the professional realm. This hands-on experience is crucial for building confidence and proficiency in utilizing NumPy and other tools when building data science projects.

Download Materials

What Users are saying..

profile image

Ed Godalle

Director Data Analytics at EY / EY Tech
linkedin profile url

I am the Director of Data Analytics with over 10+ years of IT experience. I have a background in SQL, Python, and Big Data working with Accenture, IBM, and Infosys. I am looking to enhance my skills... Read More

Relevant Projects

Learn Hyperparameter Tuning for Neural Networks with PyTorch
In this Deep Learning Project, you will learn how to optimally tune the hyperparameters (learning rate, epochs, dropout, early stopping) of a neural network model in PyTorch to improve model performance.

MLOps Project to Build Search Relevancy Algorithm with SBERT
In this MLOps SBERT project you will learn to build and deploy an accurate and scalable search algorithm on AWS using SBERT and ANNOY to enhance search relevancy in news articles.

Image Classification Model using Transfer Learning in PyTorch
In this PyTorch Project, you will build an image classification model in PyTorch using the ResNet pre-trained model.

NLP and Deep Learning For Fake News Classification in Python
In this project you will use Python to implement various machine learning methods( RNN, LSTM, GRU) for fake news classification.

Recommender System Machine Learning Project for Beginners-4
Collaborative Filtering Recommender System Project - Comparison of different model based and memory based methods to build recommendation system using collaborative filtering.

End-to-End Snowflake Healthcare Analytics Project on AWS-1
In this Snowflake Healthcare Analytics Project, you will leverage Snowflake on AWS to predict patient length of stay (LOS) in hospitals. The prediction of LOS can help in efficient resource allocation, lower the risk of staff/visitor infections, and improve overall hospital functioning.

Build a Autoregressive and Moving Average Time Series Model
In this time series project, you will learn to build Autoregressive and Moving Average Time Series Models to forecast future readings, optimize performance, and harness the power of predictive analytics for sensor data.

Learn How to Build a Logistic Regression Model in PyTorch
In this Machine Learning Project, you will learn how to build a simple logistic regression model in PyTorch for customer churn prediction.

Build a Multi-Class Classification Model in Python on Saturn Cloud
In this machine learning classification project, you will build a multi-class classification model in Python on Saturn Cloud to predict the license status of a business.

Time Series Forecasting with LSTM Neural Network Python
Deep Learning Project- Learn to apply deep learning paradigm to forecast univariate time series data.