在PCA中使用多于2台PC

时间:2019-06-28 11:38:36

标签: python pca

我想从头开始使用PCA算法,但是我想将784个功能减少到大约70个功能,而不是2个。我之前尝试过的是下面的代码。 在此代码的“选择具有最大特征值的k个特征向量”部分中,我如何选择k?

import numpy as np
from sklearn.preprocessing import StandardScaler
import matplotlib.pyplot as plt
import pandas as pd

data_train = pd.read_csv('trainData.csv',header=None)
label_train = pd.read_csv('trainLabels.csv',header=None)

data_train = StandardScaler().fit_transform(data_train)

# OR we can do this with one line of numpy for COV:
cov_mat = np.cov(data_train.T)

# Compute the eigen values and vectors using numpy
eig_vals, eig_vecs = np.linalg.eig(cov_mat)

# Make a list of (eigenvalue, eigenvector) tuples
eig_pairs = [(np.abs(eig_vals[i]), eig_vecs[:,i]) for i in range(len(eig_vals))]

# Sort the (eigenvalue, eigenvector) tuples from high to low
eig_pairs.sort(key=lambda x: x[0], reverse=True)
for i in eig_pairs:
    print(i[0])

#Choosing k eigenvectors with the largest eigenvalues    
matrix_w = np.hstack((eig_pairs[0][1].reshape(784,1), eig_pairs[1][1].reshape(784,1)))
print('Matrix W:\n', matrix_w)
transformed = matrix_w.T.dot(data_train.T)

1 个答案:

答案 0 :(得分:1)

看看如何创建matrix_w。 h_stack函数采用数组的元组并将其水平堆叠。您要做的是创建一个包含k个最大特征值的特征向量的元组,并创建矩阵:

eigenvectors = tuple([eig_pairs[i][1].reshape(784,1) for i in range(k)])
matrix_w = np.hstack(eigenvectors)