我需要将一个张量(在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?
答案 0 :(得分:3)
Tensor::index
和Tensor::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}})
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);