how to change 2D Eigen::Tensor to Eigen::Matrix

前端 未结 1 979
遥遥无期
遥遥无期 2020-12-31 20:34

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

相关标签:
1条回答
  • 2020-12-31 21:05

    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 */);
    
    0 讨论(0)
提交回复
热议问题