使用Pytorch
的C ++ libtorch前端
我想从C ++ torch::Tensor
数组创建double[]
。
在docs和论坛中都找不到关于该主题的简单文档。
类似的东西:
double array[5] = {1, 2, 3, 4, 5};
auto tharray = torch::Tensor(array, 5, torch::Device(torch::kCUDA));
我发现的唯一一件事是使用torch::from_blob
,但是如果我想将它与CUDA一起使用,则必须clone()
并使用to(device)
。
double array[] = { 1, 2, 3, 4, 5};
auto options = torch::TensorOptions().dtype(torch::kFloat64);
torch::Tensor tharray = torch::from_blob(array, {5}, options);
有没有更清洁的方法?
答案 0 :(得分:5)
我通常使用:
torch::Tensor tharray = torch::tensor({1, 2, 3, 4, 5}, {torch::kFloat64});
答案 1 :(得分:0)
您可以在此处了解有关张量创建的更多信息:https://pytorch.org/cppdocs/notes/tensor_creation.html
在不使用from_blob
的情况下,我不知道从数组创建张量的任何方法,但是您可以使用TensorOptions
来控制有关张量的各种事物,包括其设备。
根据您的示例,您可以在GPU上创建张量,如下所示:
double array[] = { 1, 2, 3, 4, 5};
auto options = torch::TensorOptions().dtype(torch::kFloat64).device(torch::kCUDA, 1);
torch::Tensor tharray = torch::from_blob(array, {5}, options);
答案 2 :(得分:0)
我没有更干净的方法,但是我会给你另一种方法。
double array[5] = {1, 2, 3, 4, 5};
auto tharray = torch::zeros(5,torch::kFloat64) //or use kF64
std::memcpy(tharray.data_ptr(),array,sizeof(double)*tharray.numel())
希望它会有所帮助。
将KF64
改正为kFloat64
,因为在炬管中不存在KF64