How To Calculate Eigenvectors And Eigenvalues With Numpy

Next Story

How To Calculate Dot Product With Numpy

Eigenvectors and eigenvalues with numpy

 

In machine learning, eigenvectors and eigenvalues come up quite a bit.

They are used in a variety of data science techniques such as Principal Component Analysis for dimensionality reduction of features.

Let’s take a look at how to calculate these linear algebra values efficiently with Numpy, a popular python numerical computation library, for a matrix.

Let’s first import our numpy package as np.

import numpy as np

Next, let’s create a sample matrix to calculate eigenvalues and eigenvectors for.

example_matrix = np.array([
  [1,2,3,4],
  [5,6,7,8],
  [9,10,11,12],
  [13,14,15,16]
])

Sweet, now we have a matrix to play with.

Numpy makes it super simple to get eigenvectors and eigenvalues for this.

eigenvalues, eigenvectors = np.linalg.eig(example_matrix)

Now, we can access the values of the eigenvalues and eigenvectors.

eigenvalues
# array([  3.62093727e+01,  -2.20937271e+00,  -4.65206927e-16, -2.13836670e-15])

eigenvectors
# array([[-0.15115432, -0.72704996,  0.02799736, -0.2749507 ],[-0.34923733, -0.28320876,  0.37038479,  0.71968426],[-0.54732033,  0.16063243, -0.82476165, -0.61451644],[-0.74540333,  0.60447363,  0.4263795 ,  0.16978287]])

The full code example can be found below.


import numpy as np

example_matrix = np.array([
  [1,2,3,4],
  [5,6,7,8],
  [9,10,11,12],
  [13,14,15,16]
])

eigenvalues, eigenvectors = np.linalg.eig(example_matrix)

eigenvalues
# array([  3.62093727e+01,  -2.20937271e+00,  -4.65206927e-16, -2.13836670e-15])

eigenvectors
# array([[-0.15115432, -0.72704996,  0.02799736, -0.2749507 ],[-0.34923733, -0.28320876,  0.37038479,  0.71968426],[-0.54732033,  0.16063243, -0.82476165, -0.61451644],[-0.74540333,  0.60447363,  0.4263795 ,  0.16978287]])
https://www.googletagmanager.com/gtag/js?id=UA-63695651-4