3

我需要将一个张量 (in ) 的一行复制c++ API到另一个张量的某个部分,其中 begin 和 end 索引可用。在 C++ 中,我们可以使用类似的东西:

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

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

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

4

2 回答 2

5

C++ API 提供Python 切片等效函数

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

因此,您可以执行以下操作:

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

myvector.slice(0, 3, 7) = myints.slice(0, 0, 3);

在你的情况下使用dim=0第一维

于 2019-08-31T11:55:21.040 回答
3

Pytorch 1.5 使用Tensor::indexTensor::index_put_

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}));  

Tensor::index和的一般翻译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几乎完全一样slicecopy_用于分配

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));
于 2020-02-05T11:52:21.687 回答