示例#1
0
        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            Microsoft.Win32.OpenFileDialog openFileDlg = new Microsoft.Win32.OpenFileDialog();
            openFileDlg.DefaultExt       = ".csv";
            openFileDlg.Filter           = "Csv Data Files (.csv)|*.csv";
            openFileDlg.InitialDirectory = Environment.CurrentDirectory; // TODO: remove this, temporary to facilitate the development

            Nullable <bool> result = openFileDlg.ShowDialog();

            if (result == true)
            {
                tbFileName.Text = openFileDlg.SafeFileName;

                var reader = new CSVReader();
                _PredictModel = await ExecuteBackgroundAsyncProcess <PredictModel>(async() =>
                {
                    var success = await reader.ReadAsync(openFileDlg.FileName);
                    if (success)
                    {
                        var model = new PredictModel(reader.Points);
                        await model.Process();

                        return(model);
                    }

                    return(null);
                });

                if (_PredictModel != null)
                {
                    if (_PredictModel.IsLoaded)
                    {
                        MainChart = new PlotModel
                        {
                            PlotType = PlotType.Cartesian
                        };

                        var series = new ScatterSeries
                        {
                            Title                 = "Points",
                            MarkerType            = MarkerType.Cross, //better performance, less to render
                            MarkerStrokeThickness = 0.5,
                            MarkerStroke          = OxyColors.DarkOliveGreen
                        };

                        series.Points.AddRange(_PredictModel.ValidPoints.ToScatterPoints());
                        MainChart.Series.Add(series);

                        ShowInvalidPoints();

                        pvMainChart.Model = MainChart;
                    }
                }
                else
                {
                    MessageBox.Show("Unable to load data, check the log files");
                    //TODO: Use a better notification window
                }
            }
        }
示例#2
0
        private void Clear_All(object sender, RoutedEventArgs e)
        {
            LinearCoefficient.Clear();
            ExponentialCoefficient.Clear();
            PowerFcCoefficient.Clear();
            tbFileName.Clear();

            pvMainChart.Model = null;
            _PredictModel     = null;
        }
        /// <summary>
        /// Runs the specified model.
        /// </summary>
        /// <param name="games">The games.</param>
        /// <param name="count">The count.</param>
        /// <param name="verbose">if set to <c>true</c> [verbose].</param>
        public override void Run(IEnumerable <Game> games, int count, bool verbose)
        {
            this.PlayerPosteriors = this.Priors.Skills.ToDictionary(ia => ia.Key, ia => new List <Gaussian> {
                ia.Value
            });
            this.DrawMargins = new List <Gaussian> {
                this.Priors.DrawMargin
            };
            this.Predictions = new List <Prediction>();

            using (new CodeTimer(this.Name))
            {
                foreach (var game in games)
                {
                    var priors = new Marginals {
                        DrawMargin = this.DrawMargins.Last()
                    };

                    foreach (var player in game.Players)
                    {
                        if (!this.PlayerPosteriors.ContainsKey(player))
                        {
                            this.PlayerPosteriors[player] = new List <Gaussian> {
                                this.SkillPrior
                            };
                        }

                        priors.Skills[player] = this.PlayerPosteriors[player].Last();
                    }

                    // Predict outcome of game
                    var prediction = PredictModel?.PredictOutcome(game, priors);
                    if (prediction != null)
                    {
                        this.Predictions.Add(prediction);
                    }

                    // Train model using this game
                    this.LastResults = this.TrainModel.Train(game, game.Players, priors);

                    foreach (var player in game.Players)
                    {
                        this.PlayerPosteriors[player].Add(this.LastResults.Posteriors.Skills[player]);
                    }

                    this.DrawMargins.Add(this.LastResults.Posteriors.DrawMargin);

                    if (verbose)
                    {
                        var post = this.LastResults.Posteriors.Skills.Select(ia => $"{ia.Key}: {ia.Value}").ToArray();
                        Console.WriteLine(@"Game {0}, Posteriors: {1}", game.Id, string.Join(", ", post));
                    }
                }
            }
        }
示例#4
0
        public ActionResult Regression(PredictModel model)
        {
            string response = "";

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            //Invoke Azure service for regression model
            response = RegressionCallOutPrediction.PredictCallOutRegression(model);
            // If we got this far, something failed, redisplay form
            if (response != "Error")
            {
                model.callOutActivity = float.Parse(response);
            }
            return(View(model));
        }
示例#5
0
        public ActionResult Classify(PredictModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            string response = "";

            //Invoke Azure service for classification
            response = ClassificationActivity.Classify(model);
            string[] values = response.Split('-');

            // If we got this far, something failed, redisplay form
            if (response != "Error")
            {
                model.category    = values[0];
                model.probability = float.Parse(values[1]);
            }
            return(View(model));
        }
示例#6
0
        public virtual ActionResult Predict(PredictModel model)
        {
            if (!ModelState.IsValid)
            {
                return(HttpNotFound());
            }

            var sw = Stopwatch.StartNew();

            RawDrawing rawDrawing;

            try {
                var lines = JsonConvert.DeserializeObject <RawPoint[][]>(model.JsonData);
                rawDrawing = new RawDrawing()
                {
                    Lines = lines
                };
            }
            catch (Exception ex) {
                return(HttpNotFound());
            }

            if (rawDrawing.LinesCount == 0)
            {
                return(Json(new {
                    Results = new int[0],                      // Any empty array will do (C# meets JS :).
                    Duration = (float)sw.Elapsed.TotalMilliseconds,
                }));
            }

            List <Tuple <Symbol, float> > rawResults = predict(rawDrawing);

            var minTime = DateTime.UtcNow.AddSeconds(-GUID_CHECK_WINDOW_SECONDS);

            Drawing drawing = null;

            if (model.IsFollowupDraw)
            {
                drawing = db.Drawings
                          .Where(d => d.ClientGuid == model.Guid && DateTime.Compare(d.DrawnDateTime, minTime) > 0)
                          .FirstOrDefault();
            }

            if (drawing == null)
            {
                drawing = new Drawing();
                drawing.DrawnDateTime = DateTime.UtcNow;
                drawing.ClientGuid    = model.Guid;
                db.Drawings.Add(drawing);
            }
#if DEBUG
            else
            {
                // Delete potentially cached image - this does not happen ofthen but it is annoying when it does happen.
                new DrawingsController(db, DependencyResolver.Current.GetService <AppSettingsProvider>())
                .ClearCachedImage(drawing.DrawingId);
            }
#endif
            var firstResult = rawResults.FirstOrDefault();

            drawing.TopSymbol       = firstResult == null ? null : firstResult.Item1;
            drawing.TopSymbolScore  = firstResult == null ? null : (double?)firstResult.Item2;
            drawing.DrawnUsingTouch = model.DrawnUsingTouch;
            drawing.SetRawDrawing(rawDrawing);

            db.SaveChanges();

            return(Json(new {
                Results = rawResults.Select(x => new {
                    SymbolId = x.Item1.SymbolId,
                    Symbol = x.Item1.SymbolStr,
                    SymbolName = x.Item1.Name,
                    Rating = x.Item2,
                    HtmlEntity = x.Item1.HtmlEntity ?? "",
                    UtfCode = char.ConvertToUtf32(x.Item1.SymbolStr, 0),
                }),
                Duration = (float)sw.Elapsed.TotalMilliseconds,
            }));
        }