pdmlabs.method.pca_tsb#
PCA class modifed over from PYOD package
Functions
|
Check if an input is within the defined range. |
|
Classes
|
Principal component analysis (PCA) can be used in detecting outliers. PCA is a linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. In this procedure, covariance matrix of the data can be decomposed to orthogonal vectors, called eigenvectors, associated with eigenvalues. The eigenvectors with high eigenvalues capture most of the variance in the data. Therefore, a low dimensional hyperplane constructed by k eigenvectors can capture most of the variance in the data. However, outliers are different from normal data points, which is more obvious on the hyperplane constructed by the eigenvectors with small eigenvalues. Therefore, outlier scores can be obtained as the sum of the projected distance of a sample on all eigenvectors. See :cite:`shyu2003novel,aggarwal2015outlier` for details. Score(X) = Sum of weighted euclidean distance between each sample to the hyperplane constructed by the selected eigenvectors :param n_components: Number of components to keep. if n_components is not set all components are kept:: n_components == min(n_samples, n_features) if n_components == 'mle' and svd_solver == 'full', Minka's MLE is used to guess the dimension if |
- class pdmlabs.method.pca_tsb.PCA(n_components=None, n_selected_components=None, contamination=0.1, copy=True, whiten=False, svd_solver='auto', tol=0.0, iterated_power='auto', random_state=None, weighted=True, standardization=True)#
Bases:
objectPrincipal component analysis (PCA) can be used in detecting outliers. PCA is a linear dimensionality reduction using Singular Value Decomposition of the data to project it to a lower dimensional space. In this procedure, covariance matrix of the data can be decomposed to orthogonal vectors, called eigenvectors, associated with eigenvalues. The eigenvectors with high eigenvalues capture most of the variance in the data. Therefore, a low dimensional hyperplane constructed by k eigenvectors can capture most of the variance in the data. However, outliers are different from normal data points, which is more obvious on the hyperplane constructed by the eigenvectors with small eigenvalues. Therefore, outlier scores can be obtained as the sum of the projected distance of a sample on all eigenvectors. See :cite:`shyu2003novel,aggarwal2015outlier` for details. Score(X) = Sum of weighted euclidean distance between each sample to the hyperplane constructed by the selected eigenvectors :param n_components: Number of components to keep.
- if n_components is not set all components are kept::
n_components == min(n_samples, n_features)
if n_components == ‘mle’ and svd_solver == ‘full’, Minka’s MLE is used to guess the dimension if
0 < n_components < 1and svd_solver == ‘full’, select the number of components such that the amount of variance that needs to be explained is greater than the percentage specified by n_components n_components cannot be equal to n_features for svd_solver == ‘arpack’.- Parameters:
n_selected_components (int, optional (default=None)) – Number of selected principal components for calculating the outlier scores. It is not necessarily equal to the total number of the principal components. If not set, use all principal components.
contamination (float in (0., 0.5), optional (default=0.1)) – The amount of contamination of the data set, i.e. the proportion of outliers in the data set. Used when fitting to define the threshold on the decision function.
copy (bool (default True)) – If False, data passed to fit are overwritten and running fit(X).transform(X) will not yield the expected results, use fit_transform(X) instead.
whiten (bool, optional (default False)) – When True (False by default) the components_ vectors are multiplied by the square root of n_samples and then divided by the singular values to ensure uncorrelated outputs with unit component-wise variances. Whitening will remove some information from the transformed signal (the relative variance scales of the components) but can sometime improve the predictive accuracy of the downstream estimators by making their data respect some hard-wired assumptions.
svd_solver (string {'auto', 'full', 'arpack', 'randomized'}) –
- auto :
the solver is selected by a default policy based on X.shape and n_components: if the input data is larger than 500x500 and the number of components to extract is lower than 80% of the smallest dimension of the data, then the more efficient ‘randomized’ method is enabled. Otherwise the exact full SVD is computed and optionally truncated afterwards.
- full :
run exact full SVD calling the standard LAPACK solver via scipy.linalg.svd and select the components by postprocessing
- arpack :
run SVD truncated to n_components calling ARPACK solver via scipy.sparse.linalg.svds. It requires strictly 0 < n_components < X.shape[1]
- randomized :
run randomized SVD by the method of Halko et al.
tol (float >= 0, optional (default .0)) – Tolerance for singular values computed by svd_solver == ‘arpack’.
iterated_power (int >= 0, or 'auto', (default 'auto')) – Number of iterations for the power method computed by svd_solver == ‘randomized’.
random_state (int, RandomState instance or None, optional (default None)) – If int, random_state is the seed used by the random number generator; If RandomState instance, random_state is the random number generator; If None, the random number generator is the RandomState instance used by np.random. Used when
svd_solver== ‘arpack’ or ‘randomized’.weighted (bool, optional (default=True)) – If True, the eigenvalues are used in score computation. The eigenvectors with small eigenvalues comes with more importance in outlier score calculation.
standardization (bool, optional (default=True)) – If True, perform standardization first to convert data to zero mean and unit variance. See http://scikit-learn.org/stable/auto_examples/preprocessing/plot_scaling_importance.html
- components_#
Principal axes in feature space, representing the directions of maximum variance in the data. The components are sorted by
explained_variance_.- Type:
array, shape (n_components, n_features)
- explained_variance_#
The amount of variance explained by each of the selected components. Equal to n_components largest eigenvalues of the covariance matrix of X.
- Type:
array, shape (n_components,)
- explained_variance_ratio_#
Percentage of variance explained by each of the selected components. If
n_componentsis not set then all components are stored and the sum of explained variances is equal to 1.0.- Type:
array, shape (n_components,)
- singular_values_#
The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the
n_componentsvariables in the lower-dimensional space.- Type:
array, shape (n_components,)
- mean_#
Per-feature empirical mean, estimated from the training set. Equal to X.mean(axis=0).
- Type:
array, shape (n_features,)
- n_components_#
The estimated number of components. When n_components is set to ‘mle’ or a number between 0 and 1 (with svd_solver == ‘full’) this number is estimated from input data. Otherwise it equals the parameter n_components, or n_features if n_components is None.
- Type:
int
- noise_variance_#
The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to computed the estimated data covariance and score samples. Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X.
- Type:
float
- decision_scores_#
The outlier scores of the training data. The higher, the more abnormal. Outliers tend to have higher scores. This value is available once the detector is fitted.
- Type:
numpy array of shape (n_samples,)
- threshold_#
The threshold is based on
contamination. It is then_samples * contaminationmost abnormal samples indecision_scores_. The threshold is calculated for generating binary outlier labels.- Type:
float
- labels_#
The binary labels of the training data. 0 stands for inliers and 1 for outliers/anomalies. It is generated by applying
threshold_ondecision_scores_.- Type:
int, either 0 or 1
- decision_function(X)#
Predict raw anomaly score of X using the fitted detector. The anomaly score of an input sample is computed based on different detector algorithms. For consistency, outliers are assigned with larger anomaly scores. :param X: The training input samples. Sparse matrices are accepted only
if they are supported by the base estimator.
- Returns:
anomaly_scores – The anomaly score of the input samples.
- Return type:
numpy array of shape (n_samples,)
- property explained_variance_#
The amount of variance explained by each of the selected components. Equal to n_components largest eigenvalues of the covariance matrix of X. Decorator for scikit-learn PCA attributes.
- property explained_variance_ratio_#
Percentage of variance explained by each of the selected components. If
n_componentsis not set then all components are stored and the sum of explained variances is equal to 1.0. Decorator for scikit-learn PCA attributes.
- fit(X, y=None)#
Fit detector. y is ignored in unsupervised methods. :param X: The input samples. :type X: numpy array of shape (n_samples, n_features) :param y: Not used, present for API consistency by convention. :type y: Ignored
- Returns:
self – Fitted estimator.
- Return type:
object
- property mean_#
Per-feature empirical mean, estimated from the training set. Decorator for scikit-learn PCA attributes.
- property noise_variance_#
The estimated noise covariance following the Probabilistic PCA model from Tipping and Bishop 1999. See “Pattern Recognition and Machine Learning” by C. Bishop, 12.2.1 p. 574 or http://www.miketipping.com/papers/met-mppca.pdf. It is required to computed the estimated data covariance and score samples. Equal to the average of (min(n_features, n_samples) - n_components) smallest eigenvalues of the covariance matrix of X. Decorator for scikit-learn PCA attributes.
- property singular_values_#
The singular values corresponding to each of the selected components. The singular values are equal to the 2-norms of the
n_componentsvariables in the lower-dimensional space. Decorator for scikit-learn PCA attributes.
- pdmlabs.method.pca_tsb.check_parameter(param, low=-2147483647, high=2147483647, param_name='', include_left=False, include_right=False)#
Check if an input is within the defined range. :param param: The input parameter to check. :type param: int, float :param low: The lower bound of the range. :type low: int, float :param high: The higher bound of the range. :type high: int, float :param param_name: The name of the parameter. :type param_name: str, optional (default=’’) :param include_left: Whether includes the lower bound (lower bound <=). :type include_left: bool, optional (default=False) :param include_right: Whether includes the higher bound (<= higher bound). :type include_right: bool, optional (default=False)
- Returns:
within_range – Whether the parameter is within the range of (low, high)
- Return type:
bool or raise errors
- pdmlabs.method.pca_tsb.standardizer(X, X_t=None, keep_scalar=False)#