機器學習“傻瓜式”理解(8)PCA(基礎理解+梯度上升)

PCA(Principal Components Analysis)

基礎理解以及公式推導

我們在機器學習的過程中需要實現數據的優化處理,降維處理是實現數據優化的手段,主成分分析則是實現數據降維的主要手段。主成分分析便是在我們所有的數據特徵中選出主要影響我們最終預測結果的一些特徵,但是值得注意的是,PCA不是進行特徵選擇的過程,而是將高維空間的數據映射到低維空間,低維空間的每個維度,是原始的高維空間的一些線性組合,這便使得PCA以後低維空間,每一個維度都失去了原來的意義。但是如果對於你的項目而言保持語意十分重要,那就不推薦PCA降維算法。
降維的思路:
①優化數據集,進行數據降維。
②目標便是使得降維後數據分佈的方差最大,用到的方法便是梯度上升法。
③PCA是一種非監督學習的方法,主要用於數據的降維降噪處理。
分析圖片
在這裏插入圖片描述
公式推廣:
在這裏插入圖片描述
主要使用的方法就是梯度上升法。
使用梯度上升法的梯度推導過程:
推導過程
PCA降維的基本原理:
尋找另外一個座標系,用這個座標系來表示原來座標中的數據,尋找前K個主要的做標準,也就是主成分,將數據櫻映射到這k個軸上,便實現了數據的降維處理。
實現代碼的封裝:

import numpy as np

class PCA:

    def __init__(self,n_components):
        '''check'''
        assert n_components >= 1,\
                "the value must be >=1"
        self.n_components  = n_components
        self.components = None

    def fit(self,X,eta=0.01,n_iters=1e4):
        '''check'''
        assert self.n_components <= X.shape[1],\
                "the size must be valid"

        '''No.1 demean'''
        def demean(x):
            return x - np.mean(X,axis = 0)

        '''No.2 '''
        def f(w,x):
            return np.sum((X.dot(w)) **2 ) / len(x)

        '''No.3 Df'''
        def df(w,x):
            return x.T.dot(x.dot(w)) * 2 / len(x)

        '''No.4 direction'''
        def direction(w):
            return w / np.linalg.norm(w)

        '''No.5 get first component'''
        def first_component(X,initial_w,eta=0.01,n_iters = 1e4,epsilon = 1e-8):
            w = initial_w
            cur_iter = 0

            while cur_iter < n_iters:
                gradient = df(w,X)
                last_w = w
                w = w + eta*gradient
                if(abs(f(w,X) - f(last_w,X)) < epsilon):
                    break
                cur_iter+=1

            return w

        '''main step'''
        X_demean = demean(X)
        self.components = np.empty(shape=(self.n_components,X.shape[1]))
        for i in range(self.n_components):
            initial_w = np.random.random(X_demean.shape[1])
            w = first_component(X,initial_w)
            self.components[i,:] = w

            X_demean = X_demean - X_demean.dot(w).reshape(-1,1) * w

        return self

    def transform(self,X):
        '''check'''
        assert X.shape[1] == self.components.shape[1],\
                "the size must be valid"

        return X.dot(self.components.T)

    def inverse_transform(self, X):
        '''check'''
        assert X.shape[1] == self.components.shape[0], \
                "the size must be valid"

        return X.dot(self.components)

    def __repr__(self):
        '''desc'''
        return "PCA(n_components=%d)" % self.n_components

另外:PCA降維在特徵臉識別和降噪處理應用十分廣泛。
降噪:我們將m維的數據降維到k維,然後再講k維數據降回到m維,最後所得到便是降噪後的數據集。

在這裏插入圖片描述
在這裏插入圖片描述
如上圖所示。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章