public async Task <IActionResult> Image(HomeImageModel homeIndexModel) { if (homeIndexModel.FileUpload?.Length > 0 && homeIndexModel.FileUpload.Length < 1024000 && ((Path.GetExtension(homeIndexModel.FileUpload.FileName).ToLower() == ".jpg") || (Path.GetExtension(homeIndexModel.FileUpload.FileName).ToLower() == ".png"))) { var filePath = $"{hostingEnvironment.WebRootPath}\\uploads\\{homeIndexModel.FileUpload.FileName}"; var saveFilePath = Utility.IdentityFileName(filePath); using (var stream = new FileStream(saveFilePath, FileMode.Create)) { await homeIndexModel.FileUpload.CopyToAsync(stream); } ImageData imageToPredict = new ImageData { ImagePath = saveFilePath }; var perdictionResult = mLImageEngine.Predict(imageToPredict); var index = perdictionResult.PredictedLabel; homeIndexModel.Name = GetDiseasesNameForImageClassification(mLImageEngine.GetOriginalLabel(index)); homeIndexModel.PerdictionPercentage = Utility.CalculatePercentage(perdictionResult.Score[index]); } else { ModelState.AddModelError("FileUpload", "Dữ Liệu không hợp lệ."); } return(View(homeIndexModel)); }
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; }
private bool OnGetPredictSentiment(string SentimentText) { SentimentData sampleData = new SentimentData() { SentimentText = SentimentText }; SentimentPrediction prediction = _modelEngine.Predict(sampleData); return(prediction.Prediction); }
public IActionResult Index(HomeIndexModel homeIndexModel) { if (ModelState.IsValid) { var diseasesTraining = new DiseasesSymptomTraining() { Syptom = homeIndexModel.Syptom }; var perdictionResult = mLSymptomEngine.Predict(diseasesTraining); homeIndexModel.Name = perdictionResult.Name; homeIndexModel.PerdictionPercentage = Utility.CalculatePercentage(perdictionResult.Score.Max()); } return(View(homeIndexModel)); }
// (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($"=================================================="); }
public ActionResult <string> PredictSentiment([FromQuery] string sentimentText) { SampleObservation sampleData = new SampleObservation() { SentimentText = sentimentText }; //Predict sentiment SamplePrediction prediction = _modelEngine.Predict(sampleData); bool isToxic = prediction.IsToxic; float probability = CalculatePercentage(prediction.Score); string retVal = $"Prediction: Is Toxic?: '{isToxic.ToString()}' with {probability.ToString()}% probability of toxicity for the text '{sentimentText}'"; return(retVal); }
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(); }
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); } }