Beispiel #1
0
        private void Form1_Load(object sender, EventArgs e)
        {
            var imgRepo = new ScreenRepository(Image.FromFile("screenshot.png"));
            //var img = imgRepo.GetPart(PartScreenType.ManaPool).Source;
            var img = imgRepo.Source;

            var solutionDirectory = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../"));

            var workspaceRelativePath = Path.Combine(solutionDirectory, "workspace");
            var modelRelativePath     = Path.Combine(workspaceRelativePath, "model.zip");

            var mlEngine = new MLModelEngine <ModelInput, ModelOutput>(modelRelativePath);

            //取得 label list, 對應 score 順序
            //var labels = mlEngine.RetriveLabels();
            foreach (var part in imgRepo.Parts)
            {
                ModelInput inputData = new ModelInput();
                using (var ms = new MemoryStream())
                {
                    part.Source.Save(ms, img.RawFormat);
                    inputData.Image = ms.ToArray();
                }
                ModelOutput prediction = mlEngine.Predict(inputData);
                //var index = Array.IndexOf(labels, prediction.PredictedLabel);
                //var score = prediction.Score[index];
                img.TagImage(part.Location, prediction);
            }

            pictureBox1.Image = img;
        }
Beispiel #2
0
        private void InitializeML()
        {
            var solutionDirectory     = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../"));
            var workspaceRelativePath = Path.Combine(solutionDirectory, "workspace");
            var modelRelativePath     = Path.Combine(workspaceRelativePath, "model.zip");

            MLEngine = new MLModelEngine <ModelInput, ModelOutput>(modelRelativePath);
        }
Beispiel #3
0
        public ProductDemandForecastController(IOptionsSnapshot <AppSettings> appSettings,
                                               MLModelEngine <ProductData, ProductUnitPrediction> productSalesModel)
        {
            this.appSettings = appSettings.Value;

            // Get injected Product Sales Model for scoring
            this.productSalesModel = productSalesModel;
        }
 public HomeController(
     IHostingEnvironment _hostingEnvironment,
     MLModelEngine <ImageData, ImagePrediction> _mLImageEngine,
     MLModelEngine <DiseasesSymptomTraining, DiseasesSymptomPerdiction> _mLSymptomEngine)
 {
     mLSymptomEngine    = _mLSymptomEngine;
     mLImageEngine      = _mLImageEngine;
     hostingEnvironment = _hostingEnvironment;
 }
Beispiel #5
0
        public CountrySalesForecastController(IOptionsSnapshot <AppSettings> appSettings,
                                              MLModelEngine <CountryData, CountrySalesPrediction> countrySalesModel,
                                              ILogger <CountrySalesForecastController> logger)
        {
            this.appSettings = appSettings.Value;

            // Get injected Country Sales Model for scoring
            this.countrySalesModel = countrySalesModel;

            this.logger = logger;
        }
Beispiel #6
0
        // (OPTIONAL) Try/test a single prediction with the trained model and any test data
        private static void TrySinglePrediction(MLContext mlContext, ITransformer model, IDataView dataView)
        {
            // Load data to test. Could be any test data. Since this is generated code, a row from a dataView is used
            // But here you can try wit any sample data to make a prediction
            var sample = mlContext.Data.CreateEnumerable <SampleObservation>(dataView, false).First();

            //Create ModelScorer with current available model/transformer and mlContext
            var mlModel = new MLModelEngine <SampleObservation, SamplePrediction>(model, mlContext);
            // Predict
            var resultprediction = mlModel.Predict(sample);

            Console.WriteLine($"=============== Single Prediction  ===============");
            Console.WriteLine($"Actual value: {sample.Fare_amount} | Predicted value: {resultprediction.Score}");
            Console.WriteLine($"==================================================");
        }
Beispiel #7
0
 public EditModel(GadgetCMS.Data.ApplicationDbContext context, UserManager <GadgetCMSUser> userManager, MLModelEngine <SentimentData, SentimentPrediction> modelEngine)
 {
     _userManager = userManager;
     _context     = context;
     _modelEngine = modelEngine;
 }
        static void Main(string[] args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();

            // Create an opportunity for the user to cancel.
            Task.Run(() =>
            {
                if (Console.ReadKey().KeyChar == 'c' || Console.ReadKey().KeyChar == 'C')
                {
                    cts.Cancel();
                }
            });

            MLContext mlContext         = new MLContext(seed: 1);
            string    modelFolder       = $"Forecast/ModelFiles";
            string    modelFilePathName = $"ModelFiles/country_month_fastTreeTweedie.zip";
            var       countrySalesModel = new MLModelEngine <CountryData, CountrySalesPrediction>(mlContext,
                                                                                                  modelFilePathName,
                                                                                                  minPredictionEngineObjectsInPool: 50,
                                                                                                  maxPredictionEngineObjectsInPool: 2000,
                                                                                                  expirationTime: 30000);

            Console.WriteLine("Current number of objects in pool: {0:####.####}", countrySalesModel.CurrentPredictionEnginePoolSize);

            //Single Prediction
            var singleCountrySample       = new CountryData("Australia", 2017, 1, 477, 164, 2486, 9, 10345, 281, 1029);
            var singleNextMonthPrediction = countrySalesModel.Predict(singleCountrySample);

            Console.WriteLine("Prediction: {0:####.####}", singleNextMonthPrediction.Score);

            // Create a high demand for the modelEngine objects.
            Parallel.For(0, 1000000, (i, loopState) =>
            {
                //Sample country data
                //next,country,year,month,max,min,std,count,sales,med,prev
                //4.23056080166201,Australia,2017,1,477.34,164.916,2486.1346772137,9,10345.71,281.7,1029.11

                var countrySample = new CountryData("Australia", 2017, 1, 477, 164, 2486, 9, 10345, 281, i);

                // This is the bottleneck in our application. All threads in this loop
                // must serialize their access to the static Console class.
                Console.CursorLeft      = 0;
                var nextMonthPrediction = countrySalesModel.Predict(countrySample);

                //(Wait for a 1/10 second)
                //System.Threading.Thread.Sleep(1000);

                Console.WriteLine("Prediction: {0:####.####}", nextMonthPrediction.Score);
                Console.WriteLine("-----------------------------------------");
                Console.WriteLine("Current number of objects in pool: {0:####.####}", countrySalesModel.CurrentPredictionEnginePoolSize);

                if (cts.Token.IsCancellationRequested)
                {
                    loopState.Stop();
                }
            });

            Console.WriteLine("-----------------------------------------");
            Console.WriteLine("Current number of objects in pool: {0:####.####}", countrySalesModel.CurrentPredictionEnginePoolSize);


            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            cts.Dispose();
        }
Beispiel #9
0
        public static void PredictionImage(this MLModelEngine <ModelInput, ModelOutput> mlEngine,
                                           Image img)
        {
            var solutionDirectory     = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "../../../../"));
            var assetsRelativePath    = Path.Combine(solutionDirectory, "assets");
            var undefinedRelativePath = Path.Combine(assetsRelativePath, "undefined");

            BlockingCollection <dynamic> predictions = new BlockingCollection <dynamic>();
            var imgRawFormat = img.RawFormat;

            var imgRepo        = new ScreenRepository(img);
            var prefixFileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");

            System.Threading.Tasks.Parallel.ForEach(imgRepo.Parts, part =>
            {
                ModelInput inputData = new ModelInput();
                using (var ms = new MemoryStream())
                {
                    part.Source.Save(ms, imgRawFormat);
                    inputData.Image = ms.ToArray();
                }
                ModelOutput prediction = mlEngine.Predict(inputData);
                predictions.Add(new
                {
                    PartImg    = part,
                    Prediction = prediction,
                });
                var isPredictFail = false;
                if (part.PartType == PartScreenType.LifePool && !prediction.PredictedLabel.StartsWith("HP"))
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.ManaPool && !prediction.PredictedLabel.StartsWith("MP"))
                {
                    isPredictFail = true;
                }
                else if (prediction.PredictedLabel.StartsWith("HP") && part.PartType != PartScreenType.LifePool)
                {
                    isPredictFail = true;
                }
                else if (prediction.PredictedLabel.StartsWith("MP") && part.PartType != PartScreenType.ManaPool)
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.FlaskSlot1 && !prediction.PredictedLabel.StartsWith("LF") &&
                         !prediction.PredictedLabel.StartsWith("EF"))
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.FlaskSlot2 && !prediction.PredictedLabel.StartsWith("MF") &&
                         !prediction.PredictedLabel.StartsWith("EF"))
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.FlaskSlot3 && !prediction.PredictedLabel.StartsWith("MF") &&
                         !prediction.PredictedLabel.StartsWith("EF"))
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.FlaskSlot4 && !prediction.PredictedLabel.StartsWith("MF") &&
                         !prediction.PredictedLabel.StartsWith("EF"))
                {
                    isPredictFail = true;
                }
                else if (part.PartType == PartScreenType.FlaskSlot5 && !prediction.PredictedLabel.StartsWith("MF") &&
                         !prediction.PredictedLabel.StartsWith("EF"))
                {
                    isPredictFail = true;
                }

                if (isPredictFail || prediction.MaxScore < 0.5)
                {
                    if (!UndefinedImageAllowSaveDate.HasValue || DateTime.Now > UndefinedImageAllowSaveDate.Value)
                    {
                        UndefinedImageAllowSaveDate = DateTime.Now.AddMinutes(1);
                        var filePath = Path.Combine(undefinedRelativePath, $"{prefixFileName}_{part.PartType}.png");
                        part.Source.Save(filePath);
                    }
                }
            });

            foreach (var d in predictions)
            {
                PartScreen  part       = d.PartImg;
                ModelOutput prediction = d.Prediction;
                img.TagImage(part.Location, prediction);
            }
        }
 public PredictorController(MLModelEngine <SampleObservation, SamplePrediction> modelEngine)
 {
     // Get the ML Model Engine injected, for scoring
     _modelEngine = modelEngine;
 }