libtorch踩坑记录


目录


一、多个输入和多个输出

二、二维vector转tensor


一、多个输入和多个输出

  • 输入
    先定义一个std::vector变量,然后逐个添加
// inputs
std::vector inputs;

torch::jit::IValue cate = torch::ones(( 1, 1, 1 ));
std::cout << "cate: " << cate << std::endl;

torch::Tensor temp = torch::randn({ 1, 3, 11705 });
std::cout << "temp size: " << temp.sizes() << " temp 0: " << temp[0][0][0] << std::endl;
inputs.push_back(temp);
inputs.push_back(cate);
  • 输出
    先输出torch::jit::IValue结果,然后根据pytorch端的输出相应得做转变
// forward
torch::jit::IValue output = module.forward(inputs);
std::vector outList = output.toTensorVector();   // it used to return [x1, x2, ...] from pytorch

auto tpl = output.toTuple();                                    // it used to return (x1, x2, ...) from pytorch
auto arm_loc = tpl->elements()[i].toTensor();

二、二维vector转tensor

我的数据是二维数组,可通过以下方式转换,其中torch::Tensor input_tensor = torch::from_blob(points.data(), { n, cols }).toType(torch::kDouble).clone();转出来数据不对,有大佬懂的可以指点一下。

// std::vector> to torch::jit::IValue
int cols = points[0].size();
int n = points.size();

torch::TensorOptions options = torch::TensorOptions().dtype(torch::kFloat32);
torch::Tensor input_tensor = torch::zeros({ n, cols }, options);
for (int i = 0; i < n; i++) {
    input_tensor.slice(0, i, i + 1) = torch::from_blob(points[i].data(), { cols }, options).clone();
}

注意: 一定要有clone()复制一份, 否则数组释放后相应数据也会释放,共享的是同一内存


参考链接

官网API
libtorch 常用api函数示例