6

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?

wumo
  • 107
  • 1
  • 8

3 Answers3

9

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.

gebbissimo
  • 2,137
  • 2
  • 25
  • 35
3

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

wdudzik
  • 1,264
  • 15
  • 24
  • 1
    `tensor` only returns after session runs. If you need to get the tensor shape before running the session, you can use TF_GraphGetTensorShape in C api. I just don't know how to do this in C++ API. Something related is inferring the output tensor shape of some operation, which is either not provided by C++ API or I haven't found.. – wumo Jul 06 '18 at 10:25
  • Sorry but I don't know the full context of your question, so I cannot really help you. As I understand you want to know dimensions of some Tensor, so you should have object of this class. Maybe you can add some example of code to your question – wdudzik Jul 06 '18 at 10:49
0

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

atif93
  • 401
  • 4
  • 8