A class implementing Principal Component Analysis (PCA)
A class implementing Principal Component Analysis (PCA)This class provides functionality for dimensionality reduction using PCA. It computes principal components of the input data and allows projection onto a lower-dimensional space.
- Template Parameters
-
T | The data type for matrix elements (typically float or double) |
PCA<double> pca;
Matrix<double> data = your_data_matrix;
pca.fit(data);
Matrix<double> transformed = pca.transform(data, 2);
#pragma once
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <vector>
#include "../utils/matrix.hpp"
template<typename T>
class PCA {
public:
void fit(
const Matrix<T> &data,
bool center =
true,
bool scale =
false);
private:
std::vector<T> singular_values_;
std::vector<T> explained_variance_;
std::vector<T> explained_variance_ratio_;
std::vector<T> mean_;
std::vector<T> scale_;
bool is_fitted_ = false;
};
using PCAD = PCA<double>;
}
void fit(const Matrix< T > &data, bool center=true, bool scale=false)
Fit the PCA model to the data.
PCA()=default
Default constructor.
std::vector< T > singular_values() const
Get the singular values (square roots of eigenvalues)
Matrix< T > components() const
Get the principal components (eigenvectors)
std::vector< T > explained_variance_ratio() const
Get the explained variance ratio for each component.
Matrix< T > transform(const Matrix< T > &data, size_t n_components=0) const
Transform data to the principal component space.
Matrix< T > fit_transform(const Matrix< T > &data, size_t n_components=0, bool center=true, bool scale=false)
Fit the model and transform the data in one step.
Namespace containing traditional machine learning algorithms.