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

Anand Kumpatla

Sr Data Scientist @ Doubleslash Software Solutions Pvt Ltd
linkedin profile url

ProjectPro is a unique platform and helps many people in the industry to solve real-life problems with a step-by-step walkthrough of projects. A platform with some fantastic resources to gain... Read More

Relevant Projects

Linear Regression Model Project in Python for Beginners Part 1
Machine Learning Linear Regression Project in Python to build a simple linear regression model and master the fundamentals of regression for beginners.

Walmart Sales Forecasting Data Science Project
Data Science Project in R-Predict the sales for each department using historical markdown data from the Walmart dataset containing data of 45 Walmart stores.

Build a Multi Touch Attribution Machine Learning Model in Python
Identifying the ROI on marketing campaigns is an essential KPI for any business. In this ML project, you will learn to build a Multi Touch Attribution Model in Python to identify the ROI of various marketing efforts and their impact on conversions or sales..

Learn to Build a Polynomial Regression Model from Scratch
In this Machine Learning Regression project, you will learn to build a polynomial regression model to predict points scored by the sports team.

Detectron2 Object Detection and Segmentation Example Python
Object Detection using Detectron2 - Build a Dectectron2 model to detect the zones and inhibitions in antibiogram images.

OpenCV Project to Master Advanced Computer Vision Concepts
In this OpenCV project, you will learn to implement advanced computer vision concepts and algorithms in OpenCV library using Python.

Word2Vec and FastText Word Embedding with Gensim in Python
In this NLP Project, you will learn how to use the popular topic modelling library Gensim for implementing two state-of-the-art word embedding methods Word2Vec and FastText models.

AWS MLOps Project for Gaussian Process Time Series Modeling
MLOps Project to Build and Deploy a Gaussian Process Time Series Model in Python on AWS

Build CNN for Image Colorization using Deep Transfer Learning
Image Processing Project -Train a model for colorization to make grayscale images colorful using convolutional autoencoders.

Build an End-to-End AWS SageMaker Classification Model
MLOps on AWS SageMaker -Learn to Build an End-to-End Classification Model on SageMaker to predict a patient’s cause of death.