将 Eigen::TensorMap 转换为 Eigen::Tensor

4

通过赋值可以将 Eigen::Map 转换为 Matrix

vector<float> v = { 1, 2, 3, 4 };
auto m_map = Eigen::Map<Eigen::Matrix<float, 2, 2, Eigen::RowMajor>>(&v[0]);
Eigen::MatrixXf m = m_map;
cout << m << endl;

这将产生以下结果:
 1 2
 3 4

如果我试图使用Tensor做类似的事情:

vector<float> v = { 1, 2, 3, 4 };
auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2);
Eigen::Tensor<float, 2> t = mapped_t;

我只是得到编译器错误 YOU_MADE_A_PROGRAMMING_MISTAKE。有没有办法将TensorMap转换为Tensor?

1个回答

7

好的,Eigen::RowMajor 不是 Eigen::Tensor 的默认设置,这意味着您没有将其分配给相同类型,这意味着 你犯了一个编程错误。您必须明确地请求交换布局。

#include <vector>
#include <unsupported/Eigen/CXX11/Tensor>

int main()
{
  std::vector<float> v = { 1, 2, 3, 4 };
  auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2);
  Eigen::Tensor<float, 2> t = Eigen::TensorLayoutSwapOp<Eigen::Tensor<float, 2, Eigen::RowMajor>>(mapped_t);
}

使用C++14,你可以编写一个漂亮的实例化函数来完成这个任务。
#include <type_traits>
#include <vector>
#include <unsupported/Eigen/CXX11/Tensor>

namespace Eigen {
  template < typename T >
  decltype(auto) TensorLayoutSwap(T&& t)
  {
    return Eigen::TensorLayoutSwapOp<typename std::remove_reference<T>::type>(t);
  }
}

int main()
{
  std::vector<float> v = { 1, 2, 3, 4 };
  auto mapped_t = Eigen::TensorMap<Eigen::Tensor<float, 2, Eigen::RowMajor>>(&v[0], 2, 2);
  Eigen::Tensor<float, 2> t = Eigen::TensorLayoutSwap(mapped_t);
}

我遇到了这样的错误:无法重载 static Eigen::PlainObjectBase<Derived>::MapType Eigen::PlainObjectBase<Derived>::Map(Eigen::PlainObjectBase<Derived>::Scalar*) [with Derived = Eigen::Matrix<const float, -1, -1, 0, -1, -1>; Eigen::PlainObjectBase<Derived>::MapType = Eigen::Map<Eigen::Matrix<const float, -1, -1, 0, -1, -1>, 0, Eigen::Stride<0, 0> >; Eigen::PlainObjectBase<Derived>::Scalar = const float]'。 - John Jiang

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接