public void Should_Throw_Argument_Null_Exception_When_Rates_Is_Null()
        {
            int month = 13;
            IEnumerable <MonthlyRate> rates = null;

            Assert.Throws <ArgumentNullException>(() => _predictor.Predict(month, rates));
        }
Example #2
0
        public void Test1()
        {
            Random randNum = new Random();

            int[] yValues = Enumerable.Repeat(0, 12).Select(i => randNum.Next(1, 30)).ToArray();

            Queue <ExchangeRate> rateQueue = new Queue <ExchangeRate>();

            foreach (int yValue in yValues)
            {
                ExchangeRate r = new ExchangeRate();
                r.rates = new JObject(new JProperty("VND", yValue));

                rateQueue.Enqueue(r);
            }

            Mock <IExchangeRateDataReader> readerMock = new Mock <IExchangeRateDataReader>();

            readerMock.Setup(reader => reader.Read(It.IsAny <DateTime>(), It.IsAny <string>())).Returns(rateQueue.Dequeue);

            PredictorOption predictorOption = new PredictorOption
            {
                FromCurrency = "USD",
                ToCurrency   = "VND",
                FromDate     = new DateTime(year: 2016, month: 1, day: 15),
                ToDate       = new DateTime(year: 2016, month: 12, day: 15),
                PredictDate  = new DateTime(year: 2017, month: 1, day: 15)
            };

            IPredictor predictor = new Predictor(readerMock.Object);
            decimal    rate      = predictor.Predict(predictorOption);

            Assert.True(rate > 0);
        }
Example #3
0
    private void SpellAndDestroy()
    {
        var positions = _line.Points;

        if (positions.Length < _minimumPoints)
        {
            Destroy(gameObject);
            return;
        }

        try
        {
            var prediction = _predictor.Predict(positions, ImageSize);

            if (prediction.HasValue)
            {
                GameObject.FindWithTag("Player").GetComponent <PlayerController>().Spelled(prediction.Value);
            }

            Destroy(gameObject);
        }
        catch
        {
            Destroy(gameObject);
        }
    }
Example #4
0
        static void TrainEvaluatePredict(TrainerBase trainer, BostonHousingData newSample)
        {
            Console.WriteLine("*******************************");
            Console.WriteLine($"{ trainer.Name }");
            Console.WriteLine("*******************************");

            trainer.Fit("..\\Data\\boston_housing.csv");

            var modelMetrics = trainer.Evaluate();

            Console.WriteLine($"Loss Function: {modelMetrics.LossFunction:0.##}{Environment.NewLine}" +
                              $"Mean Absolute Error: {modelMetrics.MeanAbsoluteError:#.##}{Environment.NewLine}" +
                              $"Mean Squared Error: {modelMetrics.MeanSquaredError:#.##}{Environment.NewLine}" +
                              $"RSquared: {modelMetrics.RSquared:0.##}{Environment.NewLine}" +
                              $"Root Mean Squared Error: {modelMetrics.RootMeanSquaredError:#.##}");

            trainer.Save();

            var predictor  = new Predictor();
            var prediction = predictor.Predict(newSample);

            Console.WriteLine("------------------------------");
            Console.WriteLine($"Prediction: {prediction.MedianPrice:#.##}");
            Console.WriteLine("------------------------------");
        }
Example #5
0
        private void CommunicationRoutine()
        {
            int i = 0;

            while (_connected)
            {
                _robot.Sensors = _connMan.ReadSensorsState();
                if (_steeringType == SteeringType.Script && i % 7 == 0)
                {
                    List <double> speeds = _neuralNetwork.Predict(_robot.Sensors.Select(x => (double)x.State).ToList());
                    _robot.LeftMotorSpeed  = (speeds[0]) * Robot.DEFAULT_MAX_SPEED;
                    _robot.RightMotorSpeed = (speeds[1]) * Robot.DEFAULT_MAX_SPEED;
                    _robot.SpeedChanged    = true;
                }
                if (i % 7 == 0)
                {
                    double speedFactor     = (Math.Abs(_robot.LeftMotorSpeed) + Math.Abs(_robot.RightMotorSpeed)) / (2 * Robot.DEFAULT_MAX_SPEED);
                    double movementFactor  = 1 - Math.Sqrt(Math.Abs(_robot.LeftMotorSpeed - _robot.RightMotorSpeed) / (2 * Robot.DEFAULT_MAX_SPEED));
                    double proximityFactor = 1 - Math.Sqrt(_robot.Sensors.Select(x => x.State).Max());
                    //Console.WriteLine(String.Format("{0:0.000} {1:0.000} {2:0.000} {3:0.000}", speedFactor * movementFactor * proximityFactor, speedFactor, movementFactor, proximityFactor));
                    Console.WriteLine(String.Format("{0:0.000}", speedFactor * movementFactor * proximityFactor));
                }
                if (_robot.SpeedChanged)
                {
                    _connMan.SendMotorsSpeedCommand(_robot.LeftMotorSpeed, _robot.RightMotorSpeed);
                    _robot.SpeedChanged = false;
                }
                i++;
            }
            _connMan.Disconnect();
        }
Example #6
0
        public static RecogReply PredictionFunc(Guid id, int timeBudgetInMS, RecogRequest req)
        {
            byte[] imgBuf      = req.Data;
            byte[] imgType     = System.Text.Encoding.UTF8.GetBytes("jpg");
            Guid   imgID       = BufferCache.HashBufferAndType(imgBuf, imgType);
            string imgFileName = imgID.ToString() + ".jpg";

            string filename = Path.Combine(saveImageDir, imgFileName);

            if (!File.Exists(filename))
            {
                FileTools.WriteBytesToFileConcurrent(filename, imgBuf);
            }

            Stopwatch timer = Stopwatch.StartNew();

            CaffeModel.SetDevice(gpu);
            string resultString = predictor.Predict(filename);

            timer.Stop();

            File.Delete(filename);
            numImageRecognized++;
            Console.WriteLine("Image {0}:{1}:{2}: {3}", numImageRecognized, imgFileName, timer.Elapsed, resultString);
            return(VHubRecogResultHelper.FixedClassificationResult(resultString, resultString));
        }
Example #7
0
        private void UpdateBalance()
        {
            BalanceRecords.Clear();

            DateTime lastTransactionDate;
            decimal  startingBalance = Core.Instance.GetBalanceToDate(SelectedMonth, SelectedYear, out lastTransactionDate);

            // Add starting balance row
            BalanceRecords.Add(new BalanceItem
            {
                Date     = lastTransactionDate,
                Change   = 0m,
                Total    = startingBalance,
                Origin   = "Balance",
                Category = string.Empty
            });
            // Add all transactions for a selected period
            List <Transaction> transactions = Core.Instance.GetTransactions(SelectedYear, SelectedMonth);

            transactions.Reverse();
            foreach (Transaction tr in transactions)
            {
                // filter out transaction before the last transaction date
                if (tr.Date > lastTransactionDate)
                {
                    startingBalance += tr.Amount;
                    BalanceRecords.Add(new BalanceItem
                    {
                        Date     = tr.Date,
                        Change   = tr.Amount,
                        Total    = startingBalance,
                        Origin   = "Transaction",
                        Category = (new CategoryNode(tr.Category)).FullName
                    });
                }
            }
            // Add all predictors for a selected period.
            DateTime actualDate = DateTime.Today;
            DateTime futureDate = new DateTime(SelectedYear, SelectedMonth,
                                               DateTime.DaysInMonth(SelectedYear, SelectedMonth));

            // Repeat for every month before selected
            while (actualDate <= futureDate)
            {
                foreach (Prediction pr in Predictor.Predict(actualDate))
                {
                    startingBalance += pr.Amount;
                    BalanceRecords.Add(new BalanceItem
                    {
                        Date     = pr.Date,
                        Change   = pr.Amount,
                        Total    = startingBalance,
                        Origin   = "Prediction",
                        Category = (new CategoryNode(pr.Category)).FullName
                    });
                }
                actualDate = actualDate.AddMonths(1);
            }
        }
Example #8
0
 void FixedUpdate()
 {
     transform.position = PositionByTime(TimeManager.GameTime);
     if (predictor != null)
     {
         predictor.Predict(PositionByTime(TimeManager.GameTime + TimeManager.GameFixedDeltaTime), transform.rotation.eulerAngles);
     }
 }
Example #9
0
        public void PredictSingle()
        {
            Predictor _pred = new Predictor();

            var res = _pred.Predict("2017/2018", 15);

            //var res2 = _pred.Predict("2017/2018", 2);
            Assert.IsTrue(res.Count > 0);
            Assert.IsNotNull(res[0]);
        }
Example #10
0
        public IActionResult TrainAndPredict(Reading reading)
        {
            var readings = _mlContext.Data.CreateEnumerable <Reading>(_dataset, true);
            var cleaned  = readings.Where(r => r.WasTested == 1);
            var dataset  = _mlContext.Data.LoadFromEnumerable <Reading>(cleaned);

            _model = Trainer.Train(_dataset);
            var result = Predictor.Predict(_model, reading);

            return(Ok(result));
        }
        public async void TestingPrediction()
        {
            Predictor predictor = new Predictor();
            var       input     = new List <int>()
            {
                23, 30, 32, 33, 34, 35, 36, 37, 38, 39, 0
            };
            var winChance = await predictor.Predict(input, "190500077");

            Assert.True(winChance >= 0 && winChance <= 1);
        }
Example #12
0
        public void PredictDate()
        {
            DateTime date = new DateTime(2017, 6, 1);

            Predictor _pred = new Predictor();

            var res = _pred.Predict(date, DateTime.Now);

            //var res2 = _pred.Predict("2017/2018", 2);
            Assert.IsTrue(res.Count > 0);
            Assert.IsNotNull(res[0]);
        }
Example #13
0
        protected override void Predict(string[] args)
        {
            var predictionData = new SentimentData
            {
                Text = args[(int)CommandLineArguments.OUTPUT_FILE]
            };

            var prediction = Predictor.Predict <SentimentData, SentimentPrediction>(MlContext, args[(int)CommandLineArguments.INPUT_FILE], predictionData);

            var verdict = prediction.Prediction ? "Positive" : "Negative";

            Console.WriteLine($"{predictionData.Text} is predicted to be {verdict} | {prediction.Probability}");
        }
        public double GetResult(PredictionRequest predictionRequest)
        {
            var input = new List <int>()
            {
                predictionRequest.OwnHeroId
            };

            input.AddRange(predictionRequest.AllyHeroIds);
            input.AddRange(predictionRequest.EnemyHeroIds);
            input.Add(predictionRequest.IsRadiant ? 0 : 1);

            Predictor predictor = new Predictor();

            return(predictor.Predict(input, predictionRequest.SteamId).GetAwaiter().GetResult());
        }
Example #15
0
        protected override void Predict(string[] args)
        {
            var predictionData = new FileData
            {
                Strings = File.ReadAllBytes(args[(int)CommandLineArguments.INPUT_FILE]).ToString()
            };

            var prediction = Predictor.Predict <FileData, FilePrediction>(MlContext,
                                                                          args[(int)CommandLineArguments.OUTPUT_FILE], predictionData);

            var verdict = prediction.Prediction ? "Positive" : "Negative";

            Console.WriteLine(
                $"{args[(int) CommandLineArguments.INPUT_FILE]} is predicted to be {verdict} | {prediction.Probability}");
        }
        protected override void Predict(string[] args)
        {
            var extraction = FeatureExtractFile(args[(int)CommandLineArguments.OUTPUT_FILE], true);

            if (extraction == null)
            {
                return;
            }

            Console.WriteLine($"Predicting on {args[(int)CommandLineArguments.OUTPUT_FILE]}:");

            var prediction = Predictor.Predict <ThreatInformation, ThreatPredictor>(MlContext, args[(int)CommandLineArguments.INPUT_FILE], extraction);

            PrettyPrintResult(prediction);
        }
Example #17
0
        public void Test_Predict_Output_Positive_IMDB()
        {
            _output.WriteLine("Test_Predict_Output_Positive_IMDB()...");

            const string INPUT_DATA = "amazing movie, very touching and deep";

            var predictor = new Predictor();

            predictor.LoadTrainData(Path.Combine(_dataFolderPath, "imdb_labelled.txt"));
            predictor.BuildAndTrainModel();

            var predictionTuple = predictor.Predict(INPUT_DATA);

            _output.WriteLine($"Prediction for \"{INPUT_DATA}\" : {predictionTuple.prediction} (Probability: {predictionTuple.probability}, Score: {predictionTuple.score})");

            Assert.True(predictionTuple.prediction);

            _output.WriteLine("...Test_Predict_Output_Positive_IMDB() DONE.");
        }
Example #18
0
        public void Test_Predict_Output_Negative_Amazon()
        {
            _output.WriteLine("Test_Predict_Output_Negative_Amazon()...");

            const string INPUT_DATA = "this smartphone does not work at all, and is heavy too";

            var predictor = new Predictor();

            predictor.LoadTrainData(Path.Combine(_dataFolderPath, "amazon_cells_labelled.txt"));
            predictor.BuildAndTrainModel();

            var predictionTuple = predictor.Predict(INPUT_DATA);

            _output.WriteLine($"Prediction for \"{INPUT_DATA}\" : {predictionTuple.prediction} (Probability: {predictionTuple.probability}, Score: {predictionTuple.score})");

            Assert.False(predictionTuple.prediction);

            _output.WriteLine("...Test_Predict_Output_Negative_Amazon() DONE.");
        }
Example #19
0
        public void Test_Predict_Output_Negative_Yelp()
        {
            _output.WriteLine("Test_Predict_Output_Negative_Yelp()...");

            const string INPUT_DATA = "This was quite a horrible meal";

            var predictor = new Predictor();

            predictor.LoadTrainData(Path.Combine(_dataFolderPath, "yelp_labelled.txt"));
            predictor.BuildAndTrainModel();

            var predictionTuple = predictor.Predict(INPUT_DATA);

            _output.WriteLine($"Prediction for \"{INPUT_DATA}\" : {predictionTuple.prediction} (Probability: {predictionTuple.probability}, Score: {predictionTuple.score})");

            Assert.False(predictionTuple.prediction);

            _output.WriteLine("...Test_Predict_Output_Negative_Yelp() DONE.");
        }
        public IEnumerable <LoadState> Broadcast()
        {
            ILinearSolver   mK0 = Info.Stiffness(State.Displacement);
            Vector <double> Dv0 = mK0.Solve(Info.ReferenceLoad);
            double          k0  = Info.ReferenceLoad.DotProduct(Dv0);

            while (true)
            {
                LoadIncrementalState prediction = Predictor.Predict(State, k0, Info);
                State = State.Add(prediction);
                Result <LoadIncrementalState> correctionResult = Corrector.Correct(State, prediction, Info);
                if (correctionResult.IsSuccess)
                {
                    State = State.Add(correctionResult.Value);
                    yield return(State);
                }
                else
                {
                    break;
                }
            }
        }
        public ActionResult Predict(string language, string query)
        {
            if (String.IsNullOrWhiteSpace(language) || String.IsNullOrWhiteSpace(query))
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }

            Language lang = (Language)Enum.Parse(typeof(Language), language);

            string[] segments = query.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries);

            List <string[][]> segmentChoices = new List <string[][]>();

            foreach (string segment in segments)
            {
                string[][] wordChoices = m_Predictor.Predict(lang, segment);
                if (wordChoices != null)
                {
                    segmentChoices.Add(wordChoices);
                }
            }

            return(Json(segmentChoices));
        }
        private void OnNextTurn()
        {
            Turn++;

            foreach (var provinceViewModel in this.Provinces)
            {
                provinceViewModel.IsFirstTurn = false;
                var provinceHistory = provinceHistories.Single(p => p.ProvinceName == provinceViewModel.ProvinceName);

                provinceHistory.Add(
                    new ProvinceRevision(
                        provinceViewModel.FarmsViewModel.Count,
                        provinceViewModel.ResourceViewModel.ResourceLevel,
                        provinceViewModel.SoldiersViewModel.Count,
                        provinceViewModel.CultureViewModel.CultureLevel));

                var predictor = new Predictor();
                var buildPredictions = predictor.Predict(provinceHistory);

                var firstPrediction = buildPredictions.First();
                provinceViewModel.BuildPrediction.Building = firstPrediction.Building;
                provinceViewModel.BuildPrediction.TurnsLeft = firstPrediction.TurnsLeft;
            }
        }
        private void OnChangeCapital()
        {
            Turn = 1;

            Provinces.Clear();

            provinceHistories.Clear();

            if (SelectedCapital != null)
            {
                var predictor = new Predictor();
                foreach (var neighbour in new NeighbourProvider().GetNeighbours(SelectedCapital))
                {
                    var provinceHistory = new ProvinceHistory(neighbour);
                    provinceHistories.Add(provinceHistory);
                    // TODO should be from model not from this loop
                    var firstPrediction = predictor.Predict(provinceHistory).First();

                    var provinceViewModel = new ProvinceViewModel
                    {
                        ProvinceName = neighbour,
                        FarmsViewModel = new NumericViewModel { Count = 1 },
                        SoldiersViewModel = new NumericViewModel { Count = 1 },
                        CultureViewModel = new CultureViewModel(),
                        ResourceViewModel = new ResourceViewModel(),
                        BuildPrediction = new BuildPredictionViewModel
                        {
                            Building = firstPrediction.Building,
                            TurnsLeft = firstPrediction.TurnsLeft
                        },
                    };
                    provinceViewModel.ProvinceRemoved += provinceViewModel_OnProvinceRemoved;
                    provinceViewModel.IsFirstTurn = true;

                    Provinces.Add(provinceViewModel);
                }
            }
        }
Example #24
0
        private static double ShowWeek(int week, int bias = int.MinValue)
        {
            int correctPredictions = 0;

            League NFLPreviousWeek = lb.BuildNFLLeague($"{DATAPATH}NFLStats_2018.xml", $"{DATAPATH}NFL_2018.xml", START_DATE.AddDays((week - 1) * 7));

            List<ITeam> allTeams = NFL.Conferences.SelectMany(c => c.Divisions).SelectMany(d => d.Teams).ToList();
            List<IGame> weekGames = new List<IGame>();

            foreach(Team t in allTeams)
            {
                foreach (Game g in t.Games)
                {
                    if (!weekGames.Exists(gg => gg.HomeTeam == g.HomeTeam)) {
                        if (g.Week == week)
                            weekGames.Add(g);
                    }
                }
            }

            foreach(Game g in weekGames)
            {
                ITeam hometeam = NFLPreviousWeek.GetTeam(g.HomeTeam);
                ITeam awayteam = NFLPreviousWeek.GetTeam(g.AwayTeam);
                Predictor P = new Predictor(NFLPreviousWeek);
                /*
                int prediction;
                if (bias == int.MinValue)
                    prediction = P.Predict(hometeam, awayteam);
                else
                    prediction = P.Predict(hometeam, awayteam, bias);
                    */
                int prediction = P.Predict(hometeam, awayteam);

                string predictedWinner;
                if (prediction > 0)
                    predictedWinner = hometeam.NickName;
                else if (prediction < 0)
                    predictedWinner = awayteam.NickName;
                else
                    predictedWinner = PickRandom(hometeam, awayteam);

                if (g.Date < DateTime.Now)
                {
                    string winner;
                    if (g.AwayPoints > g.HomePoints) winner = awayteam.NickName;
                    else if (g.AwayPoints < g.HomePoints) winner = hometeam.NickName;
                    else winner = "TIE";

                    string correct = (winner == predictedWinner) ? "YES" : "NO ";
                    if (correct == "YES") correctPredictions++;
                    Console.WriteLine("{4}: {0} {2} at {1} {3}", awayteam.NickName, hometeam.NickName, g.AwayPoints, g.HomePoints, correct);
                }
                else
                {
                    Console.WriteLine("{0,10} at {1,10}: {2}", awayteam.NickName, hometeam.NickName, predictedWinner);
                }
            }
            if (correctPredictions > 0)
                Console.WriteLine("\nCorrectly predicted {0} out of {1} games", correctPredictions, weekGames.Count);

            return (correctPredictions * 1.0 / weekGames.Count);
        }
Example #25
0
        protected override void Predict(string[] args)
        {
            var prediction = Predictor.Predict <BCData, BCPrediction>(MlContext, args[(int)CommandLineArguments.INPUT_FILE], args[(int)CommandLineArguments.OUTPUT_FILE]);

            Console.WriteLine($"Likely not happy: {prediction.Probability * 100:##.#}%");
        }
        protected override void Predict(string[] args)
        {
            var prediction = Predictor.Predict <EmploymentHistory, EmploymentHistoryPrediction>(MlContext, args[(int)CommandLineArguments.INPUT_FILE], args[(int)CommandLineArguments.OUTPUT_FILE]);

            Console.WriteLine($"Predicted Duration (in months): {prediction.DurationInMonths:0.#}");
        }
Example #27
0
        public static void Main(string[] args)
        {
            string _filepath = "";

            var date = ExecutionDateHelper.GetLastExecutionDate();

            try
            {
                Console.WriteLine("\nDownloading csv stared...");
                var csv = new CsvDownloader();
                _filepath = csv.GetScoresCsv(DateTime.Now);
                logger.Info("Csv file has been saved as: " + _filepath);
                Console.WriteLine("Downloading csv succeeded. File is located in: {0}", _filepath);
            }
            catch (Exception e)
            {
                logger.Error("Error while downloading csv file", e);
                Console.WriteLine("Downloading csv file failed.");
                return;
            }

            try
            {
                Console.WriteLine("\nParsing csv started...");
                var cs = new CsvService();
                var n  = cs.InsertScores(_filepath, date);
                logger.Info(n + " score records have been added to database");
                Console.WriteLine("Inserting scores to database succeeded.\n{0} records have been added", n);
                if (n > 0)
                {
                    ExecutionDateHelper.SetExecutionDate();
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while inserting scores.", e);
                Console.WriteLine("Inserting scores to database failed.");
                return;
            }

            try
            {
                Console.WriteLine("\nPredicting scores started...");
                var    p         = new Predictor();
                string season    = SeasonHelper.GetCurrentSeason(DateTime.Now);
                int    matchweek = MatchweekHelper.GetCurrentMatchweek();

                if (matchweek == 0 || matchweek == 38)
                {
                    season    = SeasonHelper.GetNextSeason(season);
                    matchweek = 1;
                }

                logger.InfoFormat("Prediction will be run for matchweek {0} of season {1}", matchweek, season);
                List <Match> sc = p.Predict(season, matchweek);
                logger.Info("Prediction finished successfully");
                Console.WriteLine("Predicting process succeeded.");
                Console.WriteLine("Predicted scores are:\n");
                foreach (var s in sc)
                {
                    Console.WriteLine("{0} - {1}\t\t{2}:{3}", s.Team1.Name, s.Team.Name, s.HomeGoalsPredicted, s.AwayGoalsPredicted);
                }
            }
            catch (Exception e)
            {
                logger.Error("Error while predicting.", e);
                Console.WriteLine("\nAn error occured while predicting scores.");
                return;
            }

            logger.Info("Bye");
            Console.WriteLine("\nProgram finished.");
        }
Example #28
0
 internal object Predict(FeatureObject feature)
 {
     return(_predictor.Predict(feature, WeightArray));
 }
Example #29
0
        protected override void Predict(string[] args)
        {
            var prediction = Predictor.Predict <JpegArtifactorDetectorData, JpegArtifactorDetectorPrediction>(MlContext, args[(int)CommandLineArguments.INPUT_FILE], args[(int)CommandLineArguments.OUTPUT_FILE]);

            Console.WriteLine($"Has Jpeg Artifacts: {prediction.ContainsJpegArtifacts:0.#}");
        }