在Numpy中创建“3D身份矩阵”的最佳方法是什么?

时间:2017-09-04 00:46:24

标签: python numpy matrix

我不知道标题是否有意义。通常,单位矩阵是类似

的2D矩阵
In [1]: import numpy as np

In [2]: np.identity(2)
Out[2]: 
array([[ 1.,  0.],
       [ 0.,  1.]])

并且没有第三维度。

Numpy可以给我带全零的3D矩阵

In [3]: np.zeros((2,2,3))
Out[3]: 
array([[[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.]]])

但是我想要一个“3D身份矩阵”,因为前两个维度上的所有对角元素都是1。例如,对于形状(2,2,3),它应该是

array([[[ 1.,  1.,  1.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 1.,  1.,  1.]]])

有没有优雅的方法来产生这个?

3 个答案:

答案 0 :(得分:4)

从2d单位矩阵开始,您可以使用以下两个选项来制作“3d identity matrix”

import numpy as np    
i = np.identity(2)

选项1 :沿第三维堆叠2d单位矩阵

np.dstack([i]*3)
#array([[[ 1.,  1.,  1.],
#        [ 0.,  0.,  0.]],

#       [[ 0.,  0.,  0.],
#        [ 1.,  1.,  1.]]])

选项2 :重复值,然后重塑

np.repeat(i, 3, axis=1).reshape((2,2,3))
#array([[[ 1.,  1.,  1.],
#        [ 0.,  0.,  0.]],

#       [[ 0.,  0.,  0.],
#        [ 1.,  1.,  1.]]])

选项3 :创建一个零数组,并使用高级索引将1分配给对角元素(第1和第2维)的位置:

shape = (2,2,3)
identity_3d = np.zeros(shape)
idx = np.arange(shape[0])
identity_3d[idx, idx, :] = 1  


identity_3d
#array([[[ 1.,  1.,  1.],
#        [ 0.,  0.,  0.]],

#       [[ 0.,  0.,  0.],
#        [ 1.,  1.,  1.]]])

时序

%%timeit
shape = (100,100,300)
i = np.identity(shape[0])
np.repeat(i, shape[2], axis=1).reshape(shape)

# 10 loops, best of 3: 10.1 ms per loop


%%timeit
shape = (100,100,300)
i = np.identity(shape[0])
np.dstack([i] * shape[2])

# 10 loops, best of 3: 47.2 ms per loop

%%timeit
shape = (100,100,300)
identity_3d = np.zeros(shape)
idx = np.arange(shape[0])
identity_3d[idx, idx, :] = 1

# 100 loops, best of 3: 6.31 ms per loop

答案 1 :(得分:2)

一种方法是初始化2D单位矩阵,然后将其广播到3D。因此,n为前两个轴的长度,最后一个轴为r,我们可以这样做 -

np.broadcast_to(np.identity(n)[...,None], (n,n,r))

示例运行以使事情更清晰 -

In [154]: i = np.identity(3); i # Create an identity matrix
Out[154]: 
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.]])

# Extend it to 3D. This helps us broadcast to reqd. shape later on
In [152]: i[...,None]
Out[152]: 
array([[[ 1.],
        [ 0.],
        [ 0.]],

       [[ 0.],
        [ 1.],
        [ 0.]],

       [[ 0.],
        [ 0.],
        [ 1.]]])

# Broadcast to (n,n,r) shape for the 3D identity matrix    
In [153]: np.broadcast_to(i[...,None], (3,3,3))
Out[153]: 
array([[[ 1.,  1.,  1.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 1.,  1.,  1.],
        [ 0.,  0.,  0.]],

       [[ 0.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 1.,  1.,  1.]]])

这种方法导致性能,因为它只是生成单位矩阵的视图。因此,在该形式中,输出将是只读数组。如果您需要一个具有自己的内存空间的可写数组,只需在那里附加.copy()

断言性能,这是一个时间测试,用于创建形状为3D的{​​{1}}单位矩阵:(100, 100, 300) -

In [140]: n,r = 100,300

In [141]: %timeit np.broadcast_to(np.identity(n)[...,None], (n,n,r))
100000 loops, best of 3: 9.29 µs per loop

答案 2 :(得分:0)

与@Psidom类似,使用高级np.einsum

%%timeit
shape = (100,100,300)
identity_3d = np.zeros(shape)
np.einsum('iij->ij', identity_3d)[:] = 1

1000 loops, best of 3: 251 µs per loop

%%timeit
shape = (100,100,300)
identity_3d = np.zeros(shape)
idx = np.arange(shape[0])
identity_3d[idx, idx, :] = 1

1000 loops, best of 3: 320 µs per loop

%timeit np.broadcast_to(np.identity(100)[...,None], (100,100,300)).copy()

100 loops, best of 3: 12.1 ms per loop

我假设你想要一个copy()的身份矩阵写入,因为anyarray.dot(identity)更容易由np.broadcast_to(anyarray[..., None], a.shape + (300,))计算。如果你真的只想要一个裸identity矩阵,那么@Divakar的解决方案比其他任何矩阵快得多,

%timeit np.broadcast_to(np.identity(100)[...,None], (100,100,300))

The slowest run took 5.16 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 20.8 µs per loop

broadcast_to(anyarray[..., None], . . . )可能比这更快。