[英]How can I set the diagonal of an N-dim tensor to 0 along given dims?
I'm trying to figure out a way to set the diagonal of a 3-dimensional Tensor (along 2 given dims) equal to 0. An example of this would be, let's say I have a Tensor of shape [N,N,N] and I wanted to set the diagonal along dim=1,2 equal to 0?我正在尝试找出一种方法将 3 维张量的对角线(沿 2 个给定的暗角)设置为 0。例如,假设我有一个形状为 [N,N,N 的张量] 我想将沿 dim=1,2 的对角线设置为 0? How exactly could that be done?
究竟是怎么做到的?
I tried using fill_diagonal_
but that only does the k-th diagonal element for each sub-array, ie:我尝试使用
fill_diagonal_
但这只对每个子数组的第 k 个对角线元素执行,即:
>>> data = torch.ones(3,4,4)
>>> data.fill_diagonal_(0)
tensor([[[0, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 1, 1],
[1, 1, 1, 1]],
[[1, 1, 1, 1],
[1, 1, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 1]]])
whereas I would want the entire diagonal for each sub-matrix to be equal to 0 here.而我希望每个子矩阵的整个对角线在此处等于 0。 So, the desired outcome would be,
所以,期望的结果是,
tensor([[[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]],
[[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]],
[[0, 1, 1, 1],
[1, 0, 1, 1],
[1, 1, 0, 1],
[1, 1, 1, 0]]])
Secondly, the reason I state for a given pair of dimension is, I need to repeat this `zeroing' along 2 different pairs of dimensions (eg dim=(1,2) then dim=(0,1)) to get the required masking I need.其次,对于给定的一对维度,我 state 的原因是,我需要沿着 2 对不同的维度(例如 dim=(1,2) 然后 dim=(0,1))重复此“归零”以获得所需的我需要的掩蔽。
Is there a way to mask a given diagonal over 2 arbitrary dimensions for a 3D-tensor?有没有办法在 3D 张量的 2 个任意维度上掩盖给定的对角线?
You can do this with a for loop over the sub-tensors:您可以通过子张量上的for 循环来执行此操作:
# across dim0
for i in range(data.size(0)):
data[i].fill_diagonal_(0)
If you need to perform this over an arbitrary two dimensions of a 3d tensor, simply apply the fill to the appropriate slices:如果您需要在 3d 张量的任意二维上执行此操作,只需将填充应用于适当的切片:
# across dim1
for i in range(data.size(1)):
data[:,i].fill_diagonal_(0)
# across dim2
for i in range(data.size(2)):
data[:,:,i].fill_diagonal_(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.