Deep Learning Algorithm Implementations 1.0.0
C++ implementations of fundamental deep learning algorithms
Loading...
Searching...
No Matches
/home/runner/work/deep-learning-algo-impls/deep-learning-algo-impls/include/ml/pca.hpp

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
TThe data type for matrix elements (typically float or double)
// Create a PCA object
PCA<double> pca;
// Fit PCA to data
Matrix<double> data = your_data_matrix;
pca.fit(data);
// Transform data to reduced dimensions
Matrix<double> transformed = pca.transform(data, 2); // Reduce to 2 dimensions
#pragma once
#include <algorithm>
#include <cmath>
#include <stdexcept>
#include <vector>
#include "../utils/matrix.hpp"
namespace ml {
using namespace utils;
template<typename T>
class PCA {
public:
PCA() = default;
void fit(const Matrix<T> &data, bool center = true, bool scale = false);
Matrix<T> transform(const Matrix<T> &data, size_t n_components = 0) const;
Matrix<T> fit_transform(const Matrix<T> &data, size_t n_components = 0, bool center = true, bool scale = false);
std::vector<T> explained_variance_ratio() const;
std::vector<T> singular_values() const;
private:
Matrix<T> components_;
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;
};
// Type aliases for common use cases
using PCAF = PCA<float>;
using PCAD = PCA<double>;
} // namespace ml
void fit(const Matrix< T > &data, bool center=true, bool scale=false)
Fit the PCA model to the data.
Definition pca.cpp:10
PCA()=default
Default constructor.
std::vector< T > singular_values() const
Get the singular values (square roots of eigenvalues)
Definition pca.cpp:179
Matrix< T > components() const
Get the principal components (eigenvectors)
Definition pca.cpp:171
std::vector< T > explained_variance_ratio() const
Get the explained variance ratio for each component.
Definition pca.cpp:163
Matrix< T > transform(const Matrix< T > &data, size_t n_components=0) const
Transform data to the principal component space.
Definition pca.cpp:117
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.
Definition pca.cpp:157
Namespace containing traditional machine learning algorithms.
Definition kmeans.hpp:15
PCA< float > PCAF
Definition pca.hpp:109
PCA< double > PCAD
Definition pca.hpp:110