mab*_*sif 7 python pca scikits
我正在使用Python,我已经使用本教程实现了PCA .
一切都很好,我得到了协方差,我做了一个成功的转换,使它对原始尺寸没有问题.
但是我该如何进行美白?我尝试用特征值划分特征向量:
S, V = numpy.linalg.eig(cov)
V = V / S[:, numpy.newaxis]
Run Code Online (Sandbox Code Playgroud)
并使用V来转换数据,但这导致了奇怪的数据值.请问有人可以对此有所了解吗?
ali*_*i_m 19
这是我从这里得到的一些用于矩阵白化的Matlab代码的实现.
import numpy as np
def whiten(X,fudge=1E-18):
# the matrix X should be observations-by-components
# get the covariance matrix
Xcov = np.dot(X.T,X)
# eigenvalue decomposition of the covariance matrix
d, V = np.linalg.eigh(Xcov)
# a fudge factor can be used so that eigenvectors associated with
# small eigenvalues do not get overamplified.
D = np.diag(1. / np.sqrt(d+fudge))
# whitening matrix
W = np.dot(np.dot(V, D), V.T)
# multiply by the whitening matrix
X_white = np.dot(X, W)
return X_white, W
Run Code Online (Sandbox Code Playgroud)
您还可以使用SVD对矩阵进行白化:
def svd_whiten(X):
U, s, Vt = np.linalg.svd(X, full_matrices=False)
# U and Vt are the singular matrices, and s contains the singular values.
# Since the rows of both U and Vt are orthonormal vectors, then U * Vt
# will be white
X_white = np.dot(U, Vt)
return X_white
Run Code Online (Sandbox Code Playgroud)
第二种方式有点慢,但可能在数值上更稳定.
如果您为此使用python的scikit-learn库,则只需设置内置参数
from sklearn.decomposition import PCA
pca = PCA(whiten=True)
whitened = pca.fit_transform(X)
Run Code Online (Sandbox Code Playgroud)
检查文档。