wumo
wumo

Reputation: 137

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?

Upvotes: 6

Views: 8481

Answers (3)

atif93
atif93

Reputation: 401

Looking at tensor_shape.h, it looks like tensor.shape().dim_sizes() should give you a vector containing the shape.

Upvotes: 0

gebbissimo
gebbissimo

Reputation: 2679

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.

Upvotes: 9

wdudzik
wdudzik

Reputation: 1344

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

Upvotes: 3

Related Questions