0

I created a very simple model and saved it to disk, and when I load the model and run the evaluate function I get an error.

This is the code that creates the model and loads it:

using System;
using static Tensorflow.Binding;
using static Tensorflow.KerasApi;
using Tensorflow;
using Tensorflow.NumPy;
using System.Xml.Linq;
using Tensorflow.Keras;
using System.Collections.Generic;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var x_train = np.array(new float[,] { { 0.1f }, { 0.2f }, { 0.3f }, { 0.4f } });
            var y_train = np.array(0, 1, 2, 3);

            var x_test = x_train;
            var y_test = y_train;

            CreateModel("model.h5", x_train, y_train, x_test, y_test);

            var model = keras.models.load_model("model.h5");
            model.summary();
            print("evaluate: ", model.evaluate(x_test, y_test, verbose: 2)); // <= ERROR!

            Console.ReadLine();
        }

        private static void CreateModel(string fileNmae, NDArray x_train, NDArray y_train, NDArray x_test, NDArray y_test)
        {       
            var model = keras.Sequential(new List<ILayer>() {
                tf.keras.layers.Dense(128, activation: "relu"),
                tf.keras.layers.Dense(4)
            });

            var loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits: true);

            model.compile(optimizer: new Tensorflow.Keras.Optimizers.Adam(),
                loss: loss_fn,
                metrics: new[] { "accuracy" });

            model.fit(x_train, y_train, epochs: 30, verbose: 3, use_multiprocessing: true);

            print("evaluate: ", model.evaluate(x_test, y_test, verbose: 2));

            var probability_model = keras.Sequential(new List<ILayer>() {
                model,
                tf.keras.layers.Softmax()
            });

            print("predict: ", probability_model.predict(x_test));

            model.save(fileNmae);
        }
    }
}

This is the error:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

   at Tensorflow.Keras.Engine.Model.test_step(DataHandler data_handler, Tensor x, Tensor y)
   at Tensorflow.Keras.Engine.Model.test_function(DataHandler data_handler, OwnedIterator iterator)
   at Tensorflow.Keras.Engine.Model.evaluate(NDArray x, NDArray y, Int32 batch_size, Int32 verbose, Int32 steps, Int32 max_queue_size, Int32 workers, Boolean use_multiprocessing, Boolean return_dict, Boolean is_val)
   at ConsoleApp1.Program.Main(String[] args) in F:\programming\py-tensorflow\ConsoleApp1\ConsoleApp1\Program.cs:line 32

What's wrong with my code?

codeDom
  • 1,623
  • 18
  • 54

0 Answers0