本文介绍了共轭转置运算符“.H"在 numpy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 numpy 中使用 .T 属性来获取 ndarray 的转置版本非常方便.但是,没有类似的方法来获得共轭转置.Numpy 的矩阵类有 .H 运算符,但没有 ndarray.因为我喜欢可读的代码,而且因为我懒得总是写 .conj().T,我希望 .H 属性总是对我可用.如何添加此功能?是否可以添加它,以便每次导入 numpy 时都可以无脑地使用它?

It is very convenient in numpy to use the .T attribute to get a transposed version of an ndarray. However, there is no similar way to get the conjugate transpose. Numpy's matrix class has the .H operator, but not ndarray. Because I like readable code, and because I'm too lazy to always write .conj().T, I would like the .H property to always be available to me. How can I add this feature? Is it possible to add it so that it is brainlessly available every time numpy is imported?

(关于 .I 逆运算符可以问类似的问题.)

(A similar question could by asked about the .I inverse operator.)

推荐答案

总的来说,这个问题的难点在于 Numpy 是一个 C 扩展,不能被猴子补丁......或者可以吗?forbiddenfruit 模块允许人们这样做,虽然感觉有点像在玩刀.

In general, the difficulty in this problem is that Numpy is a C-extension, which cannot be monkey patched...or can it? The forbiddenfruit module allows one to do this, although it feels a little like playing with knives.

这就是我所做的:

  1. 安装非常简单的forbiddenfruit

确定用户自定义目录:

import site
print site.getusersitepackages()

  • 在该目录中,编辑 usercustomize.py 以包含以下内容:

    from forbiddenfruit import curse
    from numpy import ndarray
    from numpy.linalg import inv
    curse(ndarray,'H',property(fget=lambda A: A.conj().T))
    curse(ndarray,'I',property(fget=lambda A: inv(A)))
    

  • 测试一下:

  • Test it:

    python -c python -c "import numpy as np; A = np.array([[1,1j]]);  print A; print A.H"
    

    结果:

    [[ 1.+0.j  0.+1.j]]
    [[ 1.-0.j]
     [ 0.-1.j]]
    

  • 这篇关于共轭转置运算符“.H"在 numpy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-29 07:13