簡體   English   中英

我應該如何從特征3中的張量切片中獲得向量?

[英]How should I get a Vector from a Tensor slice in Eigen 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]);

真的應該這么難,還是我錯過了一些簡單的事情? 感謝您提供的所有幫助!

回答了我自己的問題:是的,我缺少一些簡單的東西。 通過比較我從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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM