MLHelper.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. using DTHelperStd.DataStructures;
  5. using Microsoft.ML;
  6. using Microsoft.ML.Core.Data;
  7. using System.IO;
  8. using System.Text;
  9. namespace DTHelperStd
  10. {
  11. public class MLHelper
  12. {
  13. public static PredictionEngine<Data, DataPrediction> CityPredictionEngine { get; private set; }
  14. public static PredictionEngine<Data, DataPrediction> FirstNamePredictionEngine { get; private set; }
  15. public static PredictionEngine<Data, DataPrediction> LastNamePredictionEngine { get; private set; }
  16. private static readonly string BaseModelsPath = @"../MLModels";
  17. private static readonly string CityModelPath= $"{BaseModelsPath}/CityModel.zip";
  18. private static readonly string FirstModelPath= $"{BaseModelsPath}/FirstNameModel.zip";
  19. private static readonly string LastNameModelPath= $"{BaseModelsPath}/LastNameModel.zip";
  20. public static void InitializeMLModel()
  21. {
  22. var mlContext = new MLContext(seed: 1);
  23. ITransformer cityTrainedModel, firstNameTrainedModel, lastNameTrainedModel;
  24. using (var stream = new FileStream(CityModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
  25. {
  26. cityTrainedModel = mlContext.Model.Load(stream);
  27. }
  28. using (var stream = new FileStream(FirstModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. {
  30. firstNameTrainedModel = mlContext.Model.Load(stream);
  31. }
  32. using (var stream = new FileStream(LastNameModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
  33. {
  34. lastNameTrainedModel = mlContext.Model.Load(stream);
  35. }
  36. CityPredictionEngine = cityTrainedModel.CreatePredictionEngine<Data, DataPrediction>(mlContext);
  37. FirstNamePredictionEngine = firstNameTrainedModel.CreatePredictionEngine<Data, DataPrediction>(mlContext);
  38. LastNamePredictionEngine = lastNameTrainedModel.CreatePredictionEngine<Data, DataPrediction>(mlContext);
  39. }
  40. }
  41. }