|
| 1 | +using System; |
| 2 | +using System.Linq; |
| 3 | + |
| 4 | +using Microsoft.ML; |
| 5 | + |
| 6 | +using CreditCardFraudDetection.Common.DataModels; |
| 7 | + |
| 8 | +namespace CreditCardFraudDetection.Predictor |
| 9 | +{ |
| 10 | + public class Predictor |
| 11 | + { |
| 12 | + private readonly string _modelfile; |
| 13 | + private readonly string _dasetFile; |
| 14 | + |
| 15 | + public Predictor(string modelfile, string dasetFile) |
| 16 | + { |
| 17 | + _modelfile = modelfile ?? throw new ArgumentNullException(nameof(modelfile)); |
| 18 | + _dasetFile = dasetFile ?? throw new ArgumentNullException(nameof(dasetFile)); |
| 19 | + } |
| 20 | + |
| 21 | + |
| 22 | + public void RunMultiplePredictions(int numberOfPredictions) |
| 23 | + { |
| 24 | + var mlContext = new MLContext(); |
| 25 | + |
| 26 | + // Load data as input for predictions |
| 27 | + IDataView inputDataForPredictions = mlContext.Data.LoadFromTextFile<TransactionObservation>(_dasetFile, separatorChar: ',', hasHeader: true); |
| 28 | + |
| 29 | + Console.WriteLine($"Predictions from saved model:"); |
| 30 | + |
| 31 | + ITransformer model = mlContext.Model.Load(_modelfile, out var inputSchema); |
| 32 | + |
| 33 | + var predictionEngine = mlContext.Model.CreatePredictionEngine<TransactionObservation, TransactionFraudPrediction>(model); |
| 34 | + |
| 35 | + Console.WriteLine($"\n \n Test {numberOfPredictions} transactions, from the test datasource, that should be predicted as fraud (true):"); |
| 36 | + |
| 37 | + mlContext.Data.CreateEnumerable<TransactionObservation>(inputDataForPredictions, reuseRowObject: false) |
| 38 | + .Where(x => x.Label > 0) |
| 39 | + .Take(numberOfPredictions) |
| 40 | + .Select(testData => testData) |
| 41 | + .ToList() |
| 42 | + .ForEach(testData => |
| 43 | + { |
| 44 | + Console.WriteLine($"--- Transaction ---"); |
| 45 | + testData.PrintToConsole(); |
| 46 | + predictionEngine.Predict(testData).PrintToConsole(); |
| 47 | + Console.WriteLine($"-------------------"); |
| 48 | + }); |
| 49 | + |
| 50 | + |
| 51 | + Console.WriteLine($"\n \n Test {numberOfPredictions} transactions, from the test datasource, that should NOT be predicted as fraud (false):"); |
| 52 | + |
| 53 | + mlContext.Data.CreateEnumerable<TransactionObservation>(inputDataForPredictions, reuseRowObject: false) |
| 54 | + .Where(x => x.Label < 1) |
| 55 | + .Take(numberOfPredictions) |
| 56 | + .ToList() |
| 57 | + .ForEach(testData => |
| 58 | + { |
| 59 | + Console.WriteLine($"--- Transaction ---"); |
| 60 | + testData.PrintToConsole(); |
| 61 | + predictionEngine.Predict(testData).PrintToConsole(); |
| 62 | + Console.WriteLine($"-------------------"); |
| 63 | + }); |
| 64 | + } |
| 65 | + } |
| 66 | +} |
0 commit comments