Python 中的主成分分析

2024-04-04

我想使用主成分分析(PCA)来降维。 numpy 或 scipy 是否已经有了它,或者我必须使用自己的numpy.linalg.eigh http://docs.scipy.org/doc/numpy/reference/generated/numpy.linalg.eigh.html?

我不仅仅想使用奇异值分解 (SVD),因为我的输入数据非常高维(~460 维),所以我认为 SVD 会比计算协方差矩阵的特征向量慢。

我希望找到一个预制的、经过调试的实现,它已经就何时使用哪种方法做出了正确的决定,并且可能还进行了我不知道的其他优化。


几个月后,这是一个小类 PCA 和一张图片:

#!/usr/bin/env python
""" a small class for Principal Component Analysis
Usage:
    p = PCA( A, fraction=0.90 )
In:
    A: an array of e.g. 1000 observations x 20 variables, 1000 rows x 20 columns
    fraction: use principal components that account for e.g.
        90 % of the total variance

Out:
    p.U, p.d, p.Vt: from numpy.linalg.svd, A = U . d . Vt
    p.dinv: 1/d or 0, see NR
    p.eigen: the eigenvalues of A*A, in decreasing order (p.d**2).
        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.
        It's ok to change this; methods use the current value.

Methods:
    The methods of class PCA transform vectors or arrays of e.g.
    20 variables, 2 principal components and 1000 observations,
    using partial matrices U' d' Vt', parts of the full U d Vt:
    A ~ U' . d' . Vt' where e.g.
        U' is 1000 x 2
        d' is diag([ d0, d1 ]), the 2 largest singular values
        Vt' is 2 x 20.  Dropping the primes,

    d . Vt      2 principal vars = p.vars_pc( 20 vars )
    U           1000 obs = p.pc_obs( 2 principal vars )
    U . d . Vt  1000 obs, p.obs( 20 vars ) = pc_obs( vars_pc( vars ))
        fast approximate A . vars, using the `npc` principal components

    Ut              2 pcs = p.obs_pc( 1000 obs )
    V . dinv        20 vars = p.pc_vars( 2 principal vars )
    V . dinv . Ut   20 vars, p.vars( 1000 obs ) = pc_vars( obs_pc( obs )),
        fast approximate Ainverse . obs: vars that give ~ those obs.


Notes:
    PCA does not center or scale A; you usually want to first
        A -= A.mean(A, axis=0)
        A /= A.std(A, axis=0)
    with the little class Center or the like, below.

See also:
    http://en.wikipedia.org/wiki/Principal_component_analysis
    http://en.wikipedia.org/wiki/Singular_value_decomposition
    Press et al., Numerical Recipes (2 or 3 ed), SVD
    PCA micro-tutorial
    iris-pca .py .png

"""

from __future__ import division
import numpy as np
dot = np.dot
    # import bz.numpyutil as nu
    # dot = nu.pdot

__version__ = "2010-04-14 apr"
__author_email__ = "denis-bz-py at t-online dot de"

#...............................................................................
class PCA:
    def __init__( self, A, fraction=0.90 ):
        assert 0 <= fraction <= 1
            # A = U . diag(d) . Vt, O( m n^2 ), lapack_lite --
        self.U, self.d, self.Vt = np.linalg.svd( A, full_matrices=False )
        assert np.all( self.d[:-1] >= self.d[1:] )  # sorted
        self.eigen = self.d**2
        self.sumvariance = np.cumsum(self.eigen)
        self.sumvariance /= self.sumvariance[-1]
        self.npc = np.searchsorted( self.sumvariance, fraction ) + 1
        self.dinv = np.array([ 1/d if d > self.d[0] * 1e-6  else 0
                                for d in self.d ])

    def pc( self ):
        """ e.g. 1000 x 2 U[:, :npc] * d[:npc], to plot etc. """
        n = self.npc
        return self.U[:, :n] * self.d[:n]

    # These 1-line methods may not be worth the bother;
    # then use U d Vt directly --

    def vars_pc( self, x ):
        n = self.npc
        return self.d[:n] * dot( self.Vt[:n], x.T ).T  # 20 vars -> 2 principal

    def pc_vars( self, p ):
        n = self.npc
        return dot( self.Vt[:n].T, (self.dinv[:n] * p).T ) .T  # 2 PC -> 20 vars

    def pc_obs( self, p ):
        n = self.npc
        return dot( self.U[:, :n], p.T )  # 2 principal -> 1000 obs

    def obs_pc( self, obs ):
        n = self.npc
        return dot( self.U[:, :n].T, obs ) .T  # 1000 obs -> 2 principal

    def obs( self, x ):
        return self.pc_obs( self.vars_pc(x) )  # 20 vars -> 2 principal -> 1000 obs

    def vars( self, obs ):
        return self.pc_vars( self.obs_pc(obs) )  # 1000 obs -> 2 principal -> 20 vars


class Center:
    """ A -= A.mean() /= A.std(), inplace -- use A.copy() if need be
        uncenter(x) == original A . x
    """
        # mttiw
    def __init__( self, A, axis=0, scale=True, verbose=1 ):
        self.mean = A.mean(axis=axis)
        if verbose:
            print "Center -= A.mean:", self.mean
        A -= self.mean
        if scale:
            std = A.std(axis=axis)
            self.std = np.where( std, std, 1. )
            if verbose:
                print "Center /= A.std:", self.std
            A /= self.std
        else:
            self.std = np.ones( A.shape[-1] )
        self.A = A

    def uncenter( self, x ):
        return np.dot( self.A, x * self.std ) + np.dot( x, self.mean )


#...............................................................................
if __name__ == "__main__":
    import sys

    csv = "iris4.csv"  # wikipedia Iris_flower_data_set
        # 5.1,3.5,1.4,0.2  # ,Iris-setosa ...
    N = 1000
    K = 20
    fraction = .90
    seed = 1
    exec "\n".join( sys.argv[1:] )  # N= ...
    np.random.seed(seed)
    np.set_printoptions( 1, threshold=100, suppress=True )  # .1f
    try:
        A = np.genfromtxt( csv, delimiter="," )
        N, K = A.shape
    except IOError:
        A = np.random.normal( size=(N, K) )  # gen correlated ?

    print "csv: %s  N: %d  K: %d  fraction: %.2g" % (csv, N, K, fraction)
    Center(A)
    print "A:", A

    print "PCA ..." ,
    p = PCA( A, fraction=fraction )
    print "npc:", p.npc
    print "% variance:", p.sumvariance * 100

    print "Vt[0], weights that give PC 0:", p.Vt[0]
    print "A . Vt[0]:", dot( A, p.Vt[0] )
    print "pc:", p.pc()

    print "\nobs <-> pc <-> x: with fraction=1, diffs should be ~ 0"
    x = np.ones(K)
    # x = np.ones(( 3, K ))
    print "x:", x
    pc = p.vars_pc(x)  # d' Vt' x
    print "vars_pc(x):", pc
    print "back to ~ x:", p.pc_vars(pc)

    Ax = dot( A, x.T )
    pcx = p.obs(x)  # U' d' Vt' x
    print "Ax:", Ax
    print "A'x:", pcx
    print "max |Ax - A'x|: %.2g" % np.linalg.norm( Ax - pcx, np.inf )

    b = Ax  # ~ back to original x, Ainv A x
    back = p.vars(b)
    print "~ back again:", back
    print "max |back - x|: %.2g" % np.linalg.norm( back - x, np.inf )

# end pca.py
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 中的主成分分析 的相关文章

  • 使用 Python 创建 MIDI

    本质上 我正在尝试从头开始创建 MIDI 并将它们放到网上 我对不同的语言持开放态度 但更喜欢使用Python 两种语言之一 如果这有什么区别的话 并且想知道我应该使用哪个库 提前致谢 看起来这就是您正在寻找的 适用于 Python 的简单
  • ctypes 错误:libdc1394 错误:无法初始化 libdc1394

    我正在尝试将程序编译为共享库 我可以使用 ctypes 在 Python 代码中使用该库 使用以下命令该库可以正常编译 g shared Wl soname mylib O3 o mylib so fPIC files pkg config
  • 在 python 3 中使用子进程

    我使用 subprocess 模块在 python 3 中运行 shell 命令 这是我的代码 import subprocess filename somename py in practical i m using a real fil
  • Python 是解释型的还是编译型的,或者两者兼而有之?

    据我了解 An 解释的语言是由解释器 将高级语言转换为机器代码然后执行的程序 实时运行和执行的高级语言 它一次处理一点程序 A compiled语言是一种高级语言 其代码首先由编译器 将高级语言转换为机器代码的程序 转换为机器代码 然后由执
  • 字符串中的注释和注释中的字符串

    我正在尝试使用 Python 和 Regex 计算 C 代码中包含的注释中的字符数 但没有成功 我可以先删除字符串以删除字符串中的注释 但这也会删除注释中的字符串 结果会很糟糕 是否有机会通过使用正则表达式来询问不匹配注释中的字符串 反之亦
  • “一旦获取切片就无法更新查询”。最佳实践?

    由于我的项目的性质 我发现自己不断地从查询集中取出切片 如下所示 Thread objects filter board requested board id order by updatedate 10 但这给我带来了实际对我选择的元素进
  • PyTorch 给出 cuda 运行时错误

    我对我的代码做了一些小小的修改 以便它不使用 DataParallel and DistributedDataParallel 代码如下 import argparse import os import shutil import time
  • Python tkinter.filedialog Askfolder 干扰 clr

    我主要在 Spyder 中工作 构建需要弹出文件夹或文件浏览窗口的脚本 下面的代码在spyder中完美运行 在 Pycharm 中 askopenfilename工作良好 同时askdirectory什么都不做 卡住了 但是 如果在调试模式
  • 编辑 Jupyter Notebook 时 VS Code 中缺少“在选择中查找”

    使用 Jupyter Notebook 时 VSCode 中缺少 在选择中查找 按钮 它会减慢开发速度 所以我想请问有人知道如何激活它吗 第一张图显示了在 python 文件中的搜索 替换 第二张图显示了笔记本电脑中缺少的按钮 Python
  • ValueError:不支持连续[重复]

    这个问题在这里已经有答案了 我正在使用 GridSearchCV 进行线性回归的交叉验证 不是分类器也不是逻辑回归 我还使用 StandardScaler 对 X 进行标准化 我的数据框有 17 个特征 X 和 5 个目标 y 观察 约11
  • 如何使用 javascript/jquery/AJAX 调用 Django REST API?

    我想使用 Javascript jQuery AJAX 在前端调用 Django Rest API 请求方法是 POST 但当我看到 API 调用它的调用 OPTIONS 方法时 所以 我开始了解access control allow o
  • 揭秘sharedctypes性能

    在 python 中 可以在多个进程之间共享 ctypes 对象 然而我注意到分配这些对象似乎非常昂贵 考虑以下代码 from multiprocessing import sharedctypes as sct import ctypes
  • 如何从 JSON 响应重定向?

    所以我尝试使用 Flask 和 Javascript 上传器 Dropzone 上传文件并在上传完成后重定向 文件上传正常 但在烧瓶中使用传统的重定向 return redirect http somesite com 不执行任何操作 页面
  • Python、subprocess、call()、check_call 和 returncode 来查找命令是否存在

    我已经弄清楚如何使用 call 让我的 python 脚本运行命令 import subprocess mycommandline lumberjack sleep all night work all day subprocess cal
  • 为什么我应该使用 WSGI?

    使用 mod python 一段时间了 我读了越来越多关于 WSGI 有多好的文章 但没有真正理解为什么 那么我为什么要切换到它呢 有什么好处 这很难吗 学习曲线值得吗 为了用 Python 开发复杂的 Web 应用程序 您可能会使用更全面
  • `pyqt5'错误`元数据生成失败`

    我正在尝试安装pyqt5使用带有 M1 芯片和 Python 3 9 12 的 mac 操作系统 我怀疑M1芯片可能是原因 我收到一个错误metadata generation failed 最小工作示例 directly in the t
  • 在 Spyder 的变量资源管理器中查看局部变量

    我是 python 新手 正在使用 Spyder 的 IDE 我欣赏它的一项功能是它的变量资源管理器 然而 根据一些研究 我发现它只显示全局变量 我找到的解决方法是使用检查模块 import inspect local vars def m
  • Flask 应用程序的测试覆盖率不起作用

    您好 想在终端的 Flask 应用程序中测试 删除路由 我可以看到测试已经过去 它说 test user delete test app LayoutTestCase ok 但是当我打开封面时 它仍然是红色的 这意味着没有覆盖它 请有人向我
  • sqlite3从打印数据中删除括号

    我创建了一个脚本 用于查找数据库第一行中的最后一个值 import sqlite3 global SerialNum conn sqlite3 connect MyFirstDB db conn text factory str c con
  • tkinter:打开一个带有按钮提示的新窗口[关闭]

    Closed 这个问题需要调试细节 help minimal reproducible example 目前不接受答案 用户如何按下 tkinter GUI 中的按钮来打开新窗口 我只需要非常简单的解决方案 如果代码也能被解释那就太好了 这

随机推荐

  • Spring MVC 中如何处理静态内容?

    我正在使用 Spring MVC 3 开发一个 web 应用程序 并且有DispatcherServlet像这样捕获所有对 的请求 web xml
  • 在 React 中将函数传递给 setState() 有什么好处?

    我有一个函数叫做onRemove是这样写的 const todos setTodos useState todoData const onRemove useCallback id gt setTodos todos filter todo
  • 如何在 photoLibrary 或相机中快速裁剪 4*3 图像

    我想在使用相机后裁剪图像或从照片库中选择图像 目前 我只能裁剪方形图像 不知道如何裁剪 4 3 图像 这是我的部分代码 let imagePicker UIImagePickerController UIImagePickerControl
  • VSCode,如何获取setup.bash等环境变量文件?

    所以我正在使用 WSL ROS 和 VSCode 在 Ubuntu 上工作时 我只需在运行 VsCode 之前获取 opt ros ros distro setup bash 来获取环境变量 使用 WSL 时 我需要一种从已打开的 VSCo
  • 从正则表达式重定向中排除目录

    我希望将所有带有下划线的 URL 重定向到其对应的虚线 E g nederland amsterdam car rental变成 nederland amsterdam car rental 为此 我使用此处描述的技术 如何使用 Nginx
  • Delphi:如何在本地创建和使用线程?

    我的数据库位于 VPS 中 我应该从我的表中获取一些查询 由于从服务器获取查询需要很长时间 取决于互联网速度 我想使用线程来获取查询 现在我创建一个线程并获取查询 然后通过发送和处理消息将结果发送到我的表单 我想知道是否可以在本地创建和使用
  • 多线程中的Tornado多个IOLoop

    我正在尝试在多个线程中运行多个 IOLoop 我想知道 IOLoop 实际上是如何工作的 class WebThread threading Thread def init self threading Thread init self n
  • 如何在 PHP 中获取两个日期之间的所有月份?

    我有 2 个约会 我想获得所有月份的总天数 我怎样才能在 PHP 中做到这一点 例如 date1 2013 11 13 yy mm dd format date2 2014 02 14 Output Months Total Days 11
  • C# 上的 DllImport

    如何在 C 中访问 C DLL 的函数 以下是 DLL 的原型 NOMANGLE int CCONV SSPSendCommand SSP COMMAND cmd SSP COMMAND INFO sspInfo NOMANGLE int
  • 使用 ~(波形符)导入 SCSS 文件在 Angular 6 中不起作用

    我有两个问题scssAngular6 中的文件导入 我需要将我的部分内容导入到我的所有内容中吗 component scss在全局中导入一次后的文件src sass styles scss 导入一次还不够吗 我如何导入SCSS使用导入快捷方
  • 浮点除以零而不是 constexpr

    编译时 constexpr double x 123 0 constexpr double y x 0 0 std cout lt lt x lt lt 0 lt lt y lt lt n 编译器 gcc 4 9 2 std c 11 或
  • 在 Dart 中进行系统调用?

    我想从 dart 内部执行 python 或 java 类 以下是我从 stackoverflow 问题 Java 中使用的片段 Runtime currentRuntime Runtime getRuntime Process execu
  • 计算相机近平面和远平面边界

    我正在尝试执行中提到的计算使用 THREE Frustum 计算近 远平面顶点 https stackoverflow com questions 12018710 calculate near far plane vertices usi
  • 用css根据屏幕尺寸制作圆形图像

    我正在尝试将我的图像制作为圆形 尽管该图像具有不同的宽度和高度 但我希望它是圆形 看起来它们具有相同的宽度和高度长度 例如 我的图像尺寸 250X300 但我希望它是200X200圆 实际上我可以轻松做到这一点 问题是根据屏幕尺寸执行此操作
  • 即使连接了硬件键盘也显示 iPhone 软键盘

    我的 iPad 应用程序使用充当硬件键盘的外部 设备 但是 在设置中的某个时刻 我需要输入文本 但无法使用 设备 设备 不是键盘 那么 即使我连接了硬件键盘 有没有办法强制弹出软键盘 是的 当用户拥有与设备配对的蓝牙扫描仪 键盘 时 我们已
  • 通过 MediatR PipelineBehavior 进行单元测试验证

    我正在使用 FluentValidation 和 MediatR PipelineBehavior 来验证 CQRS 请求 我应该如何在单元测试中测试这种行为 Use the 测试扩展 https docs fluentvalidation
  • Java中不使用队列的二叉树右视图

    HERE http www geeksforgeeks org print right view binary tree 2 是不使用队列的二叉树右视图的C 实现 当我尝试将其转换为 Java 时 它不起作用 这是我的Java代码 我认为很
  • 如何修复 cordova 构建错误:不支持的类文件主要版本 62 [重复]

    这个问题在这里已经有答案了 我运行时收到此错误cordova build android在我的Mac上 FAILURE Build failed with an exception Where Script Users ad8kunle M
  • “触发快照依赖项的更改”似乎无法正常工作

    我正在将 TeamCity 6 5 1 与一个项目和大约 10 个构建配置一起使用 我有一个类似于 Core gt Framework gt Apps 的依赖链 Framework 依赖于 Core App 也依赖于 Core 和 Fram
  • Python 中的主成分分析

    我想使用主成分分析 PCA 来降维 numpy 或 scipy 是否已经有了它 或者我必须使用自己的numpy linalg eigh http docs scipy org doc numpy reference generated nu