Projekt

Obecné

Profil

« Předchozí | Další » 

Revize 870cd163

Přidáno uživatelem Roman Kalivoda před téměř 4 roky(ů)

Re #8953 Implement prediction

Zobrazit rozdíly:

Server/ServerApp/Predictor/FeatureExtractor.cs
78 78
                List<int> maxima = new List<int>();
79 79
                foreach (string building in buildings)
80 80
                {
81

  
82
                    amounts.Add(attendance.Where(activity => activity.building.Equals(building) && activity.startTime.Equals(input.Time)).Select(activity => activity.amount).First());
83
                    maxima.Add(attendance.Where(activity => activity.building.Equals(building)).Select(activity => activity.amount).Max());
81
                    List<ActivityInfo> temp = attendance.Where(activity => activity.building.Equals(building)).ToList();
82
                    amounts.Add(temp.Where(activity => activity.startTime.Equals(input.Time)).Select(activity => activity.amount).First());
83
                    maxima.Add(temp.Select(activity => activity.amount).Max());
84 84
                }
85 85
                double ratio = amounts.Sum() / (double)maxima.Sum();
86 86
                input.Label = RatioToLabel(ratio);
......
133 133
            }
134 134
        }
135 135

  
136
        private double LabelToRatio(string label)
136
        internal double LabelToRatio(string label)
137 137
        {
138 138
            if (label.Equals("10%"))
139 139
            {
Server/ServerApp/Predictor/NaiveBayesClassifier.cs
43 43
                .Append(_mlContext.Transforms.Conversion.ConvertType(nameof(ModelInput.Hour)))
44 44
                .Append(_mlContext.Transforms.Concatenate("Features", 
45 45
                new[] { nameof(ModelInput.Temp), nameof(ModelInput.Rain), nameof(ModelInput.Wind), nameof(ModelInput.Hour) }))
46
                .Append(_mlContext.Transforms.NormalizeMinMax("Features", "Features"))
46
                .Append(_mlContext.Transforms.NormalizeMeanVariance("Features", useCdf:false))
47 47
                .AppendCacheCheckpoint(_mlContext)
48 48
                .Append(_mlContext.MulticlassClassification.Trainers.NaiveBayes())
49 49
                .Append(_mlContext.Transforms.Conversion.MapKeyToValue(nameof(ModelOutput.PredictedLabel)));
Server/ServerApp/Predictor/PredictionController.cs
7 7
using ServerApp.Connection.XMLProtocolHandler;
8 8
using ServerApp.Parser.Parsers;
9 9
using Newtonsoft.Json;
10
using ServerApp.WeatherPredictionParser;
11
using ServerApp.Parser.OutputInfo;
10 12

  
11 13
namespace ServerApp.Predictor
12 14
{
13 15
    /// <summary>
14 16
    /// Implentation of the <c>IPredicitionController</c> interface.
15 17
    /// </summary>
16
    class PredictionController : IPredictionController
18
    public class PredictionController : IPredictionController
17 19
    {
18 20
        /// <summary>
19 21
        /// Configuration of the <c>Predictor</c>
......
32 34
        /// </summary>
33 35
        private FeatureExtractor FeatureExtractor;
34 36

  
37
        /// <summary>
38
        /// A weather prediction parser service
39
        /// </summary>
40
        private IJsonParser weatherService;
41

  
35 42
        /// <summary>
36 43
        /// Instantiates new prediction controller.
37 44
        /// </summary>
38 45
        /// <param name="dataParser">A data parser used to get training data.</param>
39
        public PredictionController(IDataParser dataParser, string pathToConfig = null)
46
        public PredictionController(IJsonParser weatherService, IDataParser dataParser, string pathToConfig = null)
40 47
        {
48
            this.weatherService = weatherService;
41 49
            // load config or get the default one
42 50
            if (pathToConfig is null)
43 51
            {
......
82 90

  
83 91
        public Response Predict(Request request)
84 92
        {
85
            throw new NotImplementedException();
93
            DateTime start = new DateTime(year: request.start.year, month: request.start.month, day: request.start.day, hour: request.start.hour, minute: 0, second: 0);
94
            List<Prediction> predictions = new List<Prediction>();
95
            if (request.useEndDate)
96
            {
97
                DateTime end = new DateTime(year: request.end.year, month: request.end.month, day: request.end.day, hour: request.end.hour, minute: 0, second: 0);
98
                DateTime current = start;
99
                while (current < end)
100
                {
101
                    while (current.Hour < Date.MAX_HOUR)
102
                    {
103
                        var prediction = PredictSingle(request, current);
104
                        predictions.Add(prediction);
105
                        current = current.AddHours(this.Configuration.TimeResolution);
106
                    }
107
                    current = current.AddHours(23 - current.Hour + Date.MIN_HOUR);
108
                }
109
            } else
110
            {
111
                if (request.useWeather)
112
                {
113
                    predictions.Add(PredictSingle(request, start));
114
                }
115
            }
116
            var response = new Response();
117
            response.hoursPerSegment = Configuration.TimeResolution;
118
            response.predicitons = predictions.ToArray();
119
            return response;
86 120
        }
87 121

  
122
        private Prediction PredictSingle(Request request, DateTime current)
123
        {
124
            double[] predictedValues = new double[this.Configuration.BuildingsToAreas.Count];
125
            string[] predictedLabels = new string[this.Predictors.Count];
126
            for (int i = 0; i < this.Predictors.Count; i++)
127
            {
128
                if (request.useWeather)
129
                {
130
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
131
                    {
132
                        Rain = (float)request.rain,
133
                        Temp = (float)request.temperature,
134
                        Wind = (float)request.wind,
135
                        Hour = current.Hour,
136
                        Time = current
137
                    });
138
                }
139
                else
140
                {
141
                    List<WeatherInfo> weatherInfos = weatherService.GetPredictionForTime(from: current, to: current.AddHours(this.Configuration.TimeResolution));
142
                    predictedLabels[i] = this.Predictors[i].Predict(new ModelInput
143
                    {
144
                        Rain = weatherInfos[0].rain,
145
                        Temp = (float)weatherInfos[0].temp,
146
                        Wind = (float)weatherInfos[0].wind,
147
                        Hour = current.Hour,
148
                        Time = current
149
                    });
150
                }
151
            }
152
            for (int i = 0; i < predictedValues.Length; i++)
153
            {
154
                predictedValues[i] = this.FeatureExtractor.LabelToRatio(predictedLabels[this.Configuration.BuildingsToAreas[TagInfo.buildings[i]]]) * 100;
155
            }
156

  
157
            Prediction prediction = new Prediction();
158
            prediction.dateTime = new Date
159
            {
160
                year = current.Year,
161
                month = current.Month,
162
                day = current.Day,
163
                hour = current.Hour
164
            };
165
            prediction.predictions = predictedValues;
166
            return prediction;
167
        }
88 168

  
89 169
        public void Train(string locationKey = null)
90 170
        {
91 171
            if (locationKey is null)
92 172
            // train all predictors
93 173
            {
94
                // TODO A single predictor is used for all areas, so training is done only once now.
95 174
                for (int i = 0; i < this.Predictors.Count; i++)
96 175
                {
97 176
                    // train on all available data
98
                    // TODO the train/test split is used just temporarily for demonstration.
99 177
                    List<ModelInput> data = FeatureExtractor.PrepareTrainingInput(i, DateTime.MinValue, DateTime.MaxValue);
100 178
                    Console.WriteLine("Training predictor with {0} samples.", data.Count);
101 179
                    this.Predictors[i].Fit(data);
Server/ServerApp/Program.cs
146 146

  
147 147
			// TODO nastavit čas
148 148
			IDataParser p = new DataParser(dd);
149
            IPredictionController predictionController = new PredictionController(p);
149
            IPredictionController predictionController = new PredictionController(jsonP, p);
150 150
            predictionController.Train();
151 151
            //var results = predictionController.Predict()
152 152
			
Server/ServerApp/WeatherPredictionParser/IJsonParser.cs
11 11
    /// <summary>
12 12
    /// Abstract class that every Json parser should inherit from
13 13
    /// </summary>
14
    abstract class IJsonParser
14
    public abstract class IJsonParser
15 15
    {
16 16

  
17 17
        /// <summary> Current weather </summary>

Také k dispozici: Unified diff