如何查看输入的哪些索引影响输出的索引



我想测试我的神经网络。

例如,给定:一个输入张量input,一个具有一些子模块modulenn.module,一个输出张量output

我想知道input的哪些指数影响了output的指数(1,2(

更具体地说,给定:

  • 大小为(12
  • 操作为matmul
  • 输出矩阵的查询索引为:(0,0(

预期输出为:

InputMatrix1: (0,0), (0, 1), ..., (0, 11)
InputMatrix2: (0,0), (1, 0), ..., (11, 0)

也许可视化是可以的。

有什么方法或库可以实现这一点吗?

这很容易。您想查看InputMatrix1InputMatrix2grad的非零条目,而不是产品的(0,0)元素:

x = torch.rand((12, 12), requires_grad=True)  # explicitly asking for gradient for this tensor
y = torch.rand((12, 12), requires_grad=True)  # explicitly asking for gradient for this tensor
# compute the product using @ operator:
out = x @ y
# use back propagation to compute the gradient w.r.t out[0, 0]:
out[0,0].backward()

检查输入梯度产量的非零元素,如预期:

In []: x.grad.nonzero()
tensor([[ 0,  0],
[ 0,  1],
[ 0,  2],
[ 0,  3],
[ 0,  4],
[ 0,  5],
[ 0,  6],
[ 0,  7],
[ 0,  8],
[ 0,  9],
[ 0, 10],
[ 0, 11]])
D_6

最新更新