如何基于模运算将零添加到 PyTorch 张量的末尾?
How can I add zeroes to the end of a PyTorch tensor based on a modulo operation?
我有一个张量,大小为:torch.Size([1, 305760])
由于305760
不能被400整除,我想将大小改为:[1, 306000]
用0
填充剩余的空间。我如何使用 PyTorch 做到这一点?
a = torch.randn(1,305760)
N = a.shape[1]
M = 400
b = torch.zeros([a.shape[0], (N // M + 1 ) * 400 - N])
a = torch.cat((a, b), 1)
您需要实现一个舍入函数,让您指定要舍入到的基数。这应该有效:
def myround(x, base):
return base * -(-x // base)
torch.Size([1, myround(305760,400)])
基于以下 question 但修改为强制四舍五入。
我有一个张量,大小为:torch.Size([1, 305760])
由于305760
不能被400整除,我想将大小改为:[1, 306000]
用0
填充剩余的空间。我如何使用 PyTorch 做到这一点?
a = torch.randn(1,305760)
N = a.shape[1]
M = 400
b = torch.zeros([a.shape[0], (N // M + 1 ) * 400 - N])
a = torch.cat((a, b), 1)
您需要实现一个舍入函数,让您指定要舍入到的基数。这应该有效:
def myround(x, base):
return base * -(-x // base)
torch.Size([1, myround(305760,400)])
基于以下 question 但修改为强制四舍五入。