📔
liu_yu_bo_play_with_machine_learning
  • README
  • src
    • Introduction
    • Summary
    • Chapter10
      • 第十章:评价分类结果
    • Chapter10
      • 10-2 精确率和召回率
    • Chapter10
      • 10-3 实现混淆矩阵、精准率、召回率
    • Chapter10
      • 10-4 F1 score
    • Chapter10
      • 10-5 Precision-Recall平衡
    • Chapter10
      • 10-6 precision-recall曲线
    • Chapter10
      • 10-7 ROC曲线
    • Chapter10
      • 10-8 多分类问题中的混淆矩阵
    • Chapter11
      • 11-1 什么是支撑向量机
    • Chapter11
      • 11-2 支撑向量机的推导过程
    • Chapter11
      • 11-3 Soft Margin和SVM的正则化
    • Chapter11
      • 11-4 scikit-leran中的SVM
    • Chapter11
      • 11-5 SVM中使用多项式特征
    • Chapter11
      • 11-6 什么是核函数
    • Chapter11
      • 11-7 高斯核函数
    • Chapter11
      • 11-8 scikit-learn中的高斯核函数
    • Chapter11
      • 11-9 SVM思想解决回归问题
    • Chapter12
      • 第十二章:决策树
    • Chapter12
      • 12-2 信息熵
    • Chapter12
      • 12-3 使用信息寻找最优划分
    • Chapter12
      • 12-4 基尼系数
    • Chapter12
      • 12-5 CART和决策树中的超参数
    • Chapter12
      • 12-6 决策树解决回归问题
    • Chapter12
      • 12-7 决策树的局限性
    • Chapter13
      • 第十三章:集成学习和随机森林
    • Chapter13
      • 13-2 soft voting
    • Chapter13
      • 13-3 bagging和pasting
    • Chapter13
      • 13-4 更多关于bagging的讨论
    • Chapter13
      • 13-5 随机森林和extra-trees
    • Chapter13
      • 13-6 ada boosting和gradiesnt boosting
    • Chapter13
      • 13-7 Stacking
    • Chapter4
      • KNN - K近邻算法 - K-Nearest Neighbors
    • Chapter4
      • 4-1
    • Chapter4
      • 4-2
    • Chapter4
      • 4-3 训练数据集,测试数据集
    • Chapter4
      • 4-4 分类准确度
    • Chapter4
      • 4-5
    • Chapter4
      • 4-6 网格搜索
    • Chapter4
      • 4-7
    • Chapter4
      • 4-8 scikit-learn中的Scaler
    • Chapter4
      • 4-9 更多有关K近邻算法的思考
    • Chapter5
      • 线性回归算法
    • Chapter5
      • 5-1
    • Chapter5
      • 5-10 线性回归的可解释性和更多思考
    • Chapter5
      • 5-2 最小二乘法
    • Chapter5
      • 5-3 简单线性回归的实现
    • Chapter5
      • 5-4 参数计算向量化
    • Chapter5
      • 5-5 衡量线性回归算法的指标
    • Chapter5
      • 5-6 最好的衡量线性回归法的指标 R Squared
    • Chapter5
      • 5-7 简单线性回归和正规方程解
    • Chapter5
      • 5-8 实现多元线性回归
    • Chapter5
      • 5-9 scikit-learn中的回归算法
    • Chapter6
      • 第六章:梯度下降法
    • Chapter6
      • 6-2 模拟实现梯度下降法
    • Chapter6
      • 6-3 多元线性回归中的梯度下降法
    • Chapter6
      • 6-4 在线性回归模型中使用梯度下降法
    • Chapter6
      • 6-5 梯度下降的向量化
    • Chapter6
      • 6-6 随机梯度下降
    • Chapter6
      • 6-7 代码实现随机梯度下降
    • Chapter6
      • 6-8 调试梯度下降法
    • Chapter6
      • 6-9 有关梯度下降法的更多深入讨论
    • Chapter7
      • 主成分分析法 PCA Principal Component Analysis
    • Chapter7
      • 7-1
    • Chapter7
      • 7-2 使用梯度上升法求解主成分分析问题
    • Chapter7
      • 7-3 代码实现主成分分析问题
    • Chapter7
      • 7-4 求数据的前N个主成分
    • Chapter7
      • 7-5 高维数据向低维数据映射
    • Chapter7
      • 7-6 scikit learn中的PCA
    • Chapter7
      • 7-7 MNIST数据集
    • Chapter7
      • 7-8 使用PCA降噪
    • Chapter7
      • 7-9 人脸识别和特征脸(未完成)
    • Chapter8
      • 第八章:多项式回归与模型泛化
    • Chapter8
      • 8-10 L1,L2和弹性网络
    • Chapter8
      • 8-2 scikit-learn中的多项式回归和pipeline
    • Chapter8
      • 8-3 过拟合和欠拟合
    • Chapter8
      • 8-4 为什么要训练数据集和测试数据集
    • Chapter8
      • 8-5 学习曲线
    • Chapter8
      • 8-6 验证数据集与交叉验证
    • Chapter8
      • 8-7 偏差方差权衡 Bias Variance Trade off
    • Chapter8
      • 8-8 模型正则化 Regularization
    • Chapter8
      • 8-9 LASSO Regularization
    • Chapter9
      • 第九章:逻辑回归
    • Chapter9
      • 9-2 逻辑回归的损失函数
    • Chapter9
      • 9-3 逻辑回归算法损失函数的梯度
    • Chapter9
      • 9-4 实现逻辑回归算法
    • Chapter9
      • 9-5 决策边界
    • Chapter9
      • 9-6 在逻辑回归中使用多项式特征
    • Chapter9
      • 9-7 scikit-learn中的逻辑回归
    • Chapter9
      • 9-8 OvR与OvO
Powered by GitBook
On this page
  • 把PCA封装成类
  • 使用PCA降维
  • 准备数据
  • 训练模型1
  • 训练模型2:降维
  • 对比原始数据与降维再恢复后的数据
  1. src
  2. Chapter7

7-5 高维数据向低维数据映射

定义:X是样本数据,每一行是一个数据,它有m个数据,每个数据有n个特征

X=[X1(1)X1(2)⋯X1(n)X2(1)X2(2)⋯X2(n)⋯⋯⋯⋯Xm(1)Xm(2)⋯Xm(n)]X = \begin{bmatrix} X_1^{(1)} && X_1^{(2)} && \cdots && X_1^{(n)} \\ X_2^{(1)} && X_2^{(2)} && \cdots && X_2^{(n)} \\ \cdots && \cdots && \cdots && \cdots \\ X_m^{(1)} && X_m^{(2)} && \cdots && X_m^{(n)} \end{bmatrix}X=​X1(1)​X2(1)​⋯Xm(1)​​​X1(2)​X2(2)​⋯Xm(2)​​​⋯⋯⋯⋯​​X1(n)​X2(n)​⋯Xm(n)​​​

$W_k$是求得的前k个主成分矩阵,每一行是一个主成分的单位方向,它有k个主成分方向,每个主成分的方向有n个维度

X=[Wk(1)W1(2)⋯W1(n)W2(1)W2(2)⋯W2(n)⋯⋯⋯⋯Wk(1)Wk(2)⋯Wk(n)]X = \begin{bmatrix} W_k^{(1)} && W_1^{(2)} && \cdots && W_1^{(n)} \\ W_2^{(1)} && W_2^{(2)} && \cdots && W_2^{(n)} \\ \cdots && \cdots && \cdots && \cdots \\ W_k^{(1)} && W_k^{(2)} && \cdots && W_k^{(n)} \end{bmatrix}X=​Wk(1)​W2(1)​⋯Wk(1)​​​W1(2)​W2(2)​⋯Wk(2)​​​⋯⋯⋯⋯​​W1(n)​W2(n)​⋯Wk(n)​​​

问:如何将样本X从N维转换成K维? 答:降维:把所有样本映射到K个主成分上

X⋅WkT=XkX \cdot W_k^T = X_kX⋅WkT​=Xk​

还原:把降维后的数据还原到原坐标空间

Xk⋅Wk=XmX_k \cdot W_k = X_mXk​⋅Wk​=Xm​

还原后的X与原X不同。

把PCA封装成类

import numpy as np

class PCA:
    def __init__(self, n_components):
        """初始化PCA"""
        assert n_components >= 1, "n_components must be valid"
        self.n_components = n_components
        self.components_ = None

    def fit(self, X, eta=0.01, n_iters=1e4):
        """获取数据集的前n个主成分"""
        assert self.n_components <= X.shape[1], "n_components must not be greater than the feature number of X"

        def demean(X):
            return X - np.mean(X, axis=0)

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

        def df(w, X):
            return X.T.dot(X.dot(w)) * 2. / len(X)

        # 把向量单位化
        def direction(w):
            return w / np.linalg.norm(w)

        def first_component(X, initial_w, eta, n_iters=1e4, epsilon=1e-8):
            w = direction(initial_w)
            cur_iter = 0
            while cur_iter < n_iters:
                gradient = df(w, X)
                last_w = w
                w = w + eta * gradient
                w = direction(w)
                if(abs(f(w, X)) - abs(f(last_w, X)) < epsilon):
                   break
                cur_iter += 1
            return w

        X_pca = 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.shape[1])
            eta = 0.001
            w = first_component(X_pca, initial_w, eta)
            self.components_[i, :] = w
            X_pca = X_pca - X_pca.dot(w).reshape(-1, 1) * w
        return self

    def transform(self, X):
        """将给定的X,映射到各个主成分分量中"""
        assert X.shape[1] == self.components_.shape[1]
        return X.dot(self.components_.T)

    def inverse_transform(self, X):
        """将给定的X反向映射回原来的特征空间"""
        assert X.shape[1] == self.components_.shape[0]
        return X.dot(self.components_)

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

使用PCA降维

准备数据

import numpy as np
import matplotlib.pyplot as plt

X = np.empty((100,2))
X[:,0] = np.random.uniform(0., 100., size=100)
X[:,1] = 0.75 * X[:, 0] + 3. + np.random.normal(0, 10., size=100)

训练模型1

pca = PCA(n_components=2)
pca.fit(X)

输入:pca.components_ 输出:array([[ 0.75366776, 0.65725559], [-0.65723751, 0.75368352]])

训练模型2:降维

pca = PCA(n_components=1)
pca.fit(X)

X_reduction = pca.transform(X)
X_restore = pca.inverse_transform(X_reduction)

输入:X_reduction.shape 输出:(100, 1)

输入:X_restore.shape 输出:(100, 2)

对比原始数据与降维再恢复后的数据

plt.scatter(X[:, 0], X[:, 1], color='b', alpha=0.5)
plt.scatter(X_restore[:, 0], X_restore[:, 1], color='r', alpha=0.5)
plt.show()
PreviousChapter7NextChapter7

Last updated 4 years ago