24小时热门版块排行榜    

查看: 1936  |  回复: 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 的主题更新
☆ 无星级 ★ 一星级 ★★★ 三星级 ★★★★★ 五星级
普通表情 高级回复 (可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[基金申请] 时间戳变了,能看出什么问题? +18 基诺咪客 2026-08-17 23/1150 2026-08-20 17:19 by Godzela
[基金申请] 只有每年这种时候来逛逛小木虫 +21 yaoyewhu2008 2026-08-20 22/1100 2026-08-20 17:03 by yaoyewhu2008
[基金申请] 今天系统多次维护,明天很可能放榜! +9 zju2000 2026-08-16 10/500 2026-08-20 15:56 by Leogzhya
[基金申请] 放榜前的不淡定 40+3 snowwithsea 2026-08-19 12/600 2026-08-20 15:56 by lfy8008
[基金申请] 重要消息,中午系统在维护 +11 yuleib84 2026-08-18 12/600 2026-08-20 11:09 by xskun
[基金申请] 哪位老哥知道今年的国自然具体哪一天放榜? +16 Ldrop2023 2026-08-13 20/1000 2026-08-20 11:07 by xskun
[基金申请] 今天基金会出结果吗?20260819 +14 kkkl_v 2026-08-19 15/750 2026-08-20 08:21 by sunzitan
[教师之家] 为什么余额宝的年化利率越来越低?主要原因有哪些? +5 瞬息宇宙 2026-08-15 5/250 2026-08-19 20:23 by super2002521
[基金申请] 今天放榜没戏了吧 +4 yuleib84 2026-08-19 5/250 2026-08-19 19:52 by hhs666
[基金申请] 今天放榜吗? +14 布布和一二 2026-08-19 15/750 2026-08-19 18:07 by gltch
[基金申请] filecode=后面第一个是大写字母 +10 wangze12014 2026-08-14 12/600 2026-08-19 16:56 by 苦难博士
[基金申请] 2027广东省杰青 +4 奶牛小黑 2026-08-15 10/500 2026-08-19 11:02 by wanfengnew
[基金申请] 朋友圈看到的 +6 wangzilk 2026-08-18 8/400 2026-08-19 10:55 by Haru815
[基金申请] 什么时候开奖? +6 CrisMessi 2026-08-18 6/300 2026-08-19 08:06 by Equinoxhua
[基金申请] 明天放榜? +5 Shxjjxjkx 2026-08-18 5/250 2026-08-18 18:14 by -大大大大大-
[论文投稿] 投稿咨询 +4 wwm09 2026-08-17 6/300 2026-08-18 15:36 by wwm09
[基金申请] 时间戳又变了8-15 +14 archvillain 2026-08-15 26/1300 2026-08-18 13:37 by phantomgost
[基金申请] 93BebMhtakh前后11位开头都是大写 +4 且听虎啸 2026-08-17 5/250 2026-08-18 00:49 by 蔡棒棒菂
[基金申请] 感觉是下周放榜了 +6 angus9576 2026-08-17 11/550 2026-08-17 23:57 by angus9576
[精细化工] 招聘 金属平磨液,抛光液研发工程师 +3 小天0311 2026-08-14 3/150 2026-08-16 07:31 by H9PLUS
信息提示
请填处理意见