Projekt

Obecné

Profil

Stáhnout (2.5 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 System.Text;
9
using System.Threading.Tasks;
10
using Microsoft.ML;
11
using Microsoft.ML.Data;
12
using ServerApp.Parser.OutputInfo;
13

    
14
namespace ServerApp.Predictor
15
{
16
    /// <summary>
17
    /// Implementation of the naive Bayes classifier in ML.NET.
18
    /// </summary>
19
    class NaiveBayesClassifier : IPredictor
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 model;
30

    
31
        /// <summary>
32
        /// Instantiates new <c>MLContext</c>.
33
        /// </summary>
34
        public NaiveBayesClassifier()
35
        {
36
            mlContext = new MLContext();
37

    
38
        }
39

    
40
        /// <summary>
41
        /// Extracts list of feature vectors from parsed info objects.
42
        /// </summary>
43
        /// <param name="weatherInfos">List of weather info objects.</param>
44
        /// <param name="activityInfos">List of info objects about activities at the site.</param>
45
        /// <returns>A list of feature vectors for model training.</returns>
46
        public IEnumerable<ModelInput> ExtractModelInput(List<WeatherInfo> weatherInfos, List<ActivityInfo> activityInfos)
47
        {
48
            return weatherInfos.Select(e => new ModelInput(){
49
                Temp = (float)e.temp,
50
                Label = e.temp > 15.0 ? "Full" : "Empty",
51
            }).ToList();
52
        }
53

    
54
        public void Fit(IEnumerable<ModelInput> trainInput)
55
        {
56
            IDataView trainingDataView = mlContext.Data.LoadFromEnumerable(trainInput);
57
            var dataProcessPipeline = mlContext.Transforms.Conversion.MapValueToKey(nameof(ModelInput.Label))
58
                .Append(mlContext.Transforms.Concatenate("Features", new[] { "temp" })
59
                .Append(mlContext.Transforms.NormalizeMinMax("Features", "Features")));
60
            var trainer = mlContext.MulticlassClassification.Trainers.NaiveBayes();
61
            var traininingPipeline = dataProcessPipeline.Append(trainer)
62
                .Append(mlContext.Transforms.Conversion.MapKeyToValue("prediction", "PredictedLabel"));
63

    
64
            this.model = traininingPipeline.Fit(trainingDataView);
65

    
66
        }
67

    
68
        public IDataView Predict(IEnumerable<ModelInput> input)
69
        {
70
            var data = mlContext.Data.LoadFromEnumerable(input);
71
            IDataView result = model.Transform(data);
72
            return result;
73
        }
74
    }
75
}
(4-4/4)