コード例 #1
0
        private Sequential FitAndEvaluate(Sequential newModel, string bestWeightsFile)
        {
            int imgHeight    = 75;
            int trainSamples = 31980;
            int testSamples  = 4420;
            int epochs       = 20;
            int batchSize    = 26;

            string trainDirectory      = "E:\\Projects\\MLProject1\\MLProject1\\bin\\Debug\\data\\Train";
            string testDirectory       = "E:\\Projects\\MLProject1\\MLProject1\\bin\\Debug\\data\\Test";
            string validationDirectory = "E:\\Projects\\MLProject1\\MLProject1\\bin\\Debug\\data\\Valid";

            ImageDataGenerator generator = new ImageDataGenerator(rescale: (float)(1.00 / 255.00));

            //load and iterate training dataset
            KerasIterator trainIterator = generator.FlowFromDirectory(trainDirectory,
                                                                      class_mode: "categorical",
                                                                      target_size: new Tuple <int, int>(imgHeight, imgHeight),
                                                                      batch_size: batchSize);
            //color_mode:"grayscale");

            // load and iterate testing dataset
            KerasIterator testIterator = generator.FlowFromDirectory(testDirectory,
                                                                     class_mode: "categorical",
                                                                     target_size: new Tuple <int, int>(imgHeight, imgHeight),
                                                                     batch_size: batchSize);
            //color_mode: "grayscale");

            KerasIterator validationIterator = generator.FlowFromDirectory(validationDirectory,
                                                                           class_mode: "categorical",
                                                                           target_size: new Tuple <int, int>(imgHeight, imgHeight),
                                                                           batch_size: batchSize);

            ModelCheckpoint checkpoint = new ModelCheckpoint(filepath: bestWeightsFile,
                                                             monitor: "val_accuracy",
                                                             verbose: 1,
                                                             save_best_only: true);

            newModel.FitGenerator(trainIterator, steps_per_epoch: trainSamples / batchSize, epochs: epochs, verbose: 1,
                                  validation_data: validationIterator, callbacks: new Callback[] { checkpoint });

            //evaluate model
            double[] loss = newModel.EvaluateGenerator(testIterator, steps: testSamples / batchSize);

            foreach (double d in loss)
            {
                Console.Write(d + " ");
            }

            return(newModel);
        }