5#include <xtensor-blas/xlinalg.hpp>
11 if (data.rows() < 2 || data.cols() < 2) {
12 throw std::invalid_argument(
"Data matrix must have at least 2 rows and 2 columns");
39 std::fill(mean_.begin(), mean_.end(), 0);
57 if (scale_[
j] < 1
e-10) {
73 auto cov = xt::linalg::dot(xt::transpose(
X),
X) /
static_cast<T
>(
n_samples - 1);
81 std::vector<size_t>
indices(eigenvalues.size());
84 [&eigenvalues](
size_t i1,
size_t i2) { return eigenvalues(i1) > eigenvalues(i2); });
93 explained_variance_[
i] = eigenvalues(
indices[
i]);
102 singular_values_[
i] = std::sqrt(explained_variance_[
i]);
119 throw std::runtime_error(
"PCA model has not been fitted");
126 throw std::invalid_argument(
"Data has wrong number of features");
165 throw std::runtime_error(
"PCA model has not been fitted");
167 return explained_variance_ratio_;
173 throw std::runtime_error(
"PCA model has not been fitted");
181 throw std::runtime_error(
"PCA model has not been fitted");
183 return singular_values_;
void fit(const Matrix< T > &data)
Fit the K-Means model to the data.
void fit(const Matrix< T > &data, bool center=true, bool scale=false)
Fit the PCA model to the data.
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.
T sum(const Matrix< T > &matrix)
Calculate sum of all matrix elements.
Principal Component Analysis implementation.