24小时热门版块排行榜    

北京石油化工学院2026年研究生招生接收调剂公告
查看: 1693  |  回复: 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 的主题更新
☆ 无星级 ★ 一星级 ★★★ 三星级 ★★★★★ 五星级
普通表情 高级回复 (可上传附件)
最具人气热帖推荐 [查看全部] 作者 回/看 最后发表
[考研] 本科211总分289,08工学真心求调剂 +3 utopiaE 2026-03-30 3/150 2026-03-30 23:42 by ms629
[考研] 哈尔滨工业大学材料与化工专硕378求调剂 +3 塔比乌斯 2026-03-30 3/150 2026-03-30 22:55 by 无际的草原
[考研] 085600 295分求调剂 +7 W55j 2026-03-30 9/450 2026-03-30 20:36 by dick_runner
[考研] 285求调剂 +4 AZMK 2026-03-30 7/350 2026-03-30 20:24 by laoshidan
[考研] 一志愿华中师范化学332分求调剂 +3 Lyy930824@ 2026-03-29 3/150 2026-03-30 20:15 by DHUSHUAI
[考研] 304材料求调剂 +5 钟llll 2026-03-26 5/250 2026-03-30 19:37 by 源_2020
[考研] 一志愿:西北大学,英一数一408-284分求调剂 +5 12.27 2026-03-27 5/250 2026-03-30 19:31 by 源_2020
[考研] 085600 材料与化工 329分求调剂 +18 Mr. Z 2026-03-25 19/950 2026-03-30 19:01 by Wang200018
[考研] 342求调剂 +4 加油a李zs 2026-03-26 4/200 2026-03-30 16:39 by 晶体之美
[考研] 375求调剂 +6 雨夏整夜 2026-03-29 6/300 2026-03-30 10:21 by herarysara
[考研] 一志愿南航 335分 | 0856 | GPA 4.07 | 有科研经历 +8 cccchenso 2026-03-29 8/400 2026-03-29 23:53 by 我是小康
[考研] 290求调剂 +3 dfffsar 2026-03-29 3/150 2026-03-29 22:38 by 毛毛毛阿莫2
[考博] 26申博自荐 +6 whh869393 2026-03-24 6/300 2026-03-29 21:05 by nxgogo
[考研] 086000生物与医药调剂 +5 Feisty。 2026-03-28 9/450 2026-03-29 12:02 by longlotian
[考研] 312,生物学求调剂 +3 小译同学abc 2026-03-28 3/150 2026-03-28 15:32 by 落睿可思
[考研] 304求调剂 +6 曼殊2266 2026-03-27 6/300 2026-03-28 14:10 by 唐沐儿
[考研] 一志愿南京航空航天大学材料学硕求调剂 +3 @taotao 2026-03-28 3/150 2026-03-28 10:26 by JourneyLucky
[考研] 272求调剂 +7 脚滑的守法公民 2026-03-27 7/350 2026-03-27 17:23 by laoshidan
[考研] 求调剂 +3 刘柯@ 2026-03-24 4/200 2026-03-27 11:28 by shangxh
[考研] 环境专硕324分求调剂推荐 +5 轩小宁—— 2026-03-26 5/250 2026-03-26 12:05 by i_cooler
信息提示
请填处理意见