コード例 #1
0
        public void TrainXOR()
        {
            try {
                //Load train data
                float[,] testX = new float[, ] {
                    { 0, 1 },
                };
                float[,] x = new float[, ] {
                    { 0, 0 }, { 0, 1 }, { 1, 0 }, { 1, 1 }
                };
                float[] y = new float[] { 0, 1, 1, 0 };

                //Build sequential model
                var model = new Sequential();
                model.Add(new Dense(32, activation: "relu", input_shape: new Shape(2)));
                model.Add(new Dense(32, activation: "relu"));
                model.Add(new Dropout(0.1d));
                model.Add(new Dense(1, activation: "sigmoid"));

                //Compile and train
                var optimizer = new Adam();
                model.Compile(optimizer: optimizer, loss: "mse", metrics: new string[] { "accuracy" });
                model.Fit(x, y, batch_size: 2, epochs: 1000, verbose: 1);

                float[] predicts;
                predicts = model.Predict(x).GetData <float>();
                predicts = model.PredictOnBatch(x).GetData <float>();
                predicts = model.Predict(x).GetData <float>();
                predicts = model.PredictOnBatch(x).GetData <float>();
                predicts = model.Predict(x).GetData <float>();
                predicts = model.PredictOnBatch(x).GetData <float>();

                Stopwatch watch = new Stopwatch();
                watch.Restart();
                for (int i = 0; i < 5; ++i)
                {
                    predicts = model.PredictOnBatch(testX).GetData <float>();
                }
                watch.Stop();
                string batchMs = watch.GetElapsedMilliseconds().ToString();
                watch.Restart();
                for (int i = 0; i < 5; ++i)
                {
                    predicts = model.Predict(testX).GetData <float>();
                }
                watch.Stop();

                //MainWindow.Instance.Dispatcher.BeginInvoke(new Action(() => {
                //	MainWindow.Instance.DebugTextBox.Text = batchMs + " / " + watch.GetElapsedMilliseconds().ToString();
                //}));
            } catch (Exception ex) {
                //MainWindow.Instance.Dispatcher.BeginInvoke(new Action(() => {
                //	MainWindow.Instance.DebugTextBox.Text = ex.ToString();
                //}));
            }
        }