如何用 python 生成恒等张量?

How to generate identity tensor with python?

我知道 np.eye 生成单位矩阵。我的意思是单位矩阵为

In linear algebra, the identity matrix, or sometimes ambiguously called a unit matrix, of size n is the n × n square matrix with ones on the main diagonal and zeros elsewhere.

而且我知道我们可以在 Numpy 中使用 np.identity(3) 创建它。

But, I would like to know how can I have an identity Tensor in python.

我想在张量乘法中使用恒等张量。如下所示:

其中 G = Er ×1 U1 ×2 U2 ...×M UM 是变换张量,Er ∈ R r×r×...×r 是恒等张量(对角线元素为1,其他所有项为0)。我需要生成 identity tensor.

的代码

提前致谢。

而不是 np.identity 使用 tf.eye:

tf.eye(2)
# [[1., 0.],
#  [0., 1.]]

是这样的吗?

def nd_id(n, d):
    out = np.zeros( (n,) * d )
    out[ tuple([np.arange(n)] * d) ] = 1
    return out

测试

nd_id(3,3)
Out[]: 
array([[[ 1.,  0.,  0.],
        [ 0.,  0.,  0.],
        [ 0.,  0.,  0.]],

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

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

如果所有索引都相等,可以使用 returns 一个函数来完成,但必须对其进行矢量化才能在 np.fromfunction

中使用
np.fromfunction(np.vectorize(lambda i,j,k: int(i==j==k)), (3,3,3))

输出:

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

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

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