在 C++ 中将一个张量的一大块复制到另一个张量中 API
Copy a chunk of one tensor into another one in C++ API
我需要将一个张量的一行(在 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?
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
第一维
Pytorch 1.5 使用 Tensor::index
和 Tensor::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}));
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));
我需要将一个张量的一行(在 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?
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
第一维
Pytorch 1.5 使用 Tensor::index
和 Tensor::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}));
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));