如何在每批中创建具有不同元素的火炬对角线矩阵?

How do I create a torch diagonal matrices with different element in each batch?

我想创建一个像

这样的张量
 tensor([[[1,0,0],[0,1,0],[0,0,1]],[[2,0,0],[0,2,0],[0,0,2]]]])

也就是说,当给定一个大小为 (1,n) 的火炬张量 B 时,我想创建一个大小为 (n,3,3) 的火炬张量 A,使得 A[i] 是一个 B[ i] *(大小为 3x3 的单位矩阵)。

不使用 'for sentence',我该如何创建它?

使用torch.einsum(爱因斯坦的求和符号)

A = torch.eye(3)
b = torch.tensor([1.0, 2.0, 3.0])
torch.einsum('ij,k->kij', A, b)

会 return:

tensor([[[1., 0., 0.],
     [0., 1., 0.],
     [0., 0., 1.]],

    [[2., 0., 0.],
     [0., 2., 0.],
     [0., 0., 2.]],

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