沿3D数组中的第三个轴计算2D数组的逆数而无循环 [英] Compute inverse of 2D arrays along the third axis in a 3D array without loops

查看:55
本文介绍了沿3D数组中的第三个轴计算2D数组的逆数而无循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为(N, N, K)的数组A,我想计算另一个与B[:, :, i] = np.linalg.inv(A[:, :, i])形状相同的数组B.

作为解决方案,我看到了mapfor循环,但是我想知道numpy是否提供了执行此功能的功能(我尝试过np.apply_over_axes,但似乎只能处理一维数组). /p>

带有for循环:

B = np.zeros(shape=A.shape)
for i in range(A.shape[2]):
    B[:, :, i] = np.linalg.inv(A[:, :, i])

map:

B = np.asarray(map(np.linalg.inv, np.squeeze(np.dsplit(A, A.shape[2])))).transpose(1, 2, 0)

解决方案

对于可逆矩阵M,我们具有inv(M).T == inv(M.T)(逆的转置等于转置的逆).

由于np.linalg.inv是可广播的,因此可以通过简单地转置A,调用inv并转置结果来解决您的问题:

B = np.linalg.inv(A.T).T

例如:

>>> N, K = 2, 3
>>> A = np.random.randint(1, 5, (N, N, K))
>>> A
array([[[4, 2, 3],
        [2, 3, 1]],

       [[3, 3, 4],
        [4, 4, 4]]])

>>> B = np.linalg.inv(A.T).T
>>> B
array([[[ 0.4  , -4.   ,  0.5  ],
        [-0.2  ,  3.   , -0.125]],

       [[-0.3  ,  3.   , -0.5  ],
        [ 0.4  , -2.   ,  0.375]]])

您可以按预期检查B的值是否匹配A中的数组的倒数:

>>> all(np.allclose(B[:, :, i], np.linalg.inv(A[:, :, i])) for i in range(K))
True

I have an array A whose shape is (N, N, K) and I would like to compute another array B with the same shape where B[:, :, i] = np.linalg.inv(A[:, :, i]).

As solutions, I see map and for loops but I am wondering if numpy provides a function to do this (I have tried np.apply_over_axes but it seems that it can only handle 1D array).

with a for loop:

B = np.zeros(shape=A.shape)
for i in range(A.shape[2]):
    B[:, :, i] = np.linalg.inv(A[:, :, i])

with map:

B = np.asarray(map(np.linalg.inv, np.squeeze(np.dsplit(A, A.shape[2])))).transpose(1, 2, 0)

解决方案

For an invertible matrix M we have inv(M).T == inv(M.T) (the transpose of the inverse is equal to the inverse of the transpose).

Since np.linalg.inv is broadcastable, your problem can be solved by simply transposing A, calling inv and transposing the result:

B = np.linalg.inv(A.T).T

For example:

>>> N, K = 2, 3
>>> A = np.random.randint(1, 5, (N, N, K))
>>> A
array([[[4, 2, 3],
        [2, 3, 1]],

       [[3, 3, 4],
        [4, 4, 4]]])

>>> B = np.linalg.inv(A.T).T
>>> B
array([[[ 0.4  , -4.   ,  0.5  ],
        [-0.2  ,  3.   , -0.125]],

       [[-0.3  ,  3.   , -0.5  ],
        [ 0.4  , -2.   ,  0.375]]])

You can check the values of B match the inverses of the arrays in A as expected:

>>> all(np.allclose(B[:, :, i], np.linalg.inv(A[:, :, i])) for i in range(K))
True

这篇关于沿3D数组中的第三个轴计算2D数组的逆数而无循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆