c++tensorflowdeep-learningc-api

Reshaping Tensor in C


How can I reshape TF_Tensor* using Tensorflow's C_api as it's being done in C++?

TensorShape inputShape({1,1,80,80});

Tensor inputTensor;
Tensor newTensor;

bool result = inputTensor->CopyFrom(newTensor, inputShape);

I don't see a similar method using the tensorflow's c_api.


Solution

  • Tensorflow C API operates with a (data,dims) model - treating data as a flat raw array supplied with the needed dimensions.

    Step 1: Allocating a new Tensor

    Have a look at TF_AllocateTensor(ref):

    TF_CAPI_EXPORT extern TF_Tensor* TF_AllocateTensor(TF_DataType,
                                                       const int64_t* dims,
                                                       int num_dims, size_t len);
    

    Here:

    1. TF_DataType: The TF equivalent of the data type you need from here.
    2. dims: Array corresponding to dimensions of tensor to be allocated eg. {1, 1, 80, 80}
    3. num_dims: length of dims(4 above)
    4. len: reduce(dims, *): i.e. 1*1*80*80*sizeof(DataType) = 6400*sizeof(DataType).

    Step 2: Copying data

    // Get the tensor buffer
    auto buff = (DataType *)TF_TensorData(output_of_tf_allocate);
    // std::memcpy() ...
    

    Here is some sample code from a project I did a while back on writing a very light Tensorflow C-API Wrapper.

    So, essentially your reshape will involve allocating your new tensor and copying the data from the original tensor into buff.

    The Tensorflow C API isnt meant for regular usage and thus is harder to learn + lacking documentation. I figured a lot of this out with experimentation. Any suggestions from the more experienced developers out there?