예제 #1
0
        public static MLBBaseballBatter FromCsv(string csvLine)
        {
            string[]          values            = csvLine.Split(',');
            MLBBaseballBatter mlbBaseballBatter = new MLBBaseballBatter();

            mlbBaseballBatter.InductedToHallOfFame = Convert.ToBoolean(values[0]);
            mlbBaseballBatter.OnHallOfFameBallot   = Convert.ToBoolean(values[1]);
            mlbBaseballBatter.FullPlayerName       = Convert.ToString(values[2]);
            mlbBaseballBatter.YearsPlayed          = float.Parse(values[3], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.AB                 = float.Parse(values[4], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.R                  = float.Parse(values[5], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.H                  = float.Parse(values[6], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.Doubles            = float.Parse(values[7], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.Triples            = float.Parse(values[8], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.HR                 = float.Parse(values[9], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.RBI                = float.Parse(values[10], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.SB                 = float.Parse(values[11], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.BattingAverage     = float.Parse(values[12], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.SluggingPct        = float.Parse(values[13], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.AllStarAppearances = float.Parse(values[14]);
            mlbBaseballBatter.MVPs               = float.Parse(values[15], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.TripleCrowns       = float.Parse(values[16], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.GoldGloves         = float.Parse(values[17], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.MajorLeaguePlayerOfTheYearAwards = float.Parse(values[18], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.TB = float.Parse(values[19], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.TotalPlayerAwards = float.Parse(values[20], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.LastYearPlayed    = float.Parse(values[21], System.Globalization.NumberStyles.Any);
            mlbBaseballBatter.ID = Convert.ToString(values[22]);

            return(mlbBaseballBatter);
        }
예제 #2
0
        public static MLBBaseballBatter GetBaseballBatterFromLuceneDocument(Document document)
        {
            var mlbBaseballBatter = new MLBBaseballBatter
            {
                ID             = document.GetField("Id").GetStringValue(),
                FullPlayerName = document.GetField("FullPlayerName").GetStringValue(),
                YearsPlayed    = (float)document.GetField("YearsPlayed").GetSingleValue(),
                AB             = (float)document.GetField("AB").GetSingleValue(),
                R                  = (float)document.GetField("R").GetSingleValue(),
                H                  = (float)document.GetField("H").GetSingleValue(),
                Doubles            = (float)document.GetField("Doubles").GetSingleValue(),
                Triples            = (float)document.GetField("Triples").GetSingleValue(),
                HR                 = (float)document.GetField("HR").GetSingleValue(),
                RBI                = (float)document.GetField("RBI").GetSingleValue(),
                SB                 = (float)document.GetField("SB").GetSingleValue(),
                BattingAverage     = (float)document.GetField("BattingAverage").GetSingleValue(),
                SluggingPct        = (float)document.GetField("SluggingPct").GetSingleValue(),
                AllStarAppearances = (float)document.GetField("AllStarAppearances").GetSingleValue(),
                MVPs               = (float)document.GetField("MVPs").GetSingleValue(),
                TripleCrowns       = (float)document.GetField("TripleCrowns").GetSingleValue(),
                GoldGloves         = (float)document.GetField("GoldGloves").GetSingleValue(),
                MajorLeaguePlayerOfTheYearAwards = (float)document.GetField("MajorLeaguePlayerOfTheYearAwards").GetSingleValue(),
                TB = (float)document.GetField("TB").GetSingleValue(),
                TotalPlayerAwards = (float)document.GetField("TotalPlayerAwards").GetSingleValue(),
                LastYearPlayed    = (float)document.GetField("LastYearPlayed").GetSingleValue(),
            };

            return(mlbBaseballBatter);
        }
예제 #3
0
        public MLBBaseballBatter CalculateStatisticsProratedBySeason(int numberOfSeasons)
        {
            var batter = new MLBBaseballBatter
            {
                FullPlayerName       = this.FullPlayerName,
                ID                   = this.ID,
                InductedToHallOfFame = false,
                LastYearPlayed       = this.LastYearPlayed,
                OnHallOfFameBallot   = false,
                YearsPlayed          = numberOfSeasons * 1f,
                AB                   = (this.AB / this.YearsPlayed) * numberOfSeasons,
                R       = (this.R / this.YearsPlayed) * numberOfSeasons,
                H       = (this.H / this.YearsPlayed) * numberOfSeasons,
                Doubles = (this.Doubles / this.YearsPlayed) * numberOfSeasons,
                Triples = (this.Triples / this.YearsPlayed) * numberOfSeasons,
                HR      = (float)Math.Round(
                    ((this.HR / this.YearsPlayed) * numberOfSeasons), 0,
                    MidpointRounding.AwayFromZero),
                RBI            = (this.RBI / this.YearsPlayed) * numberOfSeasons,
                SB             = (this.SB / this.YearsPlayed) * numberOfSeasons,
                BattingAverage =
                    (float)
                    (
                        ((this.H / this.YearsPlayed) * numberOfSeasons) /
                        ((this.AB / this.YearsPlayed) * numberOfSeasons)
                    ),
                AllStarAppearances = (float)Math.Round(
                    (Decimal)(this.AllStarAppearances / this.YearsPlayed) * numberOfSeasons,
                    0,
                    MidpointRounding.AwayFromZero),
                MVPs         = (this.MVPs / this.YearsPlayed) * numberOfSeasons,
                TripleCrowns = (this.TripleCrowns / this.YearsPlayed) * numberOfSeasons,
                GoldGloves   = (float)Math.Round(
                    ((this.GoldGloves / this.YearsPlayed) * numberOfSeasons), 0, MidpointRounding.AwayFromZero),
                MajorLeaguePlayerOfTheYearAwards = (this.MajorLeaguePlayerOfTheYearAwards / this.YearsPlayed) * numberOfSeasons,
                TB = (float)Math.Round(
                    ((this.TB / this.YearsPlayed) * numberOfSeasons), 0, MidpointRounding.AwayFromZero),
                TotalPlayerAwards = (float)Math.Round(
                    (this.TotalPlayerAwards / this.YearsPlayed) * numberOfSeasons, 0, MidpointRounding.AwayFromZero),
                SluggingPct = TB / AB
            };

            return(batter);
        }
        public Task <List <MLBBaseballBatter> > GetSampleBaseballData()
        {
            // Return sample baseball players (batters)
            // Mix of fictitious, active & retired players of all skills

            // Note: In a production system this service would load the list of batters
            // from distributed persisted storage, searched in information retrieval engine (i.e. Azure Search, Lucene),
            // a relational database etc.

            // Load MLB baseball batters from local CSV file

            var assembly = typeof(Test_Blazor_MLNet.Shared.Util).Assembly;

            var lines = ReadLines(() => Util.GetBaseballDataStream(), Encoding.UTF8);

            var batters = lines
                          .Skip(1)
                          .Select(v => MLBBaseballBatter.FromCsv(v));

            return(Task.FromResult(
                       batters.ToList()
                       ));;
        }
예제 #5
0
        public static PredictionData GetMLBBaseballBatterSeasonPredictions(string algorithmName, MLBBaseballBatter mLBBaseballBatter, List <MLBBaseballBatter> selectedBatterSeasons)
        {
            // Object to return
            var predictionData = new PredictionData();

            var _predictionEngineInductedToHallOfFameKey = $"Inducted-{algorithmName}";
            var _predictionEngineOnHallOfFameBallotKey   = $"OnHallOfFameBallot-{algorithmName}";

            var mlbBaseballBatterSeasonPredictions = new List <MLBBaseballBatterSeasonPrediction>();

            //if (algorithmName != "StackedEnsemble")
            //{
            //    PredictionEngine<MLBBaseballBatter, MLBHOFPrediction> _predictionEngineInductedToHallOfFame =
            //        Util.GetPredictionEngine(mlContext, "InductedToHallOfFame", algorithmName);
            //    PredictionEngine<MLBBaseballBatter, MLBHOFPrediction> _predictionEngineOnHallOfFameBallot =
            //        Util.GetPredictionEngine(mlContext, "OnHallOfFameBallot", algorithmName);

            //    for (int i = 0; i != mLBBaseballBatter.YearsPlayed; i++)
            //    {
            //        var season = i + 1;
            //        var batterSeason = selectedBatterSeasons.Where(s => Convert.ToInt32(s.YearsPlayed) == season).First();
            //        var onHallOfFameBallotPrediction = _predictionEngineOnHallOfFameBallot.Predict(batterSeason);
            //        var inductedToHallOfFamePrediction = _predictionEngineInductedToHallOfFame.Predict(batterSeason);

            //        var seasonPrediction = new MLBBaseballBatterSeasonPrediction
            //        {
            //            SeasonNumber = season,
            //            FullPlayerName = mLBBaseballBatter.FullPlayerName,
            //            InductedToHallOfFamePrediction = inductedToHallOfFamePrediction.Prediction,
            //            InductedToHallOfFameProbability = Math.Round(inductedToHallOfFamePrediction.Probability, 5, MidpointRounding.AwayFromZero),
            //            OnHallOfFameBallotPrediction = onHallOfFameBallotPrediction.Prediction,
            //            OnHallOfFameBallotProbability = Math.Round(onHallOfFameBallotPrediction.Probability, 5, MidpointRounding.AwayFromZero)
            //        };

            //        seasonPrediction.InductedToHallOfFameProbabilityLabel = (seasonPrediction.InductedToHallOfFameProbability == 0f) ? "N/A" : seasonPrediction.InductedToHallOfFameProbability.ToString();
            //        seasonPrediction.OnHallOfFameBallotProbabilityLabel = (seasonPrediction.OnHallOfFameBallotProbability == 0f) ? "N/A" : seasonPrediction.OnHallOfFameBallotProbability.ToString();


            //        mlbBaseballBatterSeasonPredictions.Add(seasonPrediction);
            //    }
            //}
            //else
            //{
            var chartData = new List <PredictionChartData>();

            var algorithNamesForEnsemble = new List <string> {
                "FastTree", "GeneralizedAdditiveModels", "LightGbm",
                "LogisticRegression", "StochasticGradientDescentCalibrated"
            };

            // If algorithm is selected that does not return probabilities add it
            var exists = algorithNamesForEnsemble.Exists(a => a.Contains(algorithmName));

            if ((!exists) && (algorithmName != "StackedEnsemble"))
            {
                algorithNamesForEnsemble.Add(algorithmName);
            }

            for (int i = 0; i != mLBBaseballBatter.YearsPlayed; i++)
            {
                var season       = i + 1;
                var batterSeason = selectedBatterSeasons.Where(s => Convert.ToInt32(s.YearsPlayed) == season).First();
                MLBBaseballBatterSeasonPrediction seasonPrediction;

                var probabilitiesInducted           = new List <AlgorithmPrediction>();
                var probabilitiesOnHallOfFameBallot = new List <AlgorithmPrediction>();

                foreach (var algorithmNameEnsemble in algorithNamesForEnsemble)
                {
                    PredictionEngine <MLBBaseballBatter, MLBHOFPrediction> _predictionEngineInductedToHallOfFameEnsemble =
                        Util.GetPredictionEngine(mlContext, "InductedToHallOfFame", algorithmNameEnsemble);
                    PredictionEngine <MLBBaseballBatter, MLBHOFPrediction> _predictionEngineOnHallOfFameBallotEnsemble =
                        Util.GetPredictionEngine(mlContext, "OnHallOfFameBallot", algorithmNameEnsemble);

                    var onHallOfFameBallotPredictionEnsemble   = _predictionEngineOnHallOfFameBallotEnsemble.Predict(batterSeason);
                    var inductedToHallOfFamePredictionEnsemble = _predictionEngineInductedToHallOfFameEnsemble.Predict(batterSeason);

                    probabilitiesInducted.Add(
                        new AlgorithmPrediction
                    {
                        AlgorithmName = algorithmNameEnsemble,
                        Prediction    = inductedToHallOfFamePredictionEnsemble.Prediction,
                        Probability   = inductedToHallOfFamePredictionEnsemble.Probability
                    });
                    probabilitiesOnHallOfFameBallot.Add(
                        new AlgorithmPrediction
                    {
                        AlgorithmName = algorithmNameEnsemble,
                        Prediction    = onHallOfFameBallotPredictionEnsemble.Prediction,
                        Probability   = onHallOfFameBallotPredictionEnsemble.Probability
                    });

                    // Only add probabilities for algorithms that return probabilities
                    if (algorithmName == "FastTree" || algorithmName == "GeneralizedAdditiveModels" || algorithmName == "LightGbm" || algorithmName == "LogisticRegression" ||
                        algorithmName == "StochasticGradientDescentCalibrated" || algorithmName == "StackedEnsemble")
                    {
                        chartData.Add(new PredictionChartData
                        {
                            Algorithm = algorithmNameEnsemble,
                            InductedToHallOfFameProbability = inductedToHallOfFamePredictionEnsemble.Probability,
                            OnHallOfFameBallotProbability   = onHallOfFameBallotPredictionEnsemble.Probability,
                            SeasonPlayed = season
                        });
                    }
                }     // EOF Foreach Algorithm Ensemble


                if (algorithmName == "StackedEnsemble")
                {
                    // Average out predictions for ensemble
                    float probabilityInducted           = probabilitiesInducted.Select(a => a.Probability).Sum() / 5;
                    float probabilityOnHallOfFameBallot = probabilitiesOnHallOfFameBallot.Select(a => a.Probability).Sum() / 5;

                    seasonPrediction = new MLBBaseballBatterSeasonPrediction
                    {
                        SeasonNumber   = season,
                        FullPlayerName = mLBBaseballBatter.FullPlayerName,
                        InductedToHallOfFamePrediction  = (probabilityInducted > 0.5f) ? true : false,
                        InductedToHallOfFameProbability = Math.Round(probabilityInducted, 5, MidpointRounding.AwayFromZero),
                        OnHallOfFameBallotPrediction    = (probabilityOnHallOfFameBallot > 0.5f) ? true : false,
                        OnHallOfFameBallotProbability   = Math.Round(probabilityOnHallOfFameBallot, 5, MidpointRounding.AwayFromZero)
                    };
                }
                else
                {
                    // Average out predictions for ensemble
                    float probabilityInducted           = probabilitiesInducted.Where(a => a.AlgorithmName == algorithmName).FirstOrDefault()?.Probability ?? 0f;
                    float probabilityOnHallOfFameBallot = probabilitiesOnHallOfFameBallot.Where(a => a.AlgorithmName == algorithmName).FirstOrDefault()?.Probability ?? 0f;

                    seasonPrediction = new MLBBaseballBatterSeasonPrediction
                    {
                        SeasonNumber   = season,
                        FullPlayerName = mLBBaseballBatter.FullPlayerName,
                        InductedToHallOfFamePrediction  = probabilitiesInducted.Where(a => a.AlgorithmName == algorithmName).FirstOrDefault().Prediction,
                        InductedToHallOfFameProbability = Math.Round(probabilityInducted, 5, MidpointRounding.AwayFromZero),
                        OnHallOfFameBallotPrediction    = probabilitiesOnHallOfFameBallot.Where(a => a.AlgorithmName == algorithmName).FirstOrDefault().Prediction,
                        OnHallOfFameBallotProbability   = Math.Round(probabilityOnHallOfFameBallot, 5, MidpointRounding.AwayFromZero)
                    };
                }

                seasonPrediction.InductedToHallOfFameProbabilityLabel = (seasonPrediction.InductedToHallOfFameProbability == 0f) ? "N/A" : seasonPrediction.InductedToHallOfFameProbability.ToString();
                seasonPrediction.OnHallOfFameBallotProbabilityLabel   = (seasonPrediction.OnHallOfFameBallotProbability == 0f) ? "N/A" : seasonPrediction.OnHallOfFameBallotProbability.ToString();
                mlbBaseballBatterSeasonPredictions.Add(seasonPrediction);

                // Add StackedEnsemble always to the ChartData
                chartData.Add(new PredictionChartData
                {
                    Algorithm = "StackedEnsemble",
                    InductedToHallOfFameProbability = seasonPrediction.InductedToHallOfFameProbability,
                    OnHallOfFameBallotProbability   = seasonPrediction.OnHallOfFameBallotProbability,
                    SeasonPlayed = season
                });
                //}

                // Get the min/max for each season
                var chardDataMin =
                    chartData
                    .GroupBy(c => new
                {
                    c.SeasonPlayed
                })
                    .Select(gcs => new PredictionChartDataMinMax()
                {
                    Algorithm    = "OnHallOfFameBallot",
                    SeasonPlayed = gcs.Key.SeasonPlayed,
                    Min          = gcs.Min(g => g.OnHallOfFameBallotProbability),
                    Max          = gcs.Max(g => g.OnHallOfFameBallotProbability)
                }).ToList();
                var chardDataMax =
                    chartData
                    .GroupBy(c => new
                {
                    c.SeasonPlayed
                })
                    .Select(gcs => new PredictionChartDataMinMax()
                {
                    Algorithm    = "InductedToHallOfFame",
                    SeasonPlayed = gcs.Key.SeasonPlayed,
                    Min          = gcs.Min(g => g.InductedToHallOfFameProbability),
                    Max          = gcs.Max(g => g.InductedToHallOfFameProbability)
                }).ToList();

                predictionData.ChartData = chartData;

                chardDataMin.AddRange(chardDataMax);
                predictionData.ChartDataMinMax = chardDataMin;
            }

            predictionData.MLBBaseballBatterSeasonPredictions = mlbBaseballBatterSeasonPredictions;

            return(predictionData);
        }