Coverage for src/abm_shape_collection/fit_pca_model.py: 100%
11 statements
« prev ^ index » next coverage.py v7.1.0, created at 2024-09-25 19:34 +0000
« prev ^ index » next coverage.py v7.1.0, created at 2024-09-25 19:34 +0000
1import numpy as np
2from sklearn.decomposition import PCA
5def fit_pca_model(features: np.ndarray, components: int, ordering: np.ndarray) -> PCA:
6 """
7 Fit PCA model to given data.
9 Parameters
10 ----------
11 features
12 Feature data (shape = num_samples x num_feature).
13 components
14 Number of components to keep.
15 ordering
16 Data used to reorient components.
18 Returns
19 -------
20 :
21 Fit PCA object.
22 """
24 # Fit data.
25 pca = PCA(n_components=components)
26 pca = pca.fit(features)
28 # Reorient features by ordering data.
29 transform = pca.transform(features)
30 for i in range(components):
31 pearson = np.corrcoef(ordering, transform[:, i])
32 if pearson[0, 1] < 0:
33 pca.components_[i] = pca.components_[i] * -1
35 return pca