none
Textbox shows zero in textbox on Single prediction execution.

    Question

  • Hello,

    I got in bit of a snag, when I tried to make a Machine Learning algorithm to check how much a car costs (Made for learning purposes), and when I train the set it trains with succes, and even evaluates correctly (no errors are shown). 

    BUT! When I try to make a single prediction my textbox drops a 0 as output. It does not show a predicted price for a car.

    I think that it's because my values are not send correctly, but I am not sure.

    Here are my codeblocks: 

    Machinelearning scriot:

    using System;
    using System.IO;
    using Microsoft.ML;
    using Microsoft.ML.Core.Data;
    using Microsoft.ML.Runtime.Api;
    using Microsoft.ML.Runtime.Data;
    using Microsoft.ML.Transforms;
    using Microsoft.ML.Transforms.Categorical;
    using Microsoft.ML.Transforms.Normalizers;
    using Microsoft.ML.Transforms.Text;
    
    
    namespace MachineLearning2.Scripts.MachineLearning
    {
    
        using Callback = Action<float>;
        class LearningModel
        {
            static readonly string CarPriceTrainPath = Path.Combine(Environment.CurrentDirectory, "Data", "CarPricesInput.csv");
            static readonly string CarModelPath = Path.Combine(Environment.CurrentDirectory, "Data", "TrainedModel.zip");
            static readonly string TestDataPath = Path.Combine(Environment.CurrentDirectory, "Data", "CarPricesTest.csv");
            static TextLoader TextLoader;
            public MLContext MLContext = new MLContext(seed: 0);
    
            private Callback _showValue;
           
    
            public LearningModel(Callback showValue)
            {
                _showValue = showValue;
            }
            public void TrainingModel()
            {
    
    
    
                
    
                TextLoader = MLContext.Data.TextReader(new TextLoader.Arguments()
                {
                    Separator = ",",
                    HasHeader = true,
                    Column = new[]
                    {
                     
                        new TextLoader.Column("Car_Price", DataKind.R4, 1),
                        new TextLoader.Column("Color_ID", DataKind.R4, 2),
                        new TextLoader.Column("Engine_ID", DataKind.R4, 3),
                        new TextLoader.Column("FuelType_ID", DataKind.R4, 4),
                        new TextLoader.Column("TotalPrice", DataKind.R4, 5),
      
                    }
                }
    );
                var model = Train(MLContext, CarPriceTrainPath);
    
                EvaluateData(MLContext, model);
    
            }
            public static ITransformer Train(MLContext MLContext, string CarPriceTrainPath)
            {
                IDataView DataView = TextLoader.Read(CarPriceTrainPath);
                var pipeline = MLContext.Transforms.CopyColumns("TotalPrice", "Label")
                .Append(MLContext.Transforms.Concatenate("Features", "Car_Price", "Color_ID", "Engine_ID", "FuelType_ID"))
                .Append(MLContext.Regression.Trainers.FastTree());
                var Model = pipeline.Fit(DataView);
                SaveModelAsFile(MLContext, Model);
               
                return Model;
               
            }
    
    
            private static void EvaluateData(MLContext MLContext, ITransformer TrainedModel)
            {
                IDataView DataView = TextLoader.Read(TestDataPath);
                var predictions = TrainedModel.Transform(DataView);
                var metrics = MLContext.Regression.Evaluate(predictions, "Label", "Score");
                
    
    
            }
            public void ReceiveData(string CarPrice, string ColorID, string EngineID, string FuelTypeID)
            {
                float InputCarPrice = float.Parse(CarPrice);
                float InputColorID = float.Parse(CarPrice);
                float InpuEngineID = float.Parse(CarPrice);
                float InputFuelTypeID = float.Parse(CarPrice);
    
                TestSinglePrediction(InputCarPrice, InputColorID, InpuEngineID, InputFuelTypeID);
            }
    
    
    
            private void TestSinglePrediction( float CarPrice, float ColorID, float EngineID, float FuelTypeID)
            {
                MLContext MachineContext = MLContext;
                ITransformer loadedModel;
                using (var stream = new FileStream(CarModelPath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    loadedModel = MachineContext.Model.Load(stream);
                }
                var predictionFunction = loadedModel.MakePredictionFunction<CarPrediction, CarPricePrediction>(MachineContext);
    
                var CarPriceSample = new CarPrediction()
                {
                    Car_Price = CarPrice,
                    Color_ID = ColorID,
                    Engine_ID = EngineID,
                    FuelType_ID = FuelTypeID,
                    TotalPrice = 0
    
    
                };
                var CarPricePrediction = predictionFunction.Predict(CarPriceSample);
                _showValue(CarPricePrediction.TotalPrice);
            }
    
    
    
            private static void SaveModelAsFile(MLContext MLContext, ITransformer Model)
            {
               // string ModelPath = CarModelPath;
                using (var fileStream = new FileStream(CarModelPath, FileMode.Create, FileAccess.Write, FileShare.Write))
                    MLContext.Model.Save(Model, fileStream);
                Form1.ShowSaveLocation(CarModelPath);
            }
    
        }
    }
    

    And then we have the form:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace MachineLearning2
    {
        public partial class Form1 : Form
        {
        
            Scripts.MachineLearning.LearningModel learningModel;
    
    
            public Form1()
            {
                InitializeComponent();
               // GetTestPredictions = new Scripts.MachineLearning.TestPredictions(ShowPrediction);
                learningModel = new Scripts.MachineLearning.LearningModel(ShowPrediction);
            }
              
             public static void ShowSaveLocation(string CarModelPath)
            {
                MessageBox.Show("The model is saved to "+ CarModelPath);
            }
             public static void ShowEvaluationProgress(string EvaluationProgress)
            {
    
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                
            }
    
    
            private void OutputTextBox_TextChanged(object sender, EventArgs e)
            {
    
            }
    
            private void label1_Click(object sender, EventArgs e)
            {
    
            }
    
            private void SendPredictionButton_Click(object sender, EventArgs e)
            {
    
                // TestPredictions.TestSinglePrediction(int.Parse(CarPriceInput.Text),int.Parse( ColorIDInput.Text), int.Parse(EngineIDInput.Text),int.Parse( FuelTypeIDInput.Text));
                learningModel.ReceiveData(CarPriceInput.Text,ColorIDInput.Text,EngineIDInput.Text,FuelTypeIDInput.Text);
    
                CarPriceInput.Text = null;
                ColorIDInput.Text = null;
                EngineIDInput.Text = null;
                FuelTypeIDInput.Text = null;
    
            }
    
             void ShowPrediction (float InputValue)
            {
                OutputTextBox.Text = InputValue.ToString();
            }
    
    
            private void TrainMachineButton_Click(object sender, EventArgs e)
            {
               
                learningModel.TrainingModel();
            }
    
            private void EvaluateMachineButton()
            {
             
            }
    
            private void FuelTypeIDList_TextChanged(object sender, EventArgs e)
            {
    
            }
        }
    }
    

    And the column class:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Microsoft.ML.Runtime.Api;
    
    namespace MachineLearning2.Scripts.MachineLearning
    {
        public class CarPrediction
        {
            [Column("0")]
            public int ID;
            [Column("1")]
            public float Car_Price;
            [Column("2")]
            public float Color_ID;
            [Column("3")]
            public float Engine_ID;
            [Column("4")]
            public float FuelType_ID;
            [Column("5")]
            public float TotalPrice;
                    
        }
        public class CarPricePrediction
        {
            [ColumnName("Score")]
            public float TotalPrice;
    
        }
    
    }
    

    Can someone be so kind as to tell me where I screwed up? I can't find a solution for this problem, and it's annoying the hell out of me. 

    Thank you in advance for your time and help,

    Cheers,

    Daniel

    Monday, January 7, 2019 10:12 AM

Answers

  • Hello Yutong,

    I figured out the error myself a moment ago.

    It seems the dataset was not having all the values properly filled in the .CSV file (Training Set), so I had to change some values in there and then it worked.

    It seems that when you have a file that has not enough entries, or the entries (rows with Data) are not properly written (mixup of strings and .R4 (Decimals/floats)) you get a zero as output if you test a single entry.

    As for the referring document (the one I am using as reference to create my own context machines) is the Taxi Fare trip document here : https://docs.microsoft.com/en-us/dotnet/machine-learning/tutorials/taxi-fare

    Sorry for bugging everyone with this, and thank you if you tried to help me but also could not find anything.

    Kind regards,

    Daniel

    Saturday, January 12, 2019 12:04 AM

All replies

  • Hi,

    Sorry to hear you are suffering from this issue, may I know which document you are referring to? 

    Regards,

    Yutong

    Tuesday, January 8, 2019 8:34 PM
    Owner
  • Hello Yutong,

    I figured out the error myself a moment ago.

    It seems the dataset was not having all the values properly filled in the .CSV file (Training Set), so I had to change some values in there and then it worked.

    It seems that when you have a file that has not enough entries, or the entries (rows with Data) are not properly written (mixup of strings and .R4 (Decimals/floats)) you get a zero as output if you test a single entry.

    As for the referring document (the one I am using as reference to create my own context machines) is the Taxi Fare trip document here : https://docs.microsoft.com/en-us/dotnet/machine-learning/tutorials/taxi-fare

    Sorry for bugging everyone with this, and thank you if you tried to help me but also could not find anything.

    Kind regards,

    Daniel

    Saturday, January 12, 2019 12:04 AM