我应该如何从特征 3 中的张量切片中获取向量



我正在撕扯头发,试图以Eigen::VectorXd访问Eigen::Tensor<double, 3>中的一列数据。

根据这个答案,切片可以很好地为我提供我想要的列。但是我不能将其分配给向量。

我有什么:

Eigen::Tensor<double, 3> my_tens(2, 3, 4);
my_tens.setRandom();
Eigen::array<Eigen::Index, 3> dims = my_tens.dimensions();
Eigen::array<Eigen::Index, 3> offsets = {0, 1, 0};
Eigen::array<Eigen::Index, 3> extents = {dims[0], 1, 1};
// This works perfectly, and is exactly the column I want:
std::cout << my_tens.slice(offsets, extents);
// ... and I want it as a VectorXd, so:
Eigen::VectorXd my_vec(dims[0]);

我尝试过的以下事情都失败了:

// Direct assignment (won't compile, no viable overloaded '=')
my_vec = my_tens.slice(offsets, extents);
// Initialisation (won't compile, no viable overloaded '<<')
my_vec << my_tens.slice(offsets, extents);
// Same problem with reshaping:
g_a = signature_a.g.slice(offsets, extents).reshape(Eigen::array<Eigen::Index, 2>{dims[0], 1});
// Converting the base (won't compile, no member 'matrix')
my_vec << my_tens.slice(offsets, extents).matrix();

我也尝试了映射,如这个答案,但这也不起作用(编辑:我认为这是由于存储顺序,但实际上是由于不正确的偏移,请参阅我的答案(:

// This produces a part of a row of the tensor, not a column. Gah!
auto page_offset = offsets[2] * dims[0] * dims[1];
auto col_offset = offsets[1] * dims[0];
auto bytes_offset = sizeof(double) * (page_offset + col_offset)
Eigen::Map<Eigen::VectorXd> my_mapped_vec(my_tens.data() + bytes_offset, dims[0]);

真的应该这么难,还是我错过了一些简单的东西?感谢您的任何帮助!

回答了我自己的问题:是的,我错过了一些简单的东西。通过比较我从地图操作中获得的数字,我意识到偏移量是 8 倍;即通过sizeof(double).

我没有意识到操作my_tens.data() + bytes_offset需要my_tens.data(),一个const double *,而不是添加固定数量的字节来偏移指针,而是用该数量的元素来偏移它。

这是正确的代码:

Eigen::Tensor<double, 3> my_tens(2, 3, 4);
my_tens.setRandom();
Eigen::array<Eigen::Index, 3> dims = my_tens.dimensions();
Eigen::array<Eigen::Index, 3> offsets = {0, 1, 0};
Eigen::array<Eigen::Index, 3> extents = {dims[0], 1, 1};
// Compute the offset, correctly this time!
auto page_offset = offsets[2] * dims[0] * dims[1];
auto col_offset = offsets[1] * dims[0];
auto elements_offset = page_offset + col_offset;
// Map into the array
Eigen::Map<Eigen::VectorXd> my_mapped_vec(my_tens.data() + elements_offset, dims[0]);
// Compare the two:
std::cout << my_tens.slice(offsets, extents) << std::endl;
std::cout << my_mapped_vec.transpose() << std::endl;

最新更新