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

时间:2019-02-05 13:29:22

标签: c++ c++11 eigen tensor eigen3

我正在努力尝试以Eigen::Tensor<double, 3>的身份访问Eigen::VectorXd中的一列数据。

切片as according to this answer可以很好地为我获取所需的列。但是我不能再将其分配给向量。

我所拥有的:

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

我也尝试了映射as in this answer,但这也不起作用( EDIT:我认为这是由于存储顺序,但实际上是由于偏移量不正确,请参见我的答案):

// 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]);

真的会很难吗,还是我缺少简单的东西?感谢您的所有帮助!

1 个答案:

答案 0 :(得分:0)

回答了我自己的问题:是的,我缺少一些简单的东西。通过比较我从Map操作中得到的数字,我意识到偏移量是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;