Python 矩阵的逆矩阵

发布于 2024-07-07 02:27:18 字数 64 浏览 12 评论 0原文

如何在Python中得到矩阵的逆矩阵? 我自己实现了它,但它是纯Python,我怀疑有更快的模块可以做到这一点。

How do I get the inverse of a matrix in python? I've implemented it myself, but it's pure python, and I suspect there are faster modules out there to do it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

温折酒 2024-07-14 02:27:18

如果你进行矩阵操作,你应该看看 numpy 。 这是一个主要用C编写的模块,会比纯python编程快很多。 以下是如何反转矩阵以及进行其他矩阵操作的示例。

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

您还可以查看 array 模块,这是一个更多当您只需要处理一种数据类型时,可以有效地实现列表。

You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.

折戟 2024-07-14 02:27:18

确保您确实需要反转矩阵。 这通常是不必要的,并且可能在数值上不稳定。 当大多数人问如何反转矩阵时,他们真正想知道如何求解 Ax = b,其中 A 是矩阵,x 和 b 是向量。 使用代码直接求解 x 的方程 Ax = b 比计算 A 的逆然后将逆乘以 B 更高效、更准确。即使您需要求解许多 b 值的 Ax = b,这也不是一个好主意如果您必须求解系统的多个 b 值,请保存 A 的 Cholesky 因式分解,但不要反转它。

请参阅不要反转该矩阵

Make sure you really need to invert the matrix. This is often unnecessary and can be numerically unstable. When most people ask how to invert a matrix, they really want to know how to solve Ax = b where A is a matrix and x and b are vectors. It's more efficient and more accurate to use code that solves the equation Ax = b for x directly than to calculate A inverse then multiply the inverse by B. Even if you need to solve Ax = b for many b values, it's not a good idea to invert A. If you have to solve the system for multiple b values, save the Cholesky factorization of A, but don't invert it.

See Don't invert that matrix.

暖伴 2024-07-14 02:27:18

遗憾的是,这里再次重复的所选矩阵要么是奇异的,要么是条件不良的:

A = matrix( [[1,2,3],[11,12,13],[21,22,23]])

根据定义,A 的逆乘以矩阵 A 本身必须给出单位矩阵。 在广受好评的解释中选择的 A 并没有做到这一点。 事实上,只要看一下逆函数就可以看出逆函数没有正确工作。 看看各个项的大小 - 与原始 A 矩阵的项相比,它们非常非常大……

值得注意的是,人类在选择矩阵示例时常常设法选择奇异矩阵!

我确实对解决方案有疑问,所以进一步研究了它。 在ubuntu-kubuntu平台上,debian包numpy没有matrix和linalg子包,所以除了导入numpy外,还需要导入scipy。

如果 A 的对角项乘以足够大的因子(例如 2),则矩阵很可能不再是奇异的或接近奇异的。 因此,

A = matrix( [[2,2,3],[11,24,13],[21,22,46]])

它既不是奇异的,也不是接近奇异的,并且该示例给出了有意义的结果......在处理浮点数时,必须注意不可避免的舍入误差的影响。

It is a pity that the chosen matrix, repeated here again, is either singular or badly conditioned:

A = matrix( [[1,2,3],[11,12,13],[21,22,23]])

By definition, the inverse of A when multiplied by the matrix A itself must give a unit matrix. The A chosen in the much praised explanation does not do that. In fact just looking at the inverse gives a clue that the inversion did not work correctly. Look at the magnitude of the individual terms - they are very, very big compared with the terms of the original A matrix...

It is remarkable that the humans when picking an example of a matrix so often manage to pick a singular matrix!

I did have a problem with the solution, so looked into it further. On the ubuntu-kubuntu platform, the debian package numpy does not have the matrix and the linalg sub-packages, so in addition to import of numpy, scipy needs to be imported also.

If the diagonal terms of A are multiplied by a large enough factor, say 2, the matrix will most likely cease to be singular or near singular. So

A = matrix( [[2,2,3],[11,24,13],[21,22,46]])

becomes neither singular nor nearly singular and the example gives meaningful results... When dealing with floating numbers one must be watchful for the effects of inavoidable round off errors.

帥小哥 2024-07-14 02:27:18

对于像我这样正在寻找不涉及 pandasnumpy 的纯 Python 解决方案的人,请查看以下 GitHub 项目:https://github.com/ThomIves/MatrixInverse

它慷慨地很好地解释了该过程的“幕后”情况。 作者很好地描述了分步方法,并提供了一些实际示例,都很容易理解。

这只是其中的一小段代码,用于非常简要地说明该方法(AM 是源矩阵,IM 是相同大小的单位矩阵):

def invert_matrix(AM, IM):
    for fd in range(len(AM)):
        fdScaler = 1.0 / AM[fd][fd]
        for j in range(len(AM)):
            AM[fd][j] *= fdScaler
            IM[fd][j] *= fdScaler
        for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
            crScaler = AM[i][fd]
            for j in range(len(AM)):
                AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
                IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
    return IM

但请务必遵循整个内容,您将学到的不仅仅是复制粘贴此代码!顺便说一句,还有一个 Jupyter 笔记本。

希望对某人有帮助,我个人发现它对于我非常特殊的任务非常有用(吸收马尔可夫链)我无法使用任何非标准包。

For those like me, who were looking for a pure Python solution without pandas or numpy involved, check out the following GitHub project: https://github.com/ThomIves/MatrixInverse.

It generously provides a very good explanation of how the process looks like "behind the scenes". The author has nicely described the step-by-step approach and presented some practical examples, all easy to follow.

This is just a little code snippet from there to illustrate the approach very briefly (AM is the source matrix, IM is the identity matrix of the same size):

def invert_matrix(AM, IM):
    for fd in range(len(AM)):
        fdScaler = 1.0 / AM[fd][fd]
        for j in range(len(AM)):
            AM[fd][j] *= fdScaler
            IM[fd][j] *= fdScaler
        for i in list(range(len(AM)))[0:fd] + list(range(len(AM)))[fd+1:]:
            crScaler = AM[i][fd]
            for j in range(len(AM)):
                AM[i][j] = AM[i][j] - crScaler * AM[fd][j]
                IM[i][j] = IM[i][j] - crScaler * IM[fd][j]
    return IM

But please do follow the entire thing, you'll learn a lot more than just copy-pasting this code! There's a Jupyter notebook as well, btw.

Hope that helps someone, I personally found it extremely useful for my very particular task (Absorbing Markov Chain) where I wasn't able to use any non-standard packages.

み格子的夏天 2024-07-14 02:27:18

您可以计算递归矩阵的行列式
然后形成邻接矩阵

这是一个简短的教程

我认为这只是适用于方阵

另一种计算方法涉及格拉姆-施密特正交化,然后转置矩阵,正交化矩阵的转置是其逆矩阵!

You could calculate the determinant of the matrix which is recursive
and then form the adjoined matrix

Here is a short tutorial

I think this only works for square matrices

Another way of computing these involves gram-schmidt orthogonalization and then transposing the matrix, the transpose of an orthogonalized matrix is its inverse!

路还长,别太狂 2024-07-14 02:27:18

Numpy 适合大多数人,但您也可以 Sympy 中的矩阵

尝试在 http://live.sympy.org/ 运行这些命令

M = Matrix([[1, 3], [-2, 3]])
M
M**-1

为了好玩,请尝试 M** (1/2)

Numpy will be suitable for most people, but you can also do matrices in Sympy

Try running these commands at http://live.sympy.org/

M = Matrix([[1, 3], [-2, 3]])
M
M**-1

For fun, try M**(1/2)

久而酒知 2024-07-14 02:27:18

如果您讨厌 numpy,请拿出 RPy 和 R 的本地副本,然后使用它。

(我也想告诉你,你确实需要反转矩阵。例如,在 R 中,linalg.solve 和solve() 函数实际上并不执行完全反转,因为它是不必要的。)

If you hate numpy, get out RPy and your local copy of R, and use it instead.

(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文