1
|
//
|
2
|
// Author: Roman Kalivoda
|
3
|
//
|
4
|
|
5
|
using System;
|
6
|
using System.Collections.Generic;
|
7
|
using System.Linq;
|
8
|
using System.Reflection;
|
9
|
using log4net;
|
10
|
using Microsoft.ML;
|
11
|
|
12
|
namespace ServerApp.Predictor
|
13
|
{
|
14
|
/// <summary>
|
15
|
/// Implementation of the naive Bayes classifier in ML.NET.
|
16
|
/// </summary>
|
17
|
class NaiveBayesClassifier : IPredictor
|
18
|
{
|
19
|
private static readonly ILog _log = LogManager.GetLogger(typeof(NaiveBayesClassifier));
|
20
|
|
21
|
/// <summary>
|
22
|
/// Context of the ML.NET framework.
|
23
|
/// </summary>
|
24
|
private MLContext _mlContext;
|
25
|
|
26
|
/// <summary>
|
27
|
/// Model instance
|
28
|
/// </summary>
|
29
|
private ITransformer _trainedModel;
|
30
|
|
31
|
private PredictionEngine<ModelInput, ModelOutput> _predictionEngine;
|
32
|
|
33
|
IDataView _trainingDataView;
|
34
|
|
35
|
/// <summary>
|
36
|
/// Instantiates new <c>MLContext</c>.
|
37
|
/// </summary>
|
38
|
public NaiveBayesClassifier()
|
39
|
{
|
40
|
_mlContext = new MLContext();
|
41
|
}
|
42
|
|
43
|
public void Fit(IEnumerable<ModelInput> trainInput)
|
44
|
{
|
45
|
this._trainingDataView = _mlContext.Data.LoadFromEnumerable(trainInput);
|
46
|
var pipeline = _mlContext.Transforms.Conversion.MapValueToKey(nameof(ModelInput.Label))
|
47
|
.Append(_mlContext.Transforms.Conversion.ConvertType(nameof(ModelInput.Hour)))
|
48
|
.Append(_mlContext.Transforms.Concatenate("Features",
|
49
|
new[] { nameof(ModelInput.Temp), nameof(ModelInput.Rain), nameof(ModelInput.Wind), nameof(ModelInput.Hour) }))
|
50
|
.Append(_mlContext.Transforms.NormalizeMeanVariance("Features", useCdf:false))
|
51
|
.AppendCacheCheckpoint(_mlContext)
|
52
|
.Append(_mlContext.MulticlassClassification.Trainers.NaiveBayes())
|
53
|
.Append(_mlContext.Transforms.Conversion.MapKeyToValue(nameof(ModelOutput.PredictedLabel)));
|
54
|
|
55
|
var cvResults = _mlContext.MulticlassClassification.CrossValidate(this._trainingDataView, pipeline);
|
56
|
_log.Debug("Cross-validated the trained model");
|
57
|
this._trainedModel = cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Model).First();
|
58
|
_log.Info($"Selected the model #{cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Fold).First()} as the best.");
|
59
|
this._predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(this._trainedModel);
|
60
|
|
61
|
}
|
62
|
|
63
|
public string Predict(ModelInput input)
|
64
|
{
|
65
|
_log.Debug($"Predicting for input: {input}");
|
66
|
return this._predictionEngine.Predict(input).PredictedLabel;
|
67
|
}
|
68
|
|
69
|
public void Evaluate(IEnumerable<ModelInput> modelInputs)
|
70
|
{
|
71
|
var testDataView = this._mlContext.Data.LoadFromEnumerable(modelInputs);
|
72
|
var data = _trainedModel.Transform(testDataView);
|
73
|
var testMetrics = _mlContext.MulticlassClassification.Evaluate(data);
|
74
|
|
75
|
Console.WriteLine($"*************************************************************************************************************");
|
76
|
Console.WriteLine($"* Metrics for Multi-class Classification model - Test Data ");
|
77
|
Console.WriteLine($"*------------------------------------------------------------------------------------------------------------");
|
78
|
Console.WriteLine($"* MicroAccuracy: {testMetrics.MicroAccuracy:0.###}");
|
79
|
Console.WriteLine($"* MacroAccuracy: {testMetrics.MacroAccuracy:0.###}");
|
80
|
Console.WriteLine($"* LogLoss: {testMetrics.LogLoss:#.###}");
|
81
|
Console.WriteLine($"* LogLossReduction: {testMetrics.LogLossReduction:#.###}");
|
82
|
Console.WriteLine($"* Confusion Matrix: {testMetrics.ConfusionMatrix.GetFormattedConfusionTable()}");
|
83
|
Console.WriteLine($"*************************************************************************************************************");
|
84
|
}
|
85
|
}
|
86
|
}
|