Projekt

Obecné

Profil

Stáhnout (3.93 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 void Fit(IEnumerable<ModelInput> trainInput)
43
        {
44
            this._trainingDataView = _mlContext.Data.LoadFromEnumerable(trainInput);
45
            var pipeline = _mlContext.Transforms.Conversion.MapValueToKey(nameof(ModelInput.Label))
46
                .Append(_mlContext.Transforms.Conversion.ConvertType(nameof(ModelInput.Hour)))
47
                .Append(_mlContext.Transforms.Concatenate("Features", 
48
                new[] { nameof(ModelInput.Temp), nameof(ModelInput.Rain), nameof(ModelInput.Wind), nameof(ModelInput.Hour) }))
49
                .Append(_mlContext.Transforms.NormalizeMeanVariance("Features", useCdf:false))
50
                .AppendCacheCheckpoint(_mlContext)
51
                .Append(_mlContext.MulticlassClassification.Trainers.NaiveBayes())
52
                .Append(_mlContext.Transforms.Conversion.MapKeyToValue(nameof(ModelOutput.PredictedLabel)));
53

    
54
            var cvResults = _mlContext.MulticlassClassification.CrossValidate(this._trainingDataView, pipeline);
55
            _log.Debug("Cross-validated the trained model");
56
            this._trainedModel = cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Model).First();
57
            _log.Info($"Selected the model #{cvResults.OrderByDescending(fold => fold.Metrics.MicroAccuracy).Select(fold => fold.Fold).First()} as the best.");
58
            this._predictionEngine = _mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(this._trainedModel);
59

    
60
        }
61

    
62
        public string Predict(ModelInput input)
63
        {
64
            _log.Debug($"Predicting for input: {input}");
65
            return this._predictionEngine.Predict(input).PredictedLabel;
66
        }
67

    
68
        public void Evaluate(IEnumerable<ModelInput> modelInputs)
69
        {
70
            var testDataView = this._mlContext.Data.LoadFromEnumerable(modelInputs);
71
            var data = _trainedModel.Transform(testDataView);
72
            var testMetrics = _mlContext.MulticlassClassification.Evaluate(data);
73

    
74
            Console.WriteLine($"*************************************************************************************************************");
75
            Console.WriteLine($"*       Metrics for Multi-class Classification model - Test Data     ");
76
            Console.WriteLine($"*------------------------------------------------------------------------------------------------------------");
77
            Console.WriteLine($"*       MicroAccuracy:    {testMetrics.MicroAccuracy:0.###}");
78
            Console.WriteLine($"*       MacroAccuracy:    {testMetrics.MacroAccuracy:0.###}");
79
            Console.WriteLine($"*       LogLoss:          {testMetrics.LogLoss:#.###}");
80
            Console.WriteLine($"*       LogLossReduction: {testMetrics.LogLossReduction:#.###}");
81
            Console.WriteLine($"*       Confusion Matrix: {testMetrics.ConfusionMatrix.GetFormattedConfusionTable()}");
82
            Console.WriteLine($"*************************************************************************************************************");
83
        }
84
    }
85
}
(7-7/9)