简体   繁体   中英

Tensorflow c++: how to get the tensor shape of an `Output?`

There's TF_GraphGetTensorShape in C API, but the interface isn't compatible with C++ Graph and Output . How to do the same using tensorflow C/C++ API?

For example. How to get the returned tensor shape of Slice operation using C++ API and then using that tensor shape to make a variable with the same shape?

Here is a small function which returns the shape as a vector, eg {48,48,2}

std::vector<int> get_tensor_shape(tensorflow::Tensor& tensor)
{
    std::vector<int> shape;
    int num_dimensions = tensor.shape().dims()
    for(int ii_dim=0; ii_dim<num_dimensions; ii_dim++) {
        shape.push_back(tensor.shape().dim_size(ii_dim));
    }
    return shape;
}

Apart from that I found tensor.DebugString() helpful, which yields for example "Tensor type: float shape: [48,48,2] values: [[0,0390625 -1][0,0390625]]...>"

For python see this thread: https://stackoverflow.com/a/40666375/2135504 , where tensor.get_shape().as_list() is recommended.

I have never used tensorflow C API but in C++ API you have class Tensor which have function shape() . It will return const TensorShape& , which has function dim_size(int index) . This function will return dimension for given index value. Hope this helps you :)

查看tensor_shape.h ,看起来tensor.shape().dim_sizes()应该给你一个包含形状的向量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM