如何用未知值和大小剪掉张量的常量值填充(填充高度和宽度相同)?
How can I crop away a tensor’s constant value padding (padding height and width are the same) with an unknown value and size?
如何用未知值和大小剪掉张量的常量值填充(填充高度和宽度相同)?
我认为因为我的张量周围的填充具有恒定值,并且高度/宽度相同,所以应该可以知道在哪里裁剪张量以移除填充。
import torch
# Test tensor with NCHW dimensions
a = torch.randn(1,4,5,5) # Can have any H & W size
# Create padding for testing
b = torch.nn.functional.pad(a, (2,2,2,2), 'constant', value=1.2) # Value can be any number
c = # equal to a, without being able to use the variables a or b (or their argument values)
NumPy 解决方案是可以接受的,因为我可以轻松地将它们转换为 PyTorch。
编辑:
pad = torch.where(b[0, 0] - b[0, 0, 0, 0] != 0)[0][0]
x_pad, y_pad = 0, 0
if (b.size(3) % 2) == 0:
x_pad = 1
if (b.size(2) % 2) == 0:
y_pad = 1
c = b[:, :, pad : -(pad + y_pad), pad : -(pad + x_pad)]
assert c == a
您可以通过获取特征图的中间行并通过查找第一个元素变化来测量填充来了解特征图的内容:
midrow = b[0, 0, b.shape[3]//2, :]
pad = (midrow[:-1] == midrow[:1])[:midrow.shape[0]//2].sum()
或者,您可以用填充值减去一个特征图并找到第一个非零值,这将是填充大小:
pad = torch.where(b[0,0] - b[0,0,0,0] != 0)[0][0]
有了填充,我们可以丢弃所有批处理元素和所有通道的特征图周围的适量值:
a = b[:, :, pad:-pad, pad:-pad]
如何用未知值和大小剪掉张量的常量值填充(填充高度和宽度相同)?
我认为因为我的张量周围的填充具有恒定值,并且高度/宽度相同,所以应该可以知道在哪里裁剪张量以移除填充。
import torch
# Test tensor with NCHW dimensions
a = torch.randn(1,4,5,5) # Can have any H & W size
# Create padding for testing
b = torch.nn.functional.pad(a, (2,2,2,2), 'constant', value=1.2) # Value can be any number
c = # equal to a, without being able to use the variables a or b (or their argument values)
NumPy 解决方案是可以接受的,因为我可以轻松地将它们转换为 PyTorch。
编辑:
pad = torch.where(b[0, 0] - b[0, 0, 0, 0] != 0)[0][0]
x_pad, y_pad = 0, 0
if (b.size(3) % 2) == 0:
x_pad = 1
if (b.size(2) % 2) == 0:
y_pad = 1
c = b[:, :, pad : -(pad + y_pad), pad : -(pad + x_pad)]
assert c == a
您可以通过获取特征图的中间行并通过查找第一个元素变化来测量填充来了解特征图的内容:
midrow = b[0, 0, b.shape[3]//2, :]
pad = (midrow[:-1] == midrow[:1])[:midrow.shape[0]//2].sum()
或者,您可以用填充值减去一个特征图并找到第一个非零值,这将是填充大小:
pad = torch.where(b[0,0] - b[0,0,0,0] != 0)[0][0]
有了填充,我们可以丢弃所有批处理元素和所有通道的特征图周围的适量值:
a = b[:, :, pad:-pad, pad:-pad]