python 在推理时运行pytorch模型,即batch_size==1,而不是使用训练的batch_size

nhaq1z21  于 2023-03-16  发布在  Python
关注(0)|答案(1)|浏览(262)

我已经训练了一个Pytorch模型,现在我想使用它,为了简化,我使用了一个线性模型,它的Tensor形式为(250,120,8);批量大小为250,数据样本大小为120,8,现在我想使用模型,只输入大小为(120,8)的Tensor,就可以得到结果,但这不起作用,模型总是需要大小为(250,120,8)的Tensor,我查了Pytorch库,但他们没有写任何相关内容。
--〉那么,当我只对一个数据样本感兴趣时,我如何在推理中使用我的模型呢?

hparams = {}
hparams['num_features'] = 8
hparams['seq_len'] = 120
model = transformer.linear(hparams=hparams)
model.load_state_dict(torch.load(file_path))
model.eval()
# this is ok
print(model(torch.rand(250,120,8),'cpu').shape) # returns (250,desired_output_size)
# but I want to do this 
model(torch.rand(120,8),'cpu') # here I get an error message
uoifb46i

uoifb46i1#

pytorch中的大多数层都假设第一个维度是批维度,你可以将一个单一维度解压缩到你的输入中,使它具有[1, ...]的形状,这不会复制任何数据,所以不会增加任何明显的延迟。

x = torch.rand(120,8)    # shape [120, 8]
x = x.unsqueeze(0)       # shape [1, 120, 8]
y = model(x,'cpu')       # shape [1, desired_size]
y = y.squeeze(0)         # shape [desired_size]

当然,如果你想的话,你可以在一条线上完成挤压/解压。

x = torch.rand(120,8)
y = model(x.unsqueeze(0), 'cpu').squeeze(0)

相关问题