【发布时间】:2018-12-06 10:45:33
【问题描述】:
我必须实现我自己的 PCA 函数函数 Y,V = PCA(data, M, whitening) 计算第一个 M 主体 组件并转换数据,使得 y_n = U^T x_n。该功能应进一步 返回 V,它解释了转换解释的方差量。
我必须将数据 D=4 的维度减少到 M=2 > 给定函数如下
def PCA(data,nr_dimensions=None, whitening=False):
""" perform PCA and reduce the dimension of the data (D) to nr_dimensions
Input:
data... samples, nr_samples x D
nr_dimensions... dimension after the transformation, scalar
whitening... False -> standard PCA, True -> PCA with whitening
Returns:
transformed data... nr_samples x nr_dimensions
variance_explained... amount of variance explained by the the first nr_dimensions principal components, scalar"""
if nr_dimensions is not None:
dim = nr_dimensions
else:
dim = 2
我所做的如下:
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import scipy.stats as stats
from scipy.stats import multivariate_normal
import pdb
import sklearn
from sklearn import datasets
#covariance matrix
mean_vec = np.mean(data)
cov_mat = (data - mean_vec).T.dot((data - mean_vec)) / (data.shape[0] - 1)
print('Covariance matrix \n%s' % cov_mat)
#now the eigendecomposition of the cov matrix
cov_mat = np.cov(data.T)
eig_vals, eig_vecs = np.linalg.eig(cov_mat)
print('Eigenvectors \n%s' % eig_vecs)
print('\nEigenvalues \n%s' % eig_vals)
# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))]
这就是我现在不知道该做什么以及如何减少维度的地步。
欢迎任何帮助! :)
【问题讨论】:
-
是样本数多还是特征数多?
-
还有
x和U是什么?在您的代码中,您只有data -
看我的回答干杯
标签: python numpy machine-learning scikit-learn pca