如何构建一个3D Tensor,其中每个2D子张量都是PyTorch中的对角矩阵?

时间:2017-11-19 00:21:41

标签: torch pytorch tensor

考虑我有2D Tensor,index_in_batch * diag_ele。 如何获得3D张量index_in_batch * Matrix(谁是对角矩阵,由drag_ele构造)?

torch.diag()构造对角矩阵仅在输入为1D时,并在输入为2D时返回对角线元素。

3 个答案:

答案 0 :(得分:7)

import torch

a = torch.rand(2, 3)
print(a)
b = torch.eye(a.size(1))
c = a.unsqueeze(2).expand(*a.size(), a.size(1))
d = c * b
print(d)

<强>输出

 0.5938  0.5769  0.0555
 0.9629  0.5343  0.2576
[torch.FloatTensor of size 2x3]


(0 ,.,.) = 
  0.5938  0.0000  0.0000
  0.0000  0.5769  0.0000
  0.0000  0.0000  0.0555

(1 ,.,.) = 
  0.9629  0.0000  0.0000
  0.0000  0.5343  0.0000
  0.0000  0.0000  0.2576
[torch.FloatTensor of size 2x3x3]

答案 1 :(得分:2)

model.reLoadData();
final int currentEmail = emailForClient; // I'm assuming emailForClient is an int

Platform.runLater(() -> {
    listView.setItems(model.getEmailList());

    if (currentOnServer > currentEmail) {
        new Alert(Alert.AlertType.INFORMATION, "Hai recevuto un email!").showAndWait();
    }
});

emailForClient = currentOnServer;

答案 2 :(得分:0)

通过包装在Variable中自动反向的解决方案。

import torch

a = torch.rand(2, 3)
print(a)

b = Variable(torch.eye(a.size(1)))
c = a.unsqueeze(2).expand(*a.size(), degree_inv.size(1))
b_expand =  b.unsqueeze(0).expand(c.size(0), *b.size())
d = torch.mul(c.double(), b_expand.double())

print(d)