问题
I get some Eigen::TensorMap from the outputs vector from a tensorflow session in C++. I want to do some operations to the Eigen::TensorMap (reshape and concat etc.).
However, my codes cannot be compiled due to some weird error. I tried to reproduce it in pure Eigen3 code.
#include <unsupported/Eigen/CXX11/Tensor>
using Eigen::Tensor;
using Eigen::TensorMap;
using Eigen::TensorRef;
using std::vector;
int main() {
int storage[128];
TensorMap<Tensor<int, 4>> t_4d(storage, 2, 4, 2, 8);
vector<TensorRef<Tensor<int,2>>> reshapedTensors;
std::array<int, 2> shape{ 16,8 };
auto re_op = t_4d.reshape(shape);
reshapedTensors.push_back(re_op);
return 0;
}
According to the Eigen Doc, the return type of reshape function is an eigen operation, it will be caculate lazily. The TensorRef is the wrapper of all tensor operations.
This piece of codes will complain that:
Severity Code Description Project File Line Suppression State Error C2679 binary '=': no operator found which takes a right-hand operand of type 'const std::array' (or there is no acceptable conversion) testEigen D:\Programming\cpp library\eigen-eigen-323c052e1731\unsupported\Eigen\CXX11\src\Tensor\TensorRef.h 49
回答1:
You can't mix different IndexType
for Tensor operations (that is the implicit 4th template parameter of Tensor
). This also means the type of the std::array
must match the IndexType
. By default, Eigen::Tensor
uses Eigen::DenseIndex
which is the same as Eigen::Index
. You can either write this instead of Eigen::Tensor<int,4>
(similar for Tensor<int,2>
)
Eigen::Tensor<int, 4, 0, int>
or you replace std::array<int, 2>
by std::array<Eigen::Index, 2>
.
Of course making typedef
s for both will safe you some typing and will simplify refactoring, if you ever need to do that.
来源:https://stackoverflow.com/questions/56985731/how-to-reshape-a-tensor-in-eigen3