Search code examples
c#tensorflowtensorflowsharp

How to reshape a tensor in TensorFlowSharp


TensorFlowSharp is the wrapper of TensorFlow in c# platform. click it to jump to TensorFlowSharp github

Now i need to reshape a tensor with shape [32,64,1] into a new tensor with shape [1, 2048].But as i refer to the official API document, the usage seems like that:

TFOutput Reshape (TensorFlow.TFOutput tensor, TensorFlow.TFOutput shape);

the problem is that i dont know how to express the shape i need in the way of TFOutput Any suggestions will be appreciated:)!


Solution

  • In standard TensorFlowSharp, an example on how to do this operation can be given by:

    tf.Reshape(x, tf.Const(shape));
    

    where tf is the current default TFGraph in your TFSession.

    Alternatively, if you use Keras Sharp, you might be able to do this operation using

    using (var K = new TensorFlowBackend())
    {
        double[,] input_array = new double[,] { { 1, 2 }, { 3, 4 } };
        Tensor variable = K.variable(array: input_array);
        Tensor variable_new_shape = K.reshape(variable, new int[] { 1, 4 });
        double[,] output = (double[,])variable_new_shape.eval();
    
        Assert.AreEqual(new double[,] { { 1, 2, 3, 4 } }, output);
    }
    

    as indicated in https://github.com/cesarsouza/keras-sharp/blob/efac7e34457ffb7cf6712793d5298b565549a1c2/Tests/TensorFlowBackendTest.cs#L45