from __future__ import print_function, division
import numpy as np
from mlfromscratch.utils import calculate_covariance_matrix
class PCA():
"""A method for doing dimensionality reduction by transforming the feature
space to a lower dimensionality, removing correlation between features and
maximizing the variance along each feature axis. This class is also used throughout
the project to plot data.
"""
def transform(self, X, n_components):
""" Fit the dataset to the number of principal components specified in the
constructor and return the transformed dataset """
covariance_matrix = calculate_covariance_matrix(X)
# Where (eigenvector[:,0] corresponds to eigenvalue[0])
eigenvalues, eigenvectors = np.linalg.eig(covariance_matrix)
# Sort the eigenvalues and corresponding eigenvectors from largest
# to smallest eigenvalue and select the first n_components
idx = eigenvalues.argsort()[::-1]
eigenvalues = eigenvalues[idx][:n_components]
eigenvectors = np.atleast_1d(eigenvectors[:, idx])[:, :n_components]
# Project the data onto principal components
X_transformed = X.dot(eigenvectors)
return X_transformed
[Machine Learning From Scratch]-unsupervised_learning-principal_component_analysis
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
- 文/潘曉璐 我一進(jìn)店門挨措,熙熙樓的掌柜王于貴愁眉苦臉地迎上來挖滤,“玉大人崩溪,你說我怎么就攤上這事『迹” “怎么了?”我有些...
- 文/不壞的土叔 我叫張陵担租,是天一觀的道長砸民。 經(jīng)常有香客問我,道長奋救,這世上最難降的妖魔是什么岭参? 我笑而不...
- 正文 為了忘掉前任,我火速辦了婚禮尝艘,結(jié)果婚禮上演侯,老公的妹妹穿的比我還像新娘。我一直安慰自己背亥,他們只是感情好秒际,可當(dāng)我...
- 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著狡汉,像睡著了一般娄徊。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上盾戴,一...
- 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢(mèng)啊……” “哼畏梆!你這毒婦竟也來了椎扬?” 一聲冷哼從身側(cè)響起,我...
- 序言:老撾萬榮一對(duì)情侶失蹤具温,失蹤者是張志新(化名)和其女友劉穎蚕涤,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體铣猩,經(jīng)...
- 正文 獨(dú)居荒郊野嶺守林人離奇死亡揖铜,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
- 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了达皿。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片天吓。...
- 正文 年R本政府宣布物邑,位于F島的核電站溜哮,受9級(jí)特大地震影響,放射性物質(zhì)發(fā)生泄漏色解。R本人自食惡果不足惜茂嗓,卻給世界環(huán)境...
- 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望科阎。 院中可真熱鬧述吸,春花似錦、人聲如沸锣笨。這莊子的主人今日做“春日...
- 文/蒼蘭香墨 我抬頭看了看天上的太陽错英。三九已至朴读,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間走趋,已是汗流浹背衅金。 一陣腳步聲響...
- 正文 我出身青樓,卻偏偏與公主長得像姨伟,于是被迫代替她去往敵國和親惩琉。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
推薦閱讀更多精彩內(nèi)容
- Now we have entered in the era of "big data". We have acc...