如何将 2D Eigen::Tensor 更改为 Eigen::Matrix [英] how to change 2D Eigen::Tensor to Eigen::Matrix
问题描述
看起来很简单.我原以为可以进行某种类型的转换,但我似乎找不到任何相关文档.
Seems simple enough. I would have thought some kind of casting would be possible, but I can't seem to find any documentation for it.
虽然我在我的应用程序中找到了避免使用 Eigen::Matrix 类的方法,但 TensorFlow 仅适用于 Eigen::Tensor,而我使用的另一个库仅具有直接使用 Eigen::Matrix 的功能.如果我可以将张量转换为矩阵并使用它,那么代码可读性将非常棒.
While I have found ways in my application to avoid using the Eigen::Matrix class, TensorFlow only works with Eigen::Tensor, and another library I use only has functionality for working directly with Eigen::Matrix. It would be spectacular for code readability if I could cast a Tensor as a Matrix and work with that.
似乎 TensorFlow 确实有一个功能可以输出 Eigen::Matrix(仍在测试中).也许这让最初的问题变得不那么有趣(也许没有人需要将张量转换为矩阵.)但是我仍然认为这是一个有效的问题.所以我不会放下我的
编辑 2:在一些构建错误后查看 TF 文档,似乎 tensorflow 的 Tensor::matrix() 函数只是返回一个 2d Eigen::Tensor,因此实际上需要进行转换.
edit 2: going through the TF documentation after some build errors, it seems that tensorflow's Tensor::matrix() function simply returns a 2d Eigen::Tensor, so the conversion is in fact necessary.
推荐答案
这是 TensorFlow 线性代数运算的常见用例,可以在 tensorflow/core/kernels.comcode>al
但是,该代码高度模板化,因此提供一个具体示例可能会很有用.
This is a common use case for TensorFlow's linear algebra ops, and an implementation can be found in tensorflow/core/kernels/linalg_ops_common.cc
. However, that code is highly templatized, so it might be useful to have a concrete example.
假设您从一个名为 t
且元素类型为 float
的 tensorflow::Tensor
开始,您可以创建一个特征矩阵 m
如下:
Assuming you start with a tensorflow::Tensor
called t
with element type float
, you can make an Eigen matrix m
as follows:
tensorflow::Tensor t = ...;
auto m = Eigen::Map<Eigen::Matrix<
float, /* scalar element type */
Eigen::Dynamic, /* num_rows is a run-time value */
Eigen::Dynamic, /* num_cols is a run-time value */
Eigen::RowMajor /* tensorflow::Tensor is always row-major */>>(
t.flat<float>().data(), /* ptr to data */
t.dim_size(0), /* num_rows */
t.dim_size(1) /* num_cols */);
如果您的张量来自 tensorflow::OpKernel
的输入(例如在 Compute()
方法中),您将使用稍微不同的类型和适当的const
限定:
If your tensor comes from the input of a tensorflow::OpKernel
(e.g. in the Compute()
method), you would use a slightly different type with the appropriate const
qualification:
OpKernelContext* ctx = ...;
const tensorflow::Tensor t = ctx->input(...);
const auto m = Eigen::Map<const Eigen::Matrix<
float, /* scalar element type */
Eigen::Dynamic, /* num_rows is a run-time value */
Eigen::Dynamic, /* num_cols is a run-time value */
Eigen::RowMajor /* tensorflow::Tensor is always row-major */>>(
t.flat<float>().data(), /* ptr to data */
t.dim_size(0), /* num_rows */
t.dim_size(1) /* num_cols */);
这篇关于如何将 2D Eigen::Tensor 更改为 Eigen::Matrix的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!