migueldeicaza / TensorFlowSharp

TensorFlow API for .NET languages
MIT License
3.14k stars 577 forks source link

tensorflowsharp load model(pb file) and predict, the results are always same #489

Closed zhimakaimen225xa closed 3 years ago

zhimakaimen225xa commented 4 years ago

Describe the bug

I trained a cnn model with keras and saved the model to h5 file, then I convert the h5 file to pb file. I opened my_model.pb file in python and predicted test data, it works ok. But when I try to load the pb file in c# (i use tensorflowsharp), the results from model prediction are always same, the probability for output are always 0.252, 0.385, 0.361, my code is as follows,

To Reproduce Include steps to reproduce the issue locally, include it as a zip file.

    public int[] Predict(string symbol, int beginIndex = 0, int endIndex = -1)
    {
        var modelfile = @"L:\\下载20200701\\Using-Deep-Learning-Neural-Networks-and-Candlestick-Chart-Representation-to-Predict-Stock-Market-master\\some_directory\\my_model.pb";//Produced by training
        byte[] buffer = System.IO.File.ReadAllBytes(modelfile);
        using (var graph = new TensorFlow.TFGraph())
        {
            graph.Import(buffer);
            using (var session = new TensorFlow.TFSession(graph))
            {
                var runner = session.GetRunner();
                //var tensor = Utils.ImageToTensorGrayScale(file);
                var tensor = dataTransfer.OutputTensor(symbol, beginIndex, endIndex);
                runner.AddInput(graph["input_1"][0], tensor);
                runner.Fetch(graph["dense_2/Softmax"][0]);

                var output = runner.Run();
                var vecResults = output[0].GetValue();
                float[,] results = (float[,])vecResults;
                int[] resultArr = ArgMax((float[,])results);

                return resultArr;
            }
        }
    }

Note: I do not have time to create models, train models, create samples from scratch and then adding your 3-4 lines of code to a sample to debug your problem. You need to provide a complete test case.

Expected behavior A clear and concise description of what you expected to happen.

Screenshots If applicable, add screenshots to help explain your problem.

Desktop (please complete the following information):

Smartphone (please complete the following information):

Additional context Add any other context about the problem here.

zhimakaimenxa commented 3 years ago

I've found the reason, the sensor created by my function:dataTransfer.OutputTensor, can only contain one sample a time, so the shape of sensor should look like:[1, channels, height, width], so I need to close this issue and open a new one.