在C ++ API中将一个张量的一部分复制到另一个张量中

时间:2019-07-05 20:24:58

标签: c++ pytorch libtorch

我需要将一个张量(在c++ API中)的行复制到另一个张量的某个部分,该形式可以使用开始索引和结束索引。在C ++中,我们可以使用类似的东西:

int myints[] = {10, 20, 30, 40, 50, 60, 70};
std::vector<int> myvector(18);

std::copy(myints, myints + 3, myvector.begin() + 4);

从第四个索引开始,将三个值从myints复制到myvector中。 我想知道libtorch(例如C ++)中是否有类似的API?

3 个答案:

答案 0 :(得分:3)

使用Tensor::indexTensor::index_put_的Pytorch 1.5

using namespace torch::indexing;

auto myints = torch::Tensor({10, 20, 30, 40, 50, 60, 70});
auto myvector = torch::ones({18});    
myvector.index_put_({3, 7}, myints.index({0, 3}));  

General translation for Tensor::index and Tensor::index_put_

Python             C++ (assuming `using namespace torch::indexing`)
-------------------------------------------------------------------
0                  0
None               None
...                "..." or Ellipsis
:                  Slice()
start:stop:step    Slice(start, stop, step)
True / False       true / false
[[1, 2]]           torch::tensor({{1, 2}})

Pytorch 1.4替代功能

Tensor Tensor::narrow(int64_t dim, int64_t start, int64_t length) 

Tensor & Tensor::copy_(const Tensor & src, bool non_blocking=false)

narrow几乎与slice类似,并且使用copy_进行分配

auto myints = torch::Tensor({10, 20, 30, 40, 50, 60, 70});
auto myvector = torch::ones({18});

myvector.narrow(0, 3, 4).copy_(myvector.narrow(0, 0, 3));

答案 1 :(得分:0)

您可以简单地使用数组切片:

myints = torch.tensor([10,20,30,40,50,60,70])
myvector = torch.ones(18)

myvector[4:7] = myints[:3]
# tensor([ 1.,  1.,  1.,  1., 10., 20., 30.,  1.,  1.,  1.,  1.,  1.,  1.,  1.,
#         1.,  1.,  1.,  1.])

这是您要寻找的吗?

答案 2 :(得分:0)

C ++ API提供了功能

User

您可以执行类似

的操作
at::Tensor at::Tensor::slice(int64_t dim, int64_t start, int64_t end, int64_t step);