[英]How to populate torch::tensor with c++ array?
This is very basic: I am normally using Eigen3 for my math operations, but need to use libtorch for a network forward pass.这是非常基本的:我通常使用 Eigen3 进行数学运算,但需要使用 libtorch 进行网络前向传递。 Now I want to populate the torch::tensor
with the data from my Eigen3 (or pure C++ array
), but without a for
loop.现在我想用我的 Eigen3(或纯 C++ array
)中的数据填充torch::tensor
,但没有for
循环。 How can I do this?我怎样才能做到这一点?
Here is the solution with a loop:这是带有循环的解决方案:
Eigen::Matrix<double, N, 1> inputEigen; // previously initialized
torch::Tensor inputTorch = torch::ones({1, N}); // my torch tensor for the forward pass
for (int i = 0; i < N; i++) {
inputTorch[0][i] = inputEigen[i]; // batch size == 1
}
std::vector<torch::jit::IValue> inputs;
inputs.push_back(inputTorch);
at::Tensor output = net.forward(inputs).toTensor();
This works fine for now, but N
might become really large and I'm just looking for a way to directly set the underlying data of my torch::tensor
with a previously used C++ array
这目前工作正常,但N
可能会变得非常大,我只是在寻找一种方法来直接使用以前使用的 C++ array
设置我的torch::tensor
的基础数据
Libtorch provides the torch::from_blob
function (see this thread ), which asks for a void*
pointer to some data and an IntArrayRef
to know the dimensions of the interpreted data. Libtorch 提供了torch::from_blob
function(参见这个线程),它要求一个指向某些数据的void*
指针和一个IntArrayRef
来了解解释数据的维度。 So that would give something like:所以这会给出类似的东西:
Eigen::Matrix<double, N, 1> inputEigen; // previously initialized;
torch::Tensor inputElement = torch::from_blob(inputEigen.data(), {1,N}).clone(); // dims
Please note the call to clone
which you may or may not need depending or your use case: basically from_blob
does not take ownership of the underlying data, so without the clone it will remain shared with (and possibly destroyed by) your Eigen matrix请注意您可能需要或不需要的clone
调用,具体取决于您的用例:基本上from_blob
不获取基础数据的所有权,因此如果没有克隆,它将与您的特征矩阵保持共享(并可能被销毁)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.