张量元组
Tuple of Tensors
我最近问了这个问题的一部分。我正在构建一个聊天机器人,并且有一个功能会产生问题。函数如下:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1).cuda())
else:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1))
return batch_inputs, lengths_inputs
但是当我尝试 运行 聊天机器人代码时,它给我这个错误:
stack(): argument 'tensors' (position 1) must be tuple of Tensors, not tensor
出于这个原因,我修复了这样的功能:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.stack(inputs, 1).cuda()
else:
batch_inputs = torch.stack(inputs, 1)
return batch_inputs, lengths_inputs
但是还是报错,报错是这样的:
TypeError: expected Tensor as element 0 in argument 0, but got list
遇到这种情况我该怎么办?
由于vec
和length
都是整数,可以直接用torch.tensor
:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.tensor(inputs, device='cuda')
else:
batch_inputs = torch.tensor(inputs)
return batch_inputs, lengths_inputs
我最近问了这个问题的一部分。我正在构建一个聊天机器人,并且有一个功能会产生问题。函数如下:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1).cuda())
else:
batch_inputs = Variable(torch.stack(torch.Tensor(inputs),1))
return batch_inputs, lengths_inputs
但是当我尝试 运行 聊天机器人代码时,它给我这个错误:
stack(): argument 'tensors' (position 1) must be tuple of Tensors, not tensor
出于这个原因,我修复了这样的功能:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.stack(inputs, 1).cuda()
else:
batch_inputs = torch.stack(inputs, 1)
return batch_inputs, lengths_inputs
但是还是报错,报错是这样的:
TypeError: expected Tensor as element 0 in argument 0, but got list
遇到这种情况我该怎么办?
由于vec
和length
都是整数,可以直接用torch.tensor
:
def variable_from_sentence(sentence):
vec, length = indexes_from_sentence(sentence)
inputs = [vec]
lengths_inputs = [length]
if hp.cuda:
batch_inputs = torch.tensor(inputs, device='cuda')
else:
batch_inputs = torch.tensor(inputs)
return batch_inputs, lengths_inputs