V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
sukai0me
V2EX  ›  Python

在 numpy 中进行矩阵运算,用 arrays 和 matrices 哪个好一些?

  •  
  •   sukai0me · Mar 23, 2016 · 4973 views
    This topic created in 3691 days ago, the information mentioned may be changed or developed.

    本人刚刚接触 numpy ,使用 np.array( )创建“矩阵”(实则是多维数组),但遇到一些降维的函数操作,比如 np.sum( ), np.mean( ), np.diag( )等, arrays 原先的维度将不被友好地保存,如图所示,图片摘自 stackoverflow :

    这是我 google 得到的最棒的答案: http://stackoverflow.com/questions/4151128/what-are-the-differences-between-numpy-arrays-and-matrices-which-one-should-i-u

    也欢迎 V2EX 的盆友们,一起讨论讨论。 特别是 arrays 遇到降维操作时,如何优雅得处理?

    7 replies    2016-03-23 20:52:48 +08:00
    chuan
        1
    chuan  
       Mar 23, 2016
    numpy 的坑啊,一开始学的时候各种受不了,后来习惯了。。一般还是推荐用 array 多些吧
    chlx
        2
    chlx  
       Mar 23, 2016
    图片挂了.
    能用 ndarray 就别用 matrices.
    关于维度的问题执行这些会降维的函数时指定 axis 对哪个维度操作
    另外个也该看看的, broadcasting:
    http://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html
    sukai0me
        3
    sukai0me  
    OP
       Mar 23, 2016
    @chuan 总觉着 numpy 的设计有些反人类...
    sukai0me
        4
    sukai0me  
    OP
       Mar 23, 2016
    @chlx
    图片:![numpy reduce function]( http://chuantu.biz/t2/33/1458704263x3738746571.png)

    再补充有关降维函数:若 A 为 2x2 的 array ( A.shape=(2,2)),进行 np.sum(A, 0),指定 axis 为 0 ,得到的结果不在是二维数组,而是一维数组,即: np.sum(A, 0).shape=( 2, ),也就是我所说的维度不被保存
    chlx
        5
    chlx  
       Mar 23, 2016
    @sukai0me
    shape=(2, ) 很直观呐.
    如果需要保留维度的话 np.sum(A, axis=0, keepdims=1)
    chuan
        6
    chuan  
       Mar 23, 2016
    @sukai0me 同感,这个设计多少还是阻挡了一些人学习的欲望
    sukai0me
        7
    sukai0me  
    OP
       Mar 23, 2016
    @chlx 谢谢!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2271 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 01:22 · PVG 09:22 · LAX 18:22 · JFK 21:22
    ♥ Do have faith in what you're doing.