2

我正在使用 LibTorch(PyTorch C++ API)在 C++ 中编码。在这里,我传递了 predict_value 和 target_value,它们都是大小为 {1, 1} 的 torch::Tensor。

torch::Tensor loss = torch::nll_loss(predicted_value, target_value);

当我尝试评估上述内容时,出现以下错误:

 0.4997 [ Variable[CPUFloatType]{1,1} ]   # printout of predicted_value
-0.5392 [ Variable[CPUFloatType]{1,1} ]   # printout of target_value
terminate called after throwing an instance of 'c10::Error'
  what():  Expected object of scalar type Long but got scalar type Float for argument #2 'target' in call to _thnn_nll_loss_forward (checked_dense_tensor_unwrap at ../../aten/src/ATen/Utils.h:84)

我尝试搜索如何将浮点类型张量转换为长类型张量,但只能找到 Python 的文档。非常感谢您提出解决此问题的建议!

4

2 回答 2

4

tensor.to(torch::kLong)给你Long类型。

这是Tensor'sto函数的重载定义:

inline Tensor Tensor::to(ScalarType dtype, bool non_blocking, bool copy) const {
    static auto table = globalATenDispatch().getOpTable("aten::to(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False) -> Tensor");
    return table->getOp<Tensor (const Tensor &, ScalarType, bool, bool)>(tensorTypeIdToBackend(type_id()), is_variable())(*this, dtype, non_blocking, copy);
}

于 2020-01-18T15:30:37.437 回答
-1
inline Tensor Tensor::to(ScalarType dtype, bool non_blocking, bool copy) const {
    static auto table = globalATenDispatch().getOpTable("aten::to(Tensor self, ScalarType dtype, bool non_blocking=False, bool copy=False) -> Tensor");
    return table->getOp<Tensor (const Tensor &, ScalarType, bool, bool)>(tensorTypeIdToBackend(type_id()), is_variable())(*this, dtype, non_blocking, copy);
}
于 2021-08-04T19:00:43.743 回答