24小时热门版块排行榜    

查看: 1889  |  回复: 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 的主题更新
☆ 无星级 ★ 一星级 ★★★ 三星级 ★★★★★ 五星级
普通表情 高级回复 (可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[考研] 售SCI一区T0P文章,我:8.O.55.1.O54,科目全,可伽急 +3 u1xkze8ybe 2026-07-30 7/350 2026-07-31 12:10 by syhhffkrym
[论文投稿] 售SCI一区T0P文章,我:8.O.55.1.O.5.4,科目全,可+急 +3 u1xkze8ybe 2026-07-30 3/150 2026-07-31 12:08 by syhhffkrym
[硕博家园] 售SCI一区T0P文章,我:8.O.55.1.O.5.4,科目全,可+急 +3 u1xkze8ybe 2026-07-30 6/300 2026-07-31 12:05 by syhhffkrym
[教师之家] 基础研究怎么拉横向,学校到款任务越来越多,难以完成 拉横向,都有哪些途径啊 +6 锦衣卫寒战 2026-07-28 6/300 2026-07-31 11:27 by syl200707
[高分子] HXDI做水性聚氨酯乳液,是不是特别容易出渣 15+3 yuyusuv 2026-07-29 3/150 2026-07-31 09:21 by huizingga
[基金申请] 小木虫看见有人已经知道结果了 +15 1234567wang 2026-07-25 19/950 2026-07-31 08:30 by ZJTJZ
[基金申请] 2026年国自然面上资助率 +8 布布和一二 2026-07-30 8/400 2026-07-31 01:51 by alongwaytogo
[基金申请] 系统今天又提示维护了,估计离放榜不远了 +11 winnerche 2026-07-29 15/750 2026-07-30 23:08 by jnhyjjm
[基金申请] 微信指数没变化,科研之友没阅读 +14 wangze12014 2026-07-28 17/850 2026-07-30 20:10 by kissu88
[考博] 申请2027年材料/化学类博士 10+3 考研老狗? 2026-07-25 5/250 2026-07-30 19:33 by 白色木鱼
[基金申请] 你们的时间戳变了吗 +3 archvillain 2026-07-30 4/200 2026-07-30 18:53 by levinzhwen
[基金申请] 今年的WR进展到哪一步了? +5 wsgjhwz 2026-07-25 9/450 2026-07-30 12:59 by 可淡不可忘
[有机交流] 产物和副产物价值比较 30+4 小汤02 2026-07-27 5/250 2026-07-30 12:44 by czyzsu
[基金申请] 时间戳他又来了 +14 晓晓爱翠翠 2026-07-26 17/850 2026-07-29 16:30 by 呵呵二哥
[有机交流] 这个自发加氧反应的机理是什么? 50+4 YUAN2273 2026-07-25 7/350 2026-07-29 12:27 by xiaobenpu
[基金申请] 没消息就是被刷了呗 +13 lambert2014 2026-07-24 14/700 2026-07-29 10:38 by msh145800
[基金申请] 这种情况还有戏吗 +5 drbart 2026-07-27 11/550 2026-07-29 05:50 by drbart
[基金申请] 同事接到电话了,我却没有 +4 1234567wang 2026-07-27 4/200 2026-07-28 10:11 by GOODLUCKER
[基金申请] 准备明年的基金了 +5 Tide man 2026-07-27 5/250 2026-07-28 09:25 by newfuzzy1
[分析] 水蒸气蒸馏法乳化现象 +3 月光娇娇 2026-07-26 3/150 2026-07-26 23:25 by caiyun
信息提示
请填处理意见