问题
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.
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.
edit: it seems that TensorFlow DOES have a function to get an Eigen::Matrix out (still testing it out). Maybe that makes the original question less interesting (maybe no one NEEDS to convert Tensors to Matrices.) However I still think it's a valid question to ask. so I won't put down my
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.
回答1:
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.
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 */);
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 */);
来源:https://stackoverflow.com/questions/39475356/how-to-change-2d-eigentensor-to-eigenmatrix