The PCA class performs Principal Component Analysis for dimensionality reduction by projecting data onto its principal components.
Constructor
Number of principal components to retain
PCA pca(2); // Reduce to 2 dimensions
Methods
fit
Fit the PCA model to the training data.
void fit(const Eigen::MatrixXd& data)
data
const Eigen::MatrixXd&
required
Training data matrix where rows are samples and columns are features
Example
Eigen::MatrixXd training_data(100, 10); // 100 samples, 10 features
// ... populate training_data ...
PCA pca(3); // Reduce to 3 principal components
pca.fit(training_data);
Transform data to the reduced dimensional space.
Eigen::MatrixXd transform(const Eigen::MatrixXd& data)
data
const Eigen::MatrixXd&
required
Data matrix to transform
Transformed data in the reduced dimensional space
Example
Eigen::MatrixXd test_data(50, 10); // 50 samples, 10 features
// ... populate test_data ...
Eigen::MatrixXd transformed = pca.transform(test_data);
// transformed has shape (50, 3) if num_components = 3
Reconstruct data from the reduced dimensional representation back to the original space.
Eigen::MatrixXd inverse_transform(const Eigen::MatrixXd& transformed_data)
transformed_data
const Eigen::MatrixXd&
required
Data in the reduced dimensional space
Reconstructed data in the original dimensional space
Example
Eigen::MatrixXd transformed = pca.transform(test_data);
Eigen::MatrixXd reconstructed = pca.inverse_transform(transformed);
// reconstructed approximates test_data
get_components
Get the principal components matrix.
Eigen::MatrixXd get_components()
Matrix of principal components
Example
Eigen::MatrixXd components = pca.get_components();
std::cout << "Principal components:\n" << components << std::endl;
get_mean
Get the mean vector computed from the training data.
Eigen::VectorXd get_mean()
Mean vector of the training data
Example
Eigen::VectorXd mean = pca.get_mean();
std::cout << "Data mean: " << mean.transpose() << std::endl;
Complete example
#include "PCA.h"
#include <Eigen/Dense>
#include <iostream>
int main() {
// Create training data
Eigen::MatrixXd data(100, 5); // 100 samples, 5 features
data.setRandom();
// Initialize PCA with 2 components
PCA pca(2);
// Fit the model
pca.fit(data);
// Transform data
Eigen::MatrixXd transformed = pca.transform(data);
std::cout << "Transformed shape: " << transformed.rows()
<< "x" << transformed.cols() << std::endl;
// Reconstruct data
Eigen::MatrixXd reconstructed = pca.inverse_transform(transformed);
// Get components and mean
Eigen::MatrixXd components = pca.get_components();
Eigen::VectorXd mean = pca.get_mean();
return 0;
}