Projekt

Obecné

Profil

Stáhnout (4.33 KB) Statistiky
| Větev: | Tag: | Revize:
1
//
2
// Author: Roman Kalivoda
3
//
4

    
5
using System;
6
using System.Collections.Generic;
7
using System.Linq;
8
using log4net;
9
using Microsoft.ML;
10

    
11
namespace ServerApp.Predictor
12
{
13
    /// <summary>
14
    /// Implementation of the naive Bayes classifier in ML.NET.
15
    /// </summary>
16
    class NaiveBayesClassifier : IPredictor
17
    {
18
        private static readonly ILog _log = LogManager.GetLogger(typeof(NaiveBayesClassifier));
19

    
20
        /// <summary>
21
        /// Context of the ML.NET framework.
22
        /// </summary>
23
        private MLContext _mlContext;
24

    
25
        /// <summary>
26
        /// Model instance
27
        /// </summary>
28
        private ITransformer _trainedModel;
29

    
30
        private PredictionEngine<ModelInput, ModelOutput> _predictionEngine;
31

    
32
        IDataView _trainingDataView;
33

    
34
        /// <summary>
35
        /// Instantiates new <c>MLContext</c>.
36
        /// </summary>
37
        public NaiveBayesClassifier()
38
        {
39
            _mlContext = new MLContext();
40
        }
41

    
42
        public NaiveBayesClassifier(string filename) : this()
43
        {
44
            DataViewSchema modelSchema;
45
            this._trainedModel = _mlContext.Model.Load(filename, out modelSchema);
46
            // TODO check if the loaded model has valid input and output schema
47
            this._predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(this._trainedModel);
48
        }
49

    
50
        public void Fit(IEnumerable<ModelInput> trainInput)
51
        {
52
            this._trainingDataView = _mlContext.Data.LoadFromEnumerable(trainInput);
53
            var pipeline = _mlContext.Transforms.Conversion.MapValueToKey(nameof(ModelInput.Label))
54
                .Append(_mlContext.Transforms.Conversion.ConvertType(nameof(ModelInput.Hour)))
55
                .Append(_mlContext.Transforms.Concatenate("Features", 
56
                new[] { nameof(ModelInput.Temp), nameof(ModelInput.Rain), nameof(ModelInput.Wind), nameof(ModelInput.Hour) }))
57
                .Append(_mlContext.Transforms.NormalizeMeanVariance("Features", useCdf:false))
58
                .AppendCacheCheckpoint(_mlContext)
59
                .Append(_mlContext.MulticlassClassification.Trainers.NaiveBayes())
60
                .Append(_mlContext.Transforms.Conversion.MapKeyToValue(nameof(ModelOutput.PredictedLabel)));
61

    
62
            var cvResults = _mlContext.MulticlassClassification.CrossValidate(this._trainingDataView, pipeline);
63
            _log.Debug("Cross-validated the trained model");
64
            this._trainedModel = cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Model).First();
65
            _log.Info($"Selected the model #{cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Fold).First()} as the best.");
66
            this._predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(this._trainedModel);
67

    
68
        }
69

    
70
        public string Predict(ModelInput input)
71
        {
72
            _log.Debug($"Predicting for input: {input}");
73
            return this._predictionEngine.Predict(input).PredictedLabel;
74
        }
75

    
76
        public void Evaluate(IEnumerable<ModelInput> modelInputs)
77
        {
78
            var testDataView = this._mlContext.Data.LoadFromEnumerable(modelInputs);
79
            var data = _trainedModel.Transform(testDataView);
80
            var testMetrics = _mlContext.MulticlassClassification.Evaluate(data);
81

    
82
            Console.WriteLine($"*************************************************************************************************************");
83
            Console.WriteLine($"*       Metrics for Multi-class Classification model - Test Data     ");
84
            Console.WriteLine($"*------------------------------------------------------------------------------------------------------------");
85
            Console.WriteLine($"*       MicroAccuracy:    {testMetrics.MicroAccuracy:0.###}");
86
            Console.WriteLine($"*       MacroAccuracy:    {testMetrics.MacroAccuracy:0.###}");
87
            Console.WriteLine($"*       LogLoss:          {testMetrics.LogLoss:#.###}");
88
            Console.WriteLine($"*       LogLossReduction: {testMetrics.LogLossReduction:#.###}");
89
            Console.WriteLine($"*       Confusion Matrix: {testMetrics.ConfusionMatrix.GetFormattedConfusionTable()}");
90
            Console.WriteLine($"*************************************************************************************************************");
91
        }
92
    }
93
}
(7-7/9)