Пример #1
0
        static void Main(string[] args)
        {
            var dataset     = @"C:\Users\mert.ceken\source\repos\190610_salary_pred\190610_salary_pred\maas-veri.csv";
            var testDataset = @"C:\Users\mert.ceken\source\repos\190610_salary_pred\190610_salary_pred\maas-veri-test.csv";

            var pipeline = new LearningPipeline
            {
                new TextLoader(dataset).CreateFrom <SalaryData>(useHeader: true, separator: ','),
                new ColumnConcatenator("Features", "YILLAR"),
                new GeneralizedAdditiveModelRegressor()
            };

            Console.WriteLine("..........Eğitiliyor..........");
            var model = pipeline.Train <SalaryData, SalaryPrediction>();

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("..........Değerlendiriliyor..........");
            var testData = new TextLoader(testDataset).CreateFrom <SalaryData>(useHeader: true, separator: ',');

            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Karekök Ortalama: {metrics.Rms}");
            Console.WriteLine($"R^2: {metrics.RSquared}");

            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("..........Tahmin..........");
            var prediction = model.Predict(new SalaryData {
                YILLAR = TAHMIN_EDILECEK_YIL
            });

            Console.WriteLine($"{TAHMIN_EDILECEK_YIL} yıl sonraki maaşınız {String.Format("{0:C}", prediction.PredictedSalary)}");

            Console.ReadLine();
        }
Пример #2
0
        static void Main(string[] args)
        {
            var pipeline = new LearningPipeline
            {
                new TextLoader("SalaryData.csv").CreateFrom <SalaryData>(useHeader: true, separator: ','),
                new ColumnConcatenator("Features", "YearsExperience"),
                new GeneralizedAdditiveModelRegressor()
            };

            Console.WriteLine("--------------Training----------------");
            var model = pipeline.Train <SalaryData, SalaryPrediction>();

            // Evaluate
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("--------------Evaluating----------------");
            var testData = new TextLoader("SalaryData-test.csv").CreateFrom <SalaryData>(useHeader: true, separator: ',');

            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Root Mean Squared: {metrics.Rms}");
            Console.WriteLine($"R^2: {metrics.RSquared}");

            // Predict
            Console.WriteLine(Environment.NewLine);
            Console.WriteLine("--------------Predicting----------------");
            var prediction = model.Predict(new SalaryData {
                YearsExperience = PREDICTION_YEARS
            });

            Console.WriteLine($"After {PREDICTION_YEARS} years you would earn around {String.Format("{0:C}", prediction.PredictedSalary)}");

            Console.ReadLine();
        }
Пример #3
0
        static void Main(string[] args)
        {
            var pipeline = new LearningPipeline();

            pipeline.Add(new TextLoader("SalaryData.csv")
                         .CreateFrom <SalaryData>(useHeader: true, separator: ','));
            pipeline.Add(new ColumnConcatenator("Features", "YearsExperience"));
            pipeline.Add(new GeneralizedAdditiveModelRegressor());

            var model = pipeline.Train <SalaryData, SalaryPrediction>();

            var testData = new TextLoader("SalaryData-test.csv")
                           .CreateFrom <SalaryData>(useHeader: true, separator: ',');

            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"RMS - {metrics.Rms}");
            Console.WriteLine($"R^2 - {metrics.RSquared}");

            var prediction = model.Predict(new SalaryData {
                YearsExperience = 7
            });

            Console.WriteLine($"Salary - {prediction.PredictedSalary}");

            Console.ReadLine();
        }
        /// <summary>
        /// Ussing passed testing data and model, it calculates model's accuracy.
        /// </summary>
        /// <returns>Accuracy of the model.</returns>
        public RegressionMetrics Evaluate(PredictionModel <BikeSharingDemandSample, BikeSharingDemandPrediction> model, string testDataLocation)
        {
            var testData = new TextLoader(testDataLocation).CreateFrom <BikeSharingDemandSample>(useHeader: true, separator: ',');
            var metrics  = new RegressionEvaluator().Evaluate(model, testData);

            return(metrics);
        }
Пример #5
0
        public static void Trainer()
        {
            var pipeline = new LearningPipeline
            {
                new TextLoader(trainingDataFilePath).CreateFrom <InsurerBillData>(useHeader: true, separator: ','),
                //new ColumnCopier(("Score", "Label")),
                new CategoricalOneHotVectorizer("ChannelName", "ProductId"),
                new ColumnConcatenator("Features", "ChannelName", "ProductId"),
                new FastTreeRegressor()
                //new GeneralizedAdditiveModelRegressor(),
            };

            var model = pipeline.Train <InsurerBillData, PredictedInsurerBill>();

            var testData = new TextLoader(testDataFilePath).CreateFrom <InsurerBillData>(useHeader: true, separator: ',');

            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"RMS - {metrics.Rms}");
            Console.WriteLine($"R^2 - {metrics.RSquared}");

            var test = new InsurerBillData {
                ChannelName = ""
            };
            var prediction = model.Predict(test);

            Console.WriteLine($"Predicted SPV - {prediction.SPV}");

            Console.ReadLine();
        }
Пример #6
0
        static void Main(string[] args)
        {
            var pipeline = new LearningPipeline();

            pipeline.Add(new TextLoader("SalaryData.csv").CreateFrom <SalaryData>(useHeader: true, separator: ','));
            pipeline.Add(new ColumnConcatenator("Features", "YearsExperience"));
            pipeline.Add(new GeneralizedAdditiveModelRegressor());

            var model = pipeline.Train <SalaryData, SalaryPrediction>();

            var testData = new TextLoader("SalaryData-test.csv").CreateFrom <SalaryData>(useHeader: true, separator: ',');

            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine("RMS - " + metrics.Rms);
            Console.WriteLine("R^2 - " + metrics.RSquared);

            float yearsExperience = 7;

            var prediction = model.Predict(new SalaryData()
            {
                YearsExperience = yearsExperience
            });

            Console.WriteLine("Salary prediction for employee with " + yearsExperience + " years experience is " + prediction.PredictedSalary);

            Console.ReadLine();
        }
Пример #7
0
        public static void GetMyPrediction()
        {
            Console.WriteLine("Begin ML.NET demo run");
            Console.WriteLine("Income from age, sex, politics");
            var    pipeline = new LearningPipeline();
            string dataPath = AppDomain.CurrentDomain.BaseDirectory + "/PeopleData.txt";

            pipeline.Add(new TextLoader(dataPath).
                         CreateFrom <myLottery>(separator: ' '));
            pipeline.Add(new ColumnCopier(("Income", "Label")));
            //pipeline.Add(new CategoricalOneHotVectorizer("Politic"));
            pipeline.Add(new ColumnConcatenator("Features", "pre10",
                                                "pre9", "pre8", "pre7", "pre6", "pre5", "pre4", "pre3"
                                                , "pre2", "pre1"));
            var sdcar = new StochasticDualCoordinateAscentRegressor();

            sdcar.MaxIterations     = 1000;
            sdcar.NormalizeFeatures = NormalizeOption.Auto;
            pipeline.Add(sdcar);
            // pipeline.N
            Console.WriteLine("\nStarting training \n");
            var model = pipeline.Train <myLottery, myPrediction>();

            Console.WriteLine("\nTraining complete \n");
            string modelPath = AppDomain.CurrentDomain.BaseDirectory + "/IncomeModel.zip";

            Task.Run(async() =>
            {
                await model.WriteAsync(modelPath);
            }).GetAwaiter().GetResult();
            var testData = new TextLoader(dataPath).
                           CreateFrom <myLottery>(separator: ' ');
            var    evaluator = new RegressionEvaluator();
            var    metrics   = evaluator.Evaluate(model, testData);
            double rms       = metrics.Rms;

            Console.WriteLine("Root mean squared error = " +
                              rms.ToString("F4"));
            Console.WriteLine("Income age 40 conservative male: ");
            myLottery newPatient = new myLottery()
            {
                pre10 = 6824298f,
                pre9  = 2589916f,
                pre8  = 2602089f,
                pre7  = 2915497f,
                pre6  = 8507838f,
                pre5  = 7679324f,
                pre4  = 607461f,
                pre3  = 5806877,
                pre2  = 6776442f,
                pre1  = 9975203
            };
            myPrediction prediction = model.Predict(newPatient);
            float        predIncome = prediction.Income;

            Console.WriteLine("Predicted income = $" +
                              predIncome.ToString("F2"));
            Console.WriteLine("\nEnd ML.NET demo");
            Console.ReadLine();
        }
Пример #8
0
        internal override ReturnObj <RegressionMetrics> EvaluateModel <T, TK>(PredictionModel <T, TK> model, string testDataFilePath)
        {
            var evaluator = new RegressionEvaluator();

            var testData = new TextLoader(testDataFilePath).CreateFrom <T>();

            return(new ReturnObj <RegressionMetrics>(evaluator.Evaluate(model, testData)));
        }
Пример #9
0
        private static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFaresPrediction> model)
        {
            var testData              = new TextLoader(_testdatapath).CreateFrom <TaxiTrip>(useHeader: true, separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"RSquared = {metrics.RSquared}");
        }
Пример #10
0
        public RegressionMetrics EvaluateModel(PredictionModel <Fatalities, FatalitiesPrediction> model)
        {
            var testData              = new TextLoader(TestDataPath).CreateFrom <Fatalities>(useHeader: true, separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            return(metrics);
        }
Пример #11
0
        public static double Evaluate(PredictionModel <WorldCupData, WorldCupPrediction> model)
        {
            var testData              = new TextLoader(_testDataPath).CreateFrom <WorldCupData>(useHeader: true, separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            return(metrics.Rms);
        }
Пример #12
0
        static void Main(string[] args)
        {
            //https://www.youtube.com/watch?v=8gVhJKszzzI
            #region
            //Setup the algorithm
            //LearningPipeline from Microsoft.ML;
            //TextLoader from Microsoft.ML.Data
            //ColumnConcatenator from Microsoft.ML.Transforms;
            //GeneralizedAdditiveModelRegressor from Microsoft.ML.Trainers;

            //TextLoader connects to CSV file
            //separator (delimiter)  needs single quotes for some reason
            //Create from is generic so can take any generic derrived type
            //ColumnConCatenator concatates your input data into one column, calls it 'features', and pass in the column to this - we only have one - YearsExperience
            //error I got - features needed to be capital first as per namign convention - threw exception when not
            #endregion
            var pipeline = new LearningPipeline();
            pipeline.Add(new TextLoader("SalaryData.csv").CreateFrom <SalaryData>(useHeader: true, separator: ','));
            pipeline.Add(new ColumnConcatenator("Features", "YearsExperience"));
            pipeline.Add(new GeneralizedAdditiveModelRegressor());

            #region
            //call train method on the pipelien will train on the data it has
            //object is generic derrived also
            //two arguments - one is data input, next is dataoutput
            //requires the data input in one column
            #endregion
            var model = pipeline.Train <SalaryData, SalaryPrediction>();
            #region
            //testing the effectiveness of the model
            //RegressionEvaluator from Microsoft.ML.Models
            //map to a newfile called SalaryData-test.csv which holds the test data set (not the  cross validation data set)
            //we can use this to stop overfitting / other errors
            //RegressionEvaluator - call Evaluate method on this and it will give you... metrics to checkl teh effectiveness of the model
            //the above method requires the model and test data passing in to check how effective it has been
            //the best evaluator metrics are the root mean squared and the r squared values )
            //RMS gives the average actual value our model was out by (it gives on average $4417)
            //The R^2 vlaue is teh value I have been seeign in the course - how far the actual values in the test data are from the relative model data - the total error - closer to 1, teh better your model is... there are some problems with this value ( I am guessin potential overfitting closer to 1)
            #endregion
            var testData  = new TextLoader("SalaryData-test.csv").CreateFrom <SalaryData>(useHeader: true, separator: ',');
            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"RMS - {metrics.Rms}");
            Console.WriteLine($"R^2 - {metrics.RSquared}");

            #region
            //predict on unseen data
            //call predict method on the model, pass in a new SalaryData model - set the Feature you want to predict on
            #endregion
            var prediction = model.Predict(new SalaryData {
                YearsExperience = 7
            });
            Console.WriteLine($"Predicted Salary for 7 = {prediction.PredictedSalary}");


            Console.ReadLine();
        }
Пример #13
0
        public void TrainAndPredictHousePriceModelTest()
        {
            string dataPath = GetDataPath("kc_house_data.csv");

            var pipeline = new LearningPipeline();

            pipeline.Add(new TextLoader <HousePriceData>(dataPath, useHeader: true, separator: ","));

            pipeline.Add(new ColumnConcatenator(outputColumn: "NumericalFeatures",
                                                "SqftLiving", "SqftLot", "SqftAbove", "SqftBasement", "Lat", "Long", "SqftLiving15", "SqftLot15"));

            pipeline.Add(new ColumnConcatenator(outputColumn: "CategoryFeatures",
                                                "Bedrooms", "Bathrooms", "Floors", "Waterfront", "View", "Condition", "Grade", "YearBuilt", "YearRenovated", "Zipcode"));

            pipeline.Add(new CategoricalOneHotVectorizer("CategoryFeatures"));
            pipeline.Add(new ColumnConcatenator(outputColumn: "Features",
                                                "NumericalFeatures", "CategoryFeatures"));
            pipeline.Add(new StochasticDualCoordinateAscentRegressor());

            PredictionModel <HousePriceData, HousePricePrediction> model = pipeline.Train <HousePriceData, HousePricePrediction>();

            HousePricePrediction prediction = model.Predict(new HousePriceData()
            {
                Bedrooms      = 3,
                Bathrooms     = 2,
                SqftLiving    = 1710,
                SqftLot       = 4697,
                Floors        = 1.5f,
                Waterfront    = 0,
                View          = 0,
                Condition     = 5,
                Grade         = 6,
                SqftAbove     = 1710,
                SqftBasement  = 0,
                YearBuilt     = 1941,
                YearRenovated = 0,
                Zipcode       = 98002,
                Lat           = 47.3048f,
                Long          = -122.218f,
                SqftLiving15  = 1030,
                SqftLot15     = 4705
            });

            Assert.InRange(prediction.Price, 260_000, 330_000);

            string testDataPath = GetDataPath("kc_house_test.csv");
            var    testData     = new TextLoader <HousePriceData>(testDataPath, useHeader: true, separator: ",");

            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Assert.InRange(metrics.L1, 85_000, 89_000);
            Assert.InRange(metrics.L2, 17_000_000_000, 19_000_000_000);
            Assert.InRange(metrics.Rms, 130_500, 135_000);
            Assert.InRange(metrics.LossFn, 17_000_000_000, 19_000_000_000);
            Assert.Equal(.8, metrics.RSquared, 1);
        }
Пример #14
0
 public static Task <RegressionMetrics> Evaluate(this PredictionModel <Sell, SellPrediction> model)
 {
     return(Task.Factory.StartNew(() =>
     {
         var dataLoader = new TextLoader(Files.LoadTestDataSet()).CreateFrom <Sell>(useHeader: true, separator: ',');
         var evaluator = new RegressionEvaluator();
         return evaluator.Evaluate(model, dataLoader);
     }));
 }
Пример #15
0
        /// <summary>
        /// モデルを評価します。
        /// </summary>
        /// <param name="model"></param>
        /// <param name="testDataPath"></param>
        private void Evaluate(PredictionModel <BostonHousingData, BostonHousingPrediction> model, string testDataPath)
        {
            var testData              = new TextLoader(testDataPath).CreateFrom <BostonHousingData>(true, ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");
            Console.WriteLine($"RSquared = {metrics.RSquared}");
        }
Пример #16
0
        private static void Evaluate(PredictionModel <PackageRelease, PackageReleasePrediction> model)
        {
            var testData = new TextLoader(_testdatapath).CreateFrom <PackageRelease>(useHeader: true, separator: ',');

            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");
        }
Пример #17
0
        private static void Evaluate(PredictionModel <Product, ProductSugars_100gPrediction> model)
        {
            var testData              = new TextLoader(_testdatapath).CreateFrom <Product>(useHeader: true, separator: _separator);
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");
            Console.WriteLine($"RSquared = {metrics.RSquared}");
        }
Пример #18
0
        public static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var testData              = new TextLoader(_testDataPath).CreateFrom <TaxiTrip>(separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");
            Console.WriteLine($"Rsquared = {metrics.RSquared}");
        }
Пример #19
0
        private static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var testData              = new TextLoader <TaxiTrip>(_testDataPath, useHeader: true, separator: ",");
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine("Rms=" + metrics.Rms);
            Console.WriteLine("RSquared = " + metrics.RSquared);
        }
Пример #20
0
        public static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var testData  = new TextLoader(_testDataPath).CreateFrom <TaxiTrip>(useHeader: true, separator: ',');
            var evaluator = new RegressionEvaluator();
            var metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine("PredictionModel quality metrics evaluation");
            Console.WriteLine($"Rms: {metrics.Rms}");
            Console.WriteLine($"RSquared: {metrics.RSquared}");
        }
Пример #21
0
        private static void Evaluate(PredictionModel <NodeObject, NodePrediction> model)
        {
            TextLoader testData = new TextLoader(_testdatapath).CreateFrom <NodeObject>(useHeader: true, separator: ',');

            RegressionEvaluator evaluator = new RegressionEvaluator();
            RegressionMetrics   metrics   = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");
            Console.WriteLine($"RSquared = {metrics.RSquared}");
        }
        private static void Evaluate(PredictionModel <ItemStock, itemStockQtyPrediction> model)
        {
            var testData              = new TextLoader(_Evaluatedatapath).CreateFrom <ItemStock>(useHeader: true, separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine($"Rms = {metrics.Rms}");

            Console.WriteLine($"RSquared = {metrics.RSquared}");
        }
        public RegressionMamlEvaluator(IHostEnvironment env, Arguments args)
            : base(args, env, MetadataUtils.Const.ScoreColumnKind.Regression, "RegressionMamlEvaluator")
        {
            Host.CheckUserArg(args.LossFunction != null, nameof(args.LossFunction), "Loss function must be specified.");

            var evalArgs = new RegressionEvaluator.Arguments();

            evalArgs.LossFunction = args.LossFunction;
            _evaluator            = new RegressionEvaluator(Host, evalArgs);
        }
Пример #24
0
        /// <summary>
        /// Evaluates scored regression data.
        /// </summary>
        /// <param name="data">The scored data.</param>
        /// <param name="labelColumnName">The name of the label column in <paramref name="data"/>.</param>
        /// <param name="scoreColumnName">The name of the score column in <paramref name="data"/>.</param>
        /// <returns>The evaluation results for these calibrated outputs.</returns>
        public RegressionMetrics Evaluate(IDataView data, string labelColumnName = DefaultColumnNames.Label, string scoreColumnName = DefaultColumnNames.Score)
        {
            Environment.CheckValue(data, nameof(data));
            Environment.CheckNonEmpty(labelColumnName, nameof(labelColumnName));
            Environment.CheckNonEmpty(scoreColumnName, nameof(scoreColumnName));

            var eval = new RegressionEvaluator(Environment, new RegressionEvaluator.Arguments()
            {
            });

            return(eval.Evaluate(data, labelColumnName, scoreColumnName));
        }
Пример #25
0
        private static void Evaluate(PredictionModel <HousePrice, HousePricePredicted> model)
        {
            var _testdatapath = @"pp-monthly-update-new-version.csv";
            var testData      = new TextLoader(_testdatapath).CreateFrom <HousePrice>(useHeader: false, separator: ',');
            var evaluator     = new RegressionEvaluator()
            {
                LabelColumn = "Price"
            };
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            Console.WriteLine(JsonConvert.SerializeObject(metrics, Formatting.Indented));
        }
Пример #26
0
        /// <summary>
        /// Evaluates the scored recommendation data.
        /// </summary>
        /// <param name="data">The scored data.</param>
        /// <param name="label">The name of the label column in <paramref name="data"/>.</param>
        /// <param name="score">The name of the score column in <paramref name="data"/>.</param>
        /// <returns>The evaluation results for these calibrated outputs.</returns>
        public RegressionEvaluator.Result Evaluate(IDataView data, string label = DefaultColumnNames.Label, string score = DefaultColumnNames.Score)
        {
            Host.CheckValue(data, nameof(data));
            Host.CheckNonEmpty(label, nameof(label));
            Host.CheckNonEmpty(score, nameof(score));

            var eval = new RegressionEvaluator(Host, new RegressionEvaluator.Arguments()
            {
            });

            return(eval.Evaluate(data, label, score));
        }
Пример #27
0
        private static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var testData = new TextLoader(_testdatapath).CreateFrom <TaxiTrip>(useHeader: true, separator: ',');

            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            // Rms should be around 2.795276
            Console.WriteLine("Rms=" + metrics.Rms);
            Console.WriteLine("RSquared = " + metrics.RSquared);
            Console.WriteLine();
        }
Пример #28
0
        /// <summary>
        /// 评估模型
        /// </summary>
        /// <param name="model"></param>
        public static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var testData              = new TextLoader(TestDataPath).CreateFrom <TaxiTrip>(useHeader: true, separator: ',');
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics metrics = evaluator.Evaluate(model, testData);

            // Rms should be around 2.795276
            //RMS是评估回归问题的一个指标。它越低,你的模型就越好。将以下代码添加到该Evaluate()函数中以打印模型的RMS。
            Console.WriteLine("Rms=" + metrics.Rms);
            //Squared是评估回归问题的另一个指标。RSquared将是介于0和1之间的值。越接近1,模型越好。将下面的代码添加到该Evaluate()函数中以打印模型的RSquared值。
            Console.WriteLine("RSquared = " + metrics.RSquared);
        }
Пример #29
0
        public static void GetMyPrediction()
        {
            Console.WriteLine("Begin ML.NET demo run");
            Console.WriteLine("Income from age, sex, politics");
            var    pipeline = new LearningPipeline();
            string dataPath = AppDomain.CurrentDomain.BaseDirectory + "/datamodel/PeopleData.txt";

            pipeline.Add(new TextLoader(dataPath).
                         CreateFrom <IncomeData>(separator: ','));
            pipeline.Add(new ColumnCopier(("Income", "Label")));
            pipeline.Add(new CategoricalOneHotVectorizer("Politic"));
            pipeline.Add(new ColumnConcatenator("Features", "Age",
                                                "Sex", "Politic"));
            var sdcar = new StochasticDualCoordinateAscentRegressor();

            sdcar.MaxIterations     = 1000;
            sdcar.NormalizeFeatures = NormalizeOption.Auto;
            pipeline.Add(sdcar);
            // pipeline.N
            Console.WriteLine("\nStarting training \n");
            var model = pipeline.Train <IncomeData, IncomePrediction>();

            Console.WriteLine("\nTraining complete \n");
            string modelPath = AppDomain.CurrentDomain.BaseDirectory + "/IncomeModel.zip";

            Task.Run(async() =>
            {
                await model.WriteAsync(modelPath);
            }).GetAwaiter().GetResult();
            var testData = new TextLoader(dataPath).
                           CreateFrom <IncomeData>(separator: ',');
            var    evaluator = new RegressionEvaluator();
            var    metrics   = evaluator.Evaluate(model, testData);
            double rms       = metrics.Rms;

            Console.WriteLine("Root mean squared error = " +
                              rms.ToString("F4"));
            Console.WriteLine("Income age 40 conservative male: ");
            IncomeData newPatient = new IncomeData()
            {
                Age     = 40.0f,
                Sex     = -1f,
                Politic = "conservative"
            };
            IncomePrediction prediction = model.Predict(newPatient);
            float            predIncome = prediction.Income * 10000;

            Console.WriteLine("Predicted income = $" +
                              predIncome.ToString("F2"));
            Console.WriteLine("\nEnd ML.NET demo");
            Console.ReadLine();
        } // Main
Пример #30
0
        private static void Evaluate(PredictionModel <TaxiTrip, TaxiTripFarePrediction> model)
        {
            var textData              = new TextLoader <TaxiTrip>(TestDataPath, useHeader: true, separator: ",");
            var evaluator             = new RegressionEvaluator();
            RegressionMetrics matrics = evaluator.Evaluate(model, textData);

            Console.WriteLine("Rms=" + matrics.Rms);
            Console.WriteLine("RSquared=" + matrics.RSquared);

            TaxiTripFarePrediction prediction01 = model.Predict(TestTrips.Trip1);

            Console.WriteLine("Predict fare : {0}, actual fare : 29.5", prediction01.fare_amount);
        }