SKLearner Home | About | Contact | Examples

Scikit-Learn make_spd_matrix() Dataset

Generate an SPD matrix using make_spd_matrix() from sklearn.datasets. SPD matrices are often used in optimization problems and various statistical methods.

Key function arguments include n_dim to specify the dimension of the matrix and random_state to ensure reproducibility.

This example demonstrates the creation of a synthetic SPD matrix, suitable for testing algorithms that require such a matrix structure.

from sklearn.datasets import make_spd_matrix
import numpy as np

# Generate an SPD matrix of dimension 5
spd_matrix = make_spd_matrix(n_dim=5, random_state=42)

# Display the shape and type of the matrix
print(f"Matrix shape: {spd_matrix.shape}")
print(f"Matrix type: {type(spd_matrix)}")

# Show the matrix
print(f"SPD Matrix:\n{spd_matrix}")

# Verify that the matrix is symmetric positive definite
eigenvalues = np.linalg.eigvals(spd_matrix)
print(f"Eigenvalues of the matrix: {eigenvalues}")
print(f"Is the matrix SPD? {np.all(eigenvalues > 0)}")

Running the example gives an output like:

Matrix shape: (5, 5)
Matrix type: <class 'numpy.ndarray'>
SPD Matrix:
[[ 0.97766615 -0.23316137 -1.21865345 -0.39562     0.92189636]
 [-0.23316137  0.64354244  1.047413    0.38781049 -0.53749089]
 [-1.21865345  1.047413    2.97417899  1.05308457 -1.61639237]
 [-0.39562     0.38781049  1.05308457  0.90057916 -0.78071011]
 [ 0.92189636 -0.53749089 -1.61639237 -0.78071011  1.64198243]]
Eigenvalues of the matrix: [5.44183294 0.1039316  0.71926352 0.55294183 0.31997928]
Is the matrix SPD? True

The steps are as follows:

  1. Import the make_spd_matrix function from sklearn.datasets:

    • This function generates a symmetric positive definite matrix.
  2. Generate an SPD matrix:

    • Use make_spd_matrix(n_dim=5, random_state=42) to create a 5x5 SPD matrix.
    • n_dim specifies the dimension, while random_state ensures reproducibility.
  3. Display the matrix shape and type:

    • Use spd_matrix.shape and type(spd_matrix) to verify the structure and type of the generated matrix.
  4. Print the SPD matrix:

    • Show the contents of the matrix to inspect its values.
  5. Verify that the matrix is symmetric positive definite:

    • Calculate the eigenvalues using np.linalg.eigvals(spd_matrix).
    • Check that all eigenvalues are positive to confirm the matrix’s SPD property using np.all(eigenvalues > 0).

This example demonstrates the generation and verification of a symmetric positive definite matrix using scikit-learn’s make_spd_matrix() function, providing a basis for further applications in optimization and statistical methods.



See Also