“Eigenvalues” and “eigenvectors” are important concepts in data analysis fields, such as Principal Component Analysis (PCA) and vibration analysis. By using NumPy’s np.linalg.eig() function, you can calculate these values all at once.
In this article, I will explain how to calculate them and how to handle the return values, using a 2×2 matrix as an example.
1. Calculating Eigenvalues and Eigenvectors
The np.linalg.eig() function calculates the eigenvalues and eigenvectors for the matrix passed as an argument and returns two values.
- 1st return value: List (array) of eigenvalues
- 2nd return value: Matrix of eigenvectors
Sample Code
Here, we will perform the calculation using a 2×2 matrix [[3, 1], [0, 2]], which makes it easy to verify the results.
import numpy as np
def eigen_calc_demo():
# 1. Define Matrix (Example: Upper triangular matrix)
# The eigenvalues should be the diagonal elements 3 and 2
matrix_x = np.array([
[3, 1],
[0, 2]
])
print("--- Original Matrix X ---")
print(matrix_x)
# 2. Calculate Eigenvalues and Eigenvectors
# w: Eigenvalues
# v: Eigenvectors
w, v = np.linalg.eig(matrix_x)
print("\n--- Eigenvalues (w) ---")
print(w)
print("\n--- Eigenvectors (v) ---")
print(v)
if __name__ == "__main__":
eigen_calc_demo()
Execution Result
--- Original Matrix X ---
[[3 1]
[0 2]]
--- Eigenvalues (w) ---
[3. 2.]
--- Eigenvectors (v) ---
[[ 1. -0.70710678]
[ 0. 0.70710678]]
2. How to Read Results and Important Points
Eigenvalues (w)
The output [3. 2.] represents the eigenvalues. Depending on the type of matrix, complex numbers may be returned.
Eigenvectors (v)
This is the most important point to note. The return value v is a matrix, but the eigenvectors are stored in the “column” (vertical) direction, not the “row” (horizontal) direction.
- The eigenvector corresponding to eigenvalue
3.(w[0]) is the 0th column ofv(vertical sequence[1., 0.]). - The eigenvector corresponding to eigenvalue
2.(w[1]) is the 1st column ofv(vertical sequence[-0.707..., 0.707...]).
To extract them in code, you write:
# Extract the eigenvector corresponding to the first eigenvalue
first_eigen_vector = v[:, 0]
Summary
- Function: Use
np.linalg.eig(matrix). - Return Values: Returned in the order of
eigenvalues, eigenvectors. - Caution: Eigenvectors are stored vertically (columns).
When using this function for tasks such as dimensionality reduction in machine learning, mixing up rows and columns is a frequent cause of bugs. Please be conscious of treating the data as columns.
