24小时热门版块排行榜    

CyRhmU.jpeg
南方科技大学公共卫生及应急管理学院2026级博士研究生招生报考通知(长期有效)
查看: 1584  |  回复: 4
【奖励】 本帖被评价4次,作者xioooli增加金币 2.6
本帖产生 1 个 程序强帖 ,点击这里进行查看

xioooli

金虫 (小有名气)


[资源] 【原创】python 写的计算 PCA 的小脚本

RT
需要安装 numpy,如果还想要绘图的话得装 matplotlib,希望对大家能有点用
CODE:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import numpy as np
from copy import deepcopy

class PCA():
    '''
    Formula:
        X = U . S . Vt
    Useage:
        p = PCA(X, fraction = 0.9)
        in which `X` is the matrix of your data and `fraction` means
        use principal components that account for e.g. 0.9 of the
        total variance
    Out:
        p.U, p.S, p.Vt from numpy.linalg.svd
        p.eigen: the eigenvalues of A*A, in decreasing order
            eigen[j] / eigen.sum() is variable j's fraction of the
            total variance;
            look at the first few eigen[] to see how many PCs get
            to 90 %, 95 % ...
        p.npc: number of principal components,
            e.g. 2 if the top 2 eigenvalues are >= `fraction` of the total.
        p.sumvariance: the number of the variances
    Methods:
        p.center(X, axis = 0, scale = True)
            classmethod for centering the matrix (e.g. `X`), returns
            the centered matrix with out changing the original matrix
    '''
    def __init__(self, X, fraction = 0.85):
        assert 0 <= fraction <= 1
        # center the matric
        A = self.center(X)
        # SVD
        self.U, self.S, self.Vt = np.linalg.svd(A, full_matrices = False)
        assert np.all(self.S[:-1] >= self.S[1:]) # sorted
        self.eigen = self.S**2
        self.sumvariance = np.cumsum(self.eigen)
        self.sumvariance /= self.sumvariance[-1]
        self.npc = np.searchsorted(self.sumvariance, fraction) + 1
        self.pc = self.U[:, :self.npc] * self.S[:self.npc]
    @classmethod
    def center(self, X, axis = 0, scale = True):
        A = deepcopy(X)
        mean = A.mean(axis = axis)
        A -= mean
        if scale:
            std = A.std(axis = axis)
            A /= np.where(std, std, 1.0)
        return A

if __name__ == '__main__':
    from matplotlib import pyplot as plt
    import sys
    if len(sys.argv) >= 2:
        csv = sys.argv[1]
    else:
        print '%s /path/to/your_data_file_in_csv_format' %sys.argv[0]
        sys.exit(1)
    # you can define your own colors here
    colors = {(0, 1, 2): 'red',
            (3, 4, 5): 'blue',
            (6, 7, 8, 9): 'green',
            (10, 11, 12): 'yellow'}
    def get_color(idx):
        for i, c in colors.items():
            if idx in i:
                return c
    X = np.genfromtxt(csv, delimiter = ',')
    p = PCA(X, fraction = 0.9)
    print p.npc
    pc = p.pc
    x, y = pc[:, 0], pc[:, 1]
    fig = plt.figure(figsize=(8,6))
    ax = fig.add_subplot(111)
    for i, k in enumerate(zip(x,y)):
        ax.text(k[0], k[1], str(i), bbox=dict(facecolor = get_color(i), alpha=0.5))
    #plt.xlim(-8, 8)
    #plt.ylim(-4, 4)
    plt.xlabel('PC1')
    plt.ylabel('PC2')
    plt.title('bulabula')
    plt.legend()
    plt.grid(True)
    plt.show()

[ Last edited by zzy870720z on 2011-5-14 at 12:31 ]
回复此楼

» 收录本帖的淘帖专辑推荐

ML相关 source

» 猜你喜欢

» 本主题相关价值贴推荐,对您同样有帮助:

已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

redtu160

木虫 (正式写手)


★★★ 三星级,支持鼓励


jjdg(金币+1): 感谢参与 2011-07-31 00:51:02
thank you very much!
3楼2011-07-30 17:19:11
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖

bennyg

木虫 (著名写手)


★★★ 三星级,支持鼓励

运行后,出错。sys.exit(1)
5楼2012-02-14 08:40:36
已阅   回复此楼   关注TA 给TA发消息 送TA红花 TA的回帖
简单回复
余泽成2楼
2010-12-13 22:07   回复  
 支持!
2011-07-31 08:30   回复  
dubo(金币+1): 欢迎常来程序语言版讨论 2011-07-31 12:50:25
一般  
相关版块跳转 我要订阅楼主 xioooli 的主题更新
☆ 无星级 ★ 一星级 ★★★ 三星级 ★★★★★ 五星级
普通表情 高级回复(可上传附件)
信息提示
请填处理意见