【问题标题】:Tensorflow C++ API: How to iterate Tensor with Dimesion=3?Tensorflow C++ API:如何使用 Dimesion=3 迭代张量?
【发布时间】:2018-04-16 03:45:50
【问题描述】:

我有一个来自输入的 shape(2,2,3) 张量。我可以通过.shape() 得到这个张量的形状,它可以用来帮助迭代。但是我无法迭代它,这可能是由于错误转换为矩阵而导致的,而矩阵的维度总是 2 代码如下所示:

const Tensor& input = context->input(0); // get the input
DCHECK_EQ(input.dims(), 3); //check the dimission==3
const TensorShape& input_shape = input.shape(); //get the shape of the tensor
auto input_tensor = input.matrix<float>();//wrong conversion
for(int i=0; i<input_shape.dim_size(0); i++)
{
  for(int j=0; j<input_shape.dim_size(1); j++)
  {
    for(int k=0; k<input_shape.dim_size(2); k++)
      {
        count<<input_tensor(i,j,k);//wrong code
      }
  }
}

所以,我想知道迭代这个张量的方法。非常感谢!

【问题讨论】:

    标签: c++ tensorflow tensor


    【解决方案1】:

    当我比较Tensorflow.org中的矩阵api和张量api时,很惊讶我得到了答案。并找到用法:

    const Tensor& input = context->input(0); // get the input
    DCHECK_EQ(input.dims(), 3); //check the dimission==3
    const TensorShape& input_shape = input.shape(); //get the shape of the tensor
    auto input_tensor = input.tensor<float, 3>();//true conversion
    for(int i=0; i<input_shape.dim_size(0); i++)
    {
        for(int j=0; j<input_shape.dim_size(1); j++)
        {
            for(int k=0; k<input_shape.dim_size(2); k++)
            {
               count<<input_tensor(i,j,k);//right one
            }
        }
    }
    

    也许在我错过 NDImission 参数之前。

    【讨论】:

    • 这段代码和你问题中的代码有什么区别?
    • 谢谢!我复制之前的代码。不同的是 input_tensor 的初始化遵循 api "TTypes::Tensor tensor()"。最后一个是二维张量的初始化遵循api“TTypes::Matrix matrix()”。
    • 是的,TTypes 是迭代 3 张量的正确方法。您也可以始终使用 .flat()(n)
    猜你喜欢
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 2018-09-04
    • 2018-11-11
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 2018-08-02
    相关资源
    最近更新 更多