猫史档案馆


【数据分析】pca

用户:四九圣尊四九圣尊查看:0 回复:4 评论:0 创建时间:2019-01-20T23:55:29


center_imagecenter_imagecenter_imagecenter_image

自己写的一个pca框架,可以跑一下加深印象:

import numpy as np
from matplotlib import pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import warnings
class PCA():
def __init__(self):
self.data = None
self.dimension = 1
self.decline = None
self.value = None
def input(self,data,dimension):
data = np.array(data).T
if data.shape[0] != dimension:
raise Exception("Check your data's dimension,they didn't fit.")
else:
self.data = data
mean = np.array([np.mean(self.data,axis=1)]).T
self.data = self.data - np.tile(mean,(1,data.shape[1]))
def set_dimension(self,x):
if x < 1 or int(x) != x:
raise Exception("Dimension can't be this:(Int and larger than 0)", x)
else:
self.dimension = x
def Decline(self):
cov = np.cov(self.data)
self.value, vector = np.linalg.eig(cov)
self.decline = vector[0:self.dimension].dot(self.data)
self.decline = (self.decline.T).tolist()
result = []
for i in range(len(self.decline)):
result.append(self.decline[i])
return result[::-1]
def check(self,plot=False):
if plot == True:
plt.plot(self.value)
plt.show()
return np.sum(self.value)


if __name__ == '__main__':
data1 = [[1,2],[2,4],[3,6],[4,8],[5,10]]
pca = PCA()
pca.input(data1,2)
pca.set_dimension(1)
result = pca.Decline()

pca.check(plot=True)


回复

上一页1 页 / 共 1下一页
user12user12

emotion_编程猫_点赞

点赞0


评论


user12user12

Good!

点赞0


评论


编码已破译编码已破译

emotion_编程猫_点赞

点赞0


评论


四九圣尊四九圣尊

这个有点儿笼统。如果想听详细过程:http://open.163.com/movie/2008/1/M/E/M6SGF6VB4_M6SGKIEME.html(珍惜生命从38分钟开始)

点赞0


评论