Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

tensorflow

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?

like image 277
wumo Avatar asked Dec 23 '22 06:12

wumo


2 Answers

Here is a small function which returns the shape as a vector, e.g. {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.

like image 79
gebbissimo Avatar answered Dec 28 '22 06:12

gebbissimo


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 :)

like image 25
wdudzik Avatar answered Dec 28 '22 08:12

wdudzik