private List <IrisData> ReadDataFromFile(string path)
        {
            var result = new List <IrisData>();

            using (var reader = new StreamReader(path))
            {
                while (!reader.EndOfStream)
                {
                    var record = new IrisData();
                    var line   = reader.ReadLine();
                    var values = line.Split(',');

                    record.SepalLenght = decimal.Parse(values[0]);
                    record.SepalWidth  = decimal.Parse(values[1]);
                    record.PetalLenght = decimal.Parse(values[2]);
                    record.PetalWidth  = decimal.Parse(values[3]);
                    record.IrisClass   = values[4] switch
                    {
                        "Iris-setosa" => IrisClassEnum.IrisSetosa,
                        "Iris-versicolor" => IrisClassEnum.IrisVersicolour,
                        "Iris-virginica" => IrisClassEnum.IrisVirginica,
                        _ => IrisClassEnum.Unknown
                    };

                    result.Add(record);
                }
            }
            return(result);
        }
    }
        public IActionResult Predict([FromBody] Iris iris)
        {
            var pipeline = new LearningPipeline
            {
                new TextLoader <IrisData>("iris-data.txt", separator: ","),
                new Dictionarizer("Label"),
                new ColumnConcatenator("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth"),
                new StochasticDualCoordinateAscentClassifier(),
                new PredictedLabelColumnOriginalValueConverter {
                    PredictedLabelColumn = "PredictedLabel"
                }
            };

            var data = new IrisData
            {
                PetalLength = iris.PetalLength,
                PetalWidth  = iris.PetalWidth,
                SepalLength = iris.SepalLength,
                SepalWidth  = iris.SepalWidth
            };

            var model      = pipeline.Train <IrisData, IrisPrediction>();
            var prediction = model.Predict(data);

            return(Ok(prediction));
        }
        public string Post([FromBody] IrisData instance)
        {
            var model      = PredictionModel.ReadAsync <IrisData, IrisPrediction>("model.zip").Result;
            var prediction = model.Predict(instance);

            return(prediction.PredictedLabels);
        }
        static void Main(string[] args)
        {
            var mlContext = new MLContext();


            //import data
            var trainingData = mlContext.Data.LoadFromTextFile <IrisData>(
                path: dataPath,
                hasHeader: false,
                separatorChar: ',');

            //data preparation and training pipeline
            var pipeline = mlContext.Transforms
                           .Concatenate("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth")
                           .Append(mlContext.Clustering.Trainers.KMeans("Features", numberOfClusters: 3));


            //train
            var model = pipeline.Fit(trainingData);

            //prediction
            var dataToMakePredictionOn = new IrisData()
            {
                PetalLength = 0.2f, PetalWidth = 5.6f, SepalLength = 1f, SepalWidth = 1.6f
            };
            var label = mlContext.Model.CreatePredictionEngine <IrisData, ClusterPrediction>(model).Predict(dataToMakePredictionOn);

            Console.WriteLine($"{string.Join(" ", label.Distances)}");
        }
    void Start()
    {
        Debug.Log("starting...");
        mlContext = new MLContext(seed: 0);
        IDataView dataView           = mlContext.Data.ReadFromTextFile <IrisData>(_dataPath, hasHeader: false, separatorChar: ',');
        string    featuresColumnName = "Features";
        var       pipeline           = mlContext.Transforms
                                       .Concatenate(featuresColumnName, "SepalLength", "SepalWidth", "PetalLength", "PetalWidth")
                                       .Append(mlContext.Clustering.Trainers.KMeans(featuresColumnName, clustersCount: 3)); //read and format flowery data
        var model = pipeline.Fit(dataView);                                                                                 //train

        using (var fileStream = new FileStream(_modelPath, FileMode.Create, FileAccess.Write, FileShare.Write))             //save trained model
        {
            mlContext.Model.Save(model, fileStream);
        }
        var      predictor = mlContext.Model.CreatePredictionEngine <IrisData, ClusterPrediction>(model);//predict
        IrisData Setosa    = new IrisData
        {
            SepalLength = 5.1f,
            SepalWidth  = 3.5f,
            PetalLength = 1.4f,
            PetalWidth  = 0.2f
        };

        Debug.Log(predictor.Predict(Setosa).PredictedClusterId);
        Debug.Log("...done predicting, now do what u like with it");
    }
Esempio n. 6
0
        public ClusterPrediction PredictFromFile()
        {
            var mlContext        = new MLContext();
            var repertoireSortie = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var _modelPath       = repertoireSortie + "/model.save";
            //Define DataViewSchema for data preparation pipeline and trained model
            DataViewSchema modelSchema;
            // Load trained model
            ITransformer trainedModel     = mlContext.Model.Load(_modelPath, out modelSchema);
            var          reader           = mlContext.Data.CreateTextLoader <IrisData>(separatorChar: ',', hasHeader: false);
            var          trainingDataView = reader.Load($"{repertoireSortie}/DataSources/iris.data");
            // STEP 4: Train your model based on the data set
            var predictor = mlContext.Model.CreatePredictionEngine <IrisData, ClusterPrediction>(trainedModel);
            var inputData = new IrisData()
            {
                SepalLength = 3.3f,
                SepalWidth  = 1.6f,
                PetalLength = 0.2f,
                PetalWidth  = 5.1f,
            };
            var prediction = predictor.Predict(inputData);

            Console.WriteLine($"Cluster: {prediction.PredictedClusterId}");
            Console.WriteLine($"Distances: {string.Join(" ", prediction.Distances)}");
            return(prediction);
        }
Esempio n. 7
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            [Blob("models/model.zip", FileAccess.Read, Connection = "AzureWebJobsStorage")] Stream serializedModel,
            ILogger log)
        {
            // Workaround for Azure Functions Host
            if (typeof(Microsoft.ML.Runtime.Data.LoadTransform) == null ||
                typeof(Microsoft.ML.Runtime.Learners.LinearClassificationTrainer) == null ||
                typeof(Microsoft.ML.Runtime.Internal.CpuMath.SseUtils) == null ||
                typeof(Microsoft.ML.Runtime.FastTree.FastTree) == null)
            {
                log.LogError("Error loading ML.NET");
                return(new StatusCodeResult(500));
            }

            //Read incoming request body
            string requestBody = new StreamReader(req.Body).ReadToEnd();

            log.LogInformation(requestBody);

            //Bind request body to IrisData object
            IrisData data = JsonConvert.DeserializeObject <IrisData>(requestBody);

            //Load prediction model
            var model = await Model.LoadSerializeModel(serializedModel);

            // var model = PredictionModel.ReadAsync<IrisData, IrisPrediction>(serializedModel).Result;

            //Make prediction
            string prediction = Model.MakePrediction(model, data);

            //Return prediction
            return((IActionResult) new OkObjectResult(prediction));
        }
Esempio n. 8
0
        public async Task <ActionResult <string> > Post(IrisData instance)
        {
            var model = await Model.LoadZipModel("model.zip");

            var prediction = Model.MakePrediction(model, instance);

            return(Ok(prediction));
        }
    // Cálculo da Distância Euclidiana
    public double CalcularDistanciaEuclidiana(Centroid centroid, IrisData data)
    {
        double a = data.SepalLength - centroid.SepalLength;
        double b = data.SepalWidth - centroid.SepalWidth;
        double c = data.PetalLength - centroid.PetalLength;
        double d = data.PetalWidth - centroid.PetalWidth;

        return(Math.Sqrt((a * a) + (b * b) + (c * c) + (d * d)));
    }
        public async Task <string> Post([FromBody] IrisData observation)
        {
            IrisPrediction prediction = await _predictActorPool
                                        .Ask <IrisPrediction>(new Predict <IrisData> {
                Observation = observation
            });

            return(prediction.PredictedLabel);
        }
        /// <summary>
        /// 使用訓練好的預測模型檔進行預測
        /// </summary>
        /// <param name="sampleData"></param>
        public static async Task PredictWithModelLoadedFromFile(IrisData sampleData = null)
        {
            // 載入之前訓練好的預測模型
            var loadPredictionModel = await PredictionModel.ReadAsync <IrisData, IrisPrediction>(ModelPath);

            // 使用匯入的預測模型進行預測,若無 sampleData 則用預設測試樣本
            var prediction = loadPredictionModel.Predict(sampleData ?? DefaultSampleData);

            Console.WriteLine($"預測的鳶尾花(Iris)類別: {prediction.PredictedLabel}");
        }
Esempio n. 12
0
        public ActionResult <float> Post([FromBody] IrisData input)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }
            var prediction = _predictionEnginePool.Predict(input);

            return(prediction.Distances.First());
        }
Esempio n. 13
0
        private static object GetDynamicClass(IrisData irisData, object newIris)
        {
            Type instanceType = newIris.GetType();

            irisData.GetType().GetFields().ToList().ForEach((field) =>
            {
                instanceType.GetField(field.Name).SetValue(newIris, field.GetValue(irisData));
            });

            return(newIris);
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            //Define data path
            var dataPath = "Data/iris.csv";

            //Create Context
            var mlContext = new MLContext();

            //Load Data
            var data = mlContext.Data.ReadFromTextFile <IrisData>(dataPath, hasHeader: true, separatorChar: ',');

            //Split data into train and test set
            var(trainData, testData) = Operations.SplitData(mlContext, data);

            //Preview Tranining Data
            var trainDataPreview = trainData.Preview();

            //Train model
            ITransformer trainedModel = Operations.Train(mlContext, trainData);

            //Apply trained model to test data
            IDataView transformedData = trainedModel.Transform(testData);

            //Preview transformed test data
            var transformedDataPreview = transformedData.Preview();

            //Evaluate model using test data
            double rSquared = Operations.Evaluate(mlContext, trainedModel, testData);

            Console.WriteLine("RSquared Metric:\t{0:P4}", rSquared);

            IrisData testInput = new IrisData
            {
                SepalLength = 3.3f,
                SepalWidth  = 1.6f,
                PetalLength = 0.2f,
                PetalWidth  = 5.1f
            };

            PredictionEngine <IrisData, IrisPrediction> predictionEngine = mlContext.Model.CreatePredictionEngine <IrisData, IrisPrediction>(trainedModel);

            //Make prediction on unseen instance of data using trained model
            string prediction = Operations.Predict(predictionEngine, testInput);

            Console.WriteLine("The prediction is {0}", prediction);

            //Save Model
            Operations.SaveModel(mlContext, trainedModel, "iris_model.zip");

            Console.ReadKey();
        }
Esempio n. 15
0
        public void Predict(PredictionModel <IrisData, ClusterPrediction> model)
        {
            IrisData Setosa = new IrisData
            {
                SepalLength = 5.1f,
                SepalWidth  = 3.5f,
                PetalLength = 1.4f,
                PetalWidth  = 0.2f
            };

            var prediction = model.Predict(Setosa);

            Console.WriteLine($"Cluster: {prediction.PredictedClusterId}");
            Console.WriteLine($"Distances: {string.Join(" ", prediction.Distances)}");
        }
Esempio n. 16
0
        private static void NormalizeData()
        {
            var targetRange = new DoubleRange(-10, 10);

            var spec1Normalizer = new Normalizer(IrisData.Select(i => i.Spec1).ToArray(), targetRange);
            var spec2Normalizer = new Normalizer(IrisData.Select(i => i.Spec2).ToArray(), targetRange);
            var spec3Normalizer = new Normalizer(IrisData.Select(i => i.Spec3).ToArray(), targetRange);
            var spec4Normalizer = new Normalizer(IrisData.Select(i => i.Spec4).ToArray(), targetRange);

            IrisDataNormalized = IrisData.Select(d =>
                                                 new Iris(
                                                     spec1Normalizer.Normalize(d.Spec1),
                                                     spec2Normalizer.Normalize(d.Spec2),
                                                     spec3Normalizer.Normalize(d.Spec3),
                                                     spec4Normalizer.Normalize(d.Spec4),
                                                     d.Type)).ToArray();
        }
 public void ReadData()
 {
     string sheetName = "Iris";
     var irisFile = new ExcelQueryFactory(GetPath());
     var irisData = from a in irisFile.Worksheet<IrisData>(sheetName) select a;
     foreach (var iris in irisData)
     {
         IrisData irisTemp = new IrisData()
         {
             Iris = iris.Iris,
             PetalLength= iris.PetalLength,
             PetalWidth=iris.PetalWidth,
             SepalLength=iris.SepalLength,
             SepalWidth=iris.SepalWidth
         };
         IrisList.Add(irisTemp);
     }
 }
Esempio n. 18
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            MLContext mlContext = new MLContext();

            ITransformer trainedModel = Operations.LoadModel(mlContext, "iris_model.zip");

            string   requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            IrisData data        = JsonConvert.DeserializeObject <IrisData>(requestBody);

            PredictionEngine <IrisData, IrisPrediction> predictionEngine = mlContext.Model.CreatePredictionEngine <IrisData, IrisPrediction>(trainedModel);

            string prediction = Operations.Predict(predictionEngine, data);

            return((ActionResult) new OkObjectResult(prediction));
        }
Esempio n. 19
0
        public void addContent()
        {
            if (characters != null)
            {
                foreach (IrisCharacter charac in characters)
                {
                    IrisData.addCharacter(charac.name, charac);
                }
            }

            if (images != null)
            {
                foreach (IrisImage image in images)
                {
                    IrisData.addImage(image.name, image);
                }
            }

            if (sounds != null)
            {
                foreach (IrisSound sound in sounds)
                {
                    IrisData.addSound(sound.name, sound);
                }
            }

            if (backgrounds != null)
            {
                foreach (IrisBackground background in backgrounds)
                {
                    IrisData.addBackground(background.name, background);
                }
            }

            if (npcs != null)
            {
                foreach (NpcStructure npc in npcs)
                {
                    IrisData.addNpc(npc.name, npc);
                }
            }
        }
Esempio n. 20
0
        /// <summary>
        /// 分類鳶尾花(K-means)
        /// </summary>
        public void InitIris()
        {
            IrisData Setosa = new IrisData
            {
                SepalLength = 5.1f,
                SepalWidth  = 3.5f,
                PetalLength = 1.4f,
                PetalWidth  = 0.2f
            };

            var mlContext = new MLContext(seed: 0);

            string    dataPath = AppDomain.CurrentDomain.BaseDirectory + "/MLData/iris-data.txt";
            IDataView dataView = mlContext.Data.LoadFromTextFile <IrisData>(dataPath, hasHeader: false, separatorChar: ',');

            string featuresColumnName = "Features";
            var    pipeline           = mlContext.Transforms
                                        .Concatenate(featuresColumnName, "SepalLength", "SepalWidth", "PetalLength", "PetalWidth")
                                        .Append(mlContext.Clustering.Trainers.KMeans(featuresColumnName, numberOfClusters: 3));

            ITransformer model = pipeline.Fit(dataView);

            var modelZipUri = AppDomain.CurrentDomain.BaseDirectory + "/MLModel/iris.zip";

            using (var fileStream = new FileStream(modelZipUri, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                mlContext.Model.Save(model, dataView.Schema, fileStream);
            }

            ITransformer transformer;

            // Load model.
            using (var file = File.OpenRead(modelZipUri))
                transformer = mlContext.Model.Load(file, out DataViewSchema schema);

            // var result = model.Transform(mlContext.Data.LoadFromEnumerable(new List<IrisData>() { Setosa }));
            var predictor  = mlContext.Model.CreatePredictionEngine <IrisData, ClusterPrediction>(transformer);
            var prediction = predictor.Predict(Setosa);

            Console.WriteLine($"Cluster: {prediction.PredictedClusterId}");
            Console.WriteLine($"Distances: {string.Join(" ", prediction.Distances)}");
        }
Esempio n. 21
0
        public void TrainModel()
        {
            // STEP 2: Create a ML.NET environment
            var mlContext = new MLContext();
            // If working in Visual Studio, make sure the 'Copy to Output Directory'
            // property of iris-data.txt is set to 'Copy always'
            var reader           = mlContext.Data.CreateTextLoader <IrisData>(separatorChar: ',', hasHeader: false);
            var repertoireSortie = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            var trainingDataView = reader.Load($"{repertoireSortie}/DataSources/iris.data");
            // STEP 3: Transform your data and add a learner
            // Assign numeric values to text in the "Label" column, because only
            // numbers can be processed during model training.
            // Add a learning algorithm to the pipeline. e.g.(What type of iris is this?)
            // Convert the Label back into original text (after converting to number in step 3)
            //var pipeline = mlContext.Transforms.Conversion.MapValueToKey("Label")
            //    .Append(mlContext.Transforms.Concatenate("Features", "SepalLength", "SepalWidth", "PetalLength", "PetalWidth"))
            //    .Append(mlContext.MulticlassClassification.Trainers.SdcaMaximumEntropy("Label", "Features"))
            //    .Append(mlContext.Transforms.Conversion.MapKeyToValue("PredictedLabel"));
            string featuresColumnName = "Features";
            var    pipeline           = mlContext.Transforms
                                        .Concatenate(featuresColumnName, "SepalLength", "SepalWidth", "PetalLength", "PetalWidth")
                                        .Append(mlContext.Clustering.Trainers.KMeans(featuresColumnName, numberOfClusters: 3));

            // STEP 4: Train your model based on the data set
            var model     = pipeline.Fit(trainingDataView);
            var predictor = mlContext.Model.CreatePredictionEngine <IrisData, ClusterPrediction>(model);
            var inputData = new IrisData()
            {
                SepalLength = 3.3f,
                SepalWidth  = 1.6f,
                PetalLength = 0.2f,
                PetalWidth  = 5.1f,
            };
            var prediction = predictor.Predict(inputData);

            Console.WriteLine($"Cluster: {prediction.PredictedClusterId}");
            Console.WriteLine($"Distances: {string.Join(" ", prediction.Distances)}");

            SaveModelAsFile(mlContext, model, trainingDataView);
        }
Esempio n. 22
0
        static void Main(string[] args)
        {
            string dataPath = "data/iris.txt";

            string modelPath = "model.zip";

            var model = Model.TrainModel(dataPath, modelPath).Result;

            // Test data for prediction
            IrisData input = new IrisData()
            {
                SepalLength = 3.3f,
                SepalWidth  = 1.6f,
                PetalLength = 0.2f,
                PetalWidth  = 5.1f
            };

            string prediction = Model.MakePrediction(model, input);


            Console.WriteLine($"Predicted flower type is: {prediction}");
        }
Esempio n. 23
0
    // Obtêm o centróide mais próximo
    public int ObterCentroideMaisProximo(List <Centroid> centroids, int numClusters, IrisData data)
    {
        double minDistance;
        int    nearestcentroid;

        // Inicializa valores assumindo o centróide 0 como mais próximo
        minDistance     = CalcularDistanciaEuclidiana(centroids[0], data);
        nearestcentroid = 0;

        for (int i = 1; i < numClusters; i++)
        {
            double distance = CalcularDistanciaEuclidiana(centroids[i], data);

            if (distance < minDistance)
            {
                minDistance     = distance;
                nearestcentroid = i;
            }
        }

        return(nearestcentroid);
    }
Esempio n. 24
0
        public IrisPrediction PredictIris(IrisData irisData)
        {
            // Step 2: Create a pipeline and load your data
            var pipeline = new LearningPipeline();

            // If working in Visual Studio, make sure the
            // 'Copy to Output Directory' property of
            // iris-data.txt is set to 'Copy always'
            string dataPath = "iris-data.txt";

            pipeline.Add(new TextLoader(dataPath).CreateFrom <IrisData>(separator: ','));

            // Step 3: Transform your data
            // Assign numeric values to text in the "Label" column, because only
            // numbers can be processed during model training
            pipeline.Add(new Dictionarizer("Label"));

            // Step 4: Add learner
            // Add a learning algorithm to the pipeline
            // This is a classification scenario (what type of iris is this?)
            pipeline.Add(new StochasticDualCoordinateAscentClassifier());

            // Convert the Label back into original text (after converting to number in step 3)
            pipeline.Add(new PredictedLabelColumnOriginalValueConverter()
            {
                PredictedLabelColumn = "PredictedLabel"
            });

            // Step 5: Train your model based on the data set
            var model = pipeline.Train <IrisData, IrisPrediction>();

            // Step 6: Use your model to make a prediction
            // You can change these numbers to test different predictions
            var prediction = model.Predict(irisData);

            return(prediction);
        }
 public ClusterPrediction RunModel(IrisData irisData)
 {
     return(_predictor.Predict(irisData));
 }
Esempio n. 26
0
        static void Main(string[] args)
        {
            var mlContext = new MLContext();

            // localdb SQL database connection string using a filepath to attach the database file into localdb
            string dbFilePath       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Database", "Iris.mdf");
            string connectionString = $"Data Source = (LocalDB)\\MSSQLLocalDB;AttachDbFilename={dbFilePath};Database=Iris;Integrated Security = True";

            // ConnString Example: localdb SQL database connection string for 'localdb default location' (usually files located at /Users/YourUser/)
            //string connectionString = @"Data Source=(localdb)\MSSQLLocalDb;Initial Catalog=YOUR_DATABASE;Integrated Security=True;Pooling=False";
            //
            // ConnString Example: on-premises SQL Server Database (Integrated security)
            //string connectionString = @"Data Source=YOUR_SERVER;Initial Catalog=YOUR_DATABASE;Integrated Security=True;Pooling=False";
            //
            // ConnString Example:  Azure SQL Database connection string
            //string connectionString = @"Server=tcp:yourserver.database.windows.net,1433; Initial Catalog = YOUR_DATABASE; Persist Security Info = False; User ID = YOUR_USER; Password = YOUR_PASSWORD; MultipleActiveResultSets = False; Encrypt = True; TrustServerCertificate = False; Connection Timeout = 60; ConnectRetryCount = 5; ConnectRetryInterval = 10;";

            string commandText = "SELECT * from IrisData";

            DatabaseLoader loader = mlContext.Data.CreateDatabaseLoader <IrisData>();

            DatabaseSource dbSource = new DatabaseSource(SqlClientFactory.Instance,
                                                         connectionString,
                                                         commandText);

            IDataView dataView = loader.Load(dbSource);
            var       pre      = dataView.Preview();

            var trainTestData            = mlContext.Data.TrainTestSplit(dataView);
            var finalTransformerPipeLine = mlContext.Transforms.Conversion.MapValueToKey(inputColumnName: "class", outputColumnName: "KeyColumn").
                                           Append(mlContext.Transforms.Concatenate("Features", nameof(IrisData.petal_length), nameof(IrisData.petal_width), nameof(IrisData.sepal_length),
                                                                                   nameof(IrisData.sepal_width)));



            // Apply the ML algorithm
            var trainingPipeLine = finalTransformerPipeLine.Append(mlContext.MulticlassClassification.Trainers.LbfgsMaximumEntropy(labelColumnName: "KeyColumn", featureColumnName: "Features"))
                                   .Append(mlContext.Transforms.Conversion.MapKeyToValue(outputColumnName: "class", inputColumnName: "KeyColumn"));

            Console.WriteLine("Training the ML model while streaming data from a SQL database...");
            Stopwatch watch = new Stopwatch();

            watch.Start();

            var model = trainingPipeLine.Fit(trainTestData.TrainSet);

            watch.Stop();
            Console.WriteLine("Elapsed time for training the model = {0} seconds", watch.ElapsedMilliseconds / 1000);

            Console.WriteLine("Evaluating the model...");
            Stopwatch watch2 = new Stopwatch();

            watch2.Start();

            var predictions = model.Transform(trainTestData.TestSet);
            // Now that we have the test predictions, calculate the metrics of those predictions and output the results.
            var metrics = mlContext.MulticlassClassification.Evaluate(predictions, "KeyColumn", "Score");

            watch2.Stop();
            Console.WriteLine("Elapsed time for evaluating the model = {0} seconds", watch2.ElapsedMilliseconds / 1000);

            ConsoleHelper.PrintMultiClassClassificationMetrics("==== Evaluation Metrics training from a Database ====", metrics);

            Console.WriteLine("Trying a single prediction:");

            var predictionEngine = mlContext.Model.CreatePredictionEngine <IrisData, DataPrediction>(model);

            var sampleData1 = new IrisData()
            {
                sepal_length = 6.1f,
                sepal_width  = 3f,
                petal_length = 4.9f,
                petal_width  = 1.8f,
                class1       = string.Empty
            };

            var sampleData2 = new IrisData()
            {
                sepal_length = 5.1f,
                sepal_width  = 3.5f,
                petal_length = 1.4f,
                petal_width  = 0.2f,
                class1       = string.Empty
            };

            var irisPred1 = predictionEngine.Predict(sampleData1);
            var irisPred2 = predictionEngine.Predict(sampleData2);

            // Since we apply MapValueToKey estimator with default parameters, key values
            // depends on order of occurence in data file. Which is "Iris-setosa", "Iris-versicolor", "Iris-virginica"
            // So if we have Score column equal to [0.2, 0.3, 0.5] that's mean what score for
            // Iris-setosa is 0.2
            // Iris-versicolor is 0.3
            // Iris-virginica is 0.5.
            //Add a dictionary to map the above float values to strings.
            Dictionary <float, string> IrisFlowers = new Dictionary <float, string>();

            IrisFlowers.Add(0, "Setosa");
            IrisFlowers.Add(1, "versicolor");
            IrisFlowers.Add(2, "virginica");

            Console.WriteLine($"Predicted Label 1: {IrisFlowers[Array.IndexOf(irisPred1.Score, irisPred1.Score.Max())]} - Score:{irisPred1.Score.Max()}", Color.YellowGreen);
            Console.WriteLine($"Predicted Label 2: {IrisFlowers[Array.IndexOf(irisPred2.Score, irisPred2.Score.Max())]} - Score:{irisPred2.Score.Max()}", Color.YellowGreen);
            Console.WriteLine();

            //*** Detach database from localdb only if you used a conn-string with a filepath to attach the database file into localdb ***
            Console.WriteLine("... Detaching database from SQL localdb ...");
            DetachDatabase(connectionString);

            Console.WriteLine("=============== Press any key ===============");
            Console.ReadKey();
        }
        public void LoadSampleData(double width, double height, string horizontalData, string verticalData)
        {
            double sepalLengthMin = dataContext.Iris.Min(i => i.SepalLength);
            double sepalLengthMax = dataContext.Iris.Max(i => i.SepalLength);
            double sepalWidthMin  = dataContext.Iris.Min(i => i.SepalWidth);
            double sepalWidthMax  = dataContext.Iris.Max(i => i.SepalWidth);
            double petalLengthMin = dataContext.Iris.Min(i => i.PetalLength);
            double petalLengthMax = dataContext.Iris.Max(i => i.PetalLength);
            double petalWidthMin  = dataContext.Iris.Min(i => i.PetalWidth);
            double petalWidthMax  = dataContext.Iris.Max(i => i.PetalWidth);

            IrisData.Clear();

            foreach (Kohonen.Data.Iris i in dataContext.Iris)
            {
                double x = 0;
                double y = 0;
                switch (horizontalData)
                {
                case "Sepal Length":
                    x = (i.SepalLength - sepalLengthMin) * (width / (sepalLengthMax - sepalLengthMin));
                    break;

                case "Sepal Width":
                    x = (i.SepalWidth - sepalWidthMin) * (width / (sepalWidthMax - sepalWidthMin));
                    break;

                case "Petal Length":
                    x = (i.PetalLength - petalLengthMin) * (width / (petalLengthMax - petalLengthMin));
                    break;

                case "Petal Width":
                    x = (i.PetalWidth - petalWidthMin) * (width / (petalWidthMax - petalWidthMin));
                    break;

                default:
                    continue;
                }
                switch (verticalData)
                {
                case "Sepal Length":
                    y = (i.SepalLength - sepalLengthMin) * (height / (sepalLengthMax - sepalLengthMin));
                    break;

                case "Sepal Width":
                    y = (i.SepalWidth - sepalWidthMin) * (height / (sepalWidthMax - sepalWidthMin));
                    break;

                case "Petal Length":
                    y = (i.PetalLength - petalLengthMin) * (height / (petalLengthMax - petalLengthMin));
                    break;

                case "Petal Width":
                    y = (i.PetalWidth - petalWidthMin) * (height / (petalWidthMax - petalWidthMin));
                    break;

                default:
                    continue;
                }
                IrisData.Add(new IrisLib(i, x, y));
            }
        }
Esempio n. 28
0
        public ActionResult Post([FromBody] IrisData input)
        {
            string prediction = Operations.Predict(_predictionEngine, input);

            return(Ok(prediction));
        }
 public IrisPrediction Predict(IrisData irisData)
 {
     return(_instance.Predict(irisData));
 }
Esempio n. 30
0
    public void Executar()
    {
        // Lista de Instâncias
        var instances = new List <IrisData>();

        // Lê o arquivo e preenche a lista
        int    counter = 0;
        string line;

        var path = Environment.CurrentDirectory + "\\Assets\\Data\\iris.data";

        var file = new StreamReader(path);

        while ((line = file.ReadLine()) != null)
        {
            var iris = line.ToString().Split(',');

            var instance = new IrisData
            {
                SepalLength = Convert.ToDouble(iris[0].Replace('.', ',')),
                SepalWidth  = Convert.ToDouble(iris[1].Replace('.', ',')),
                PetalLength = Convert.ToDouble(iris[2].Replace('.', ',')),
                PetalWidth  = Convert.ToDouble(iris[3].Replace('.', ',')),
                Family      = iris[4]
            };

            instances.Add(instance);

            counter++;
        }

        file.Close();

        // Executa o KMeans
        AlgoritmoKMeans(instances, instancesAmount, 3, 100);

        // Escreve o arquivo final com os resultados
        string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

        using (StreamWriter outputFile = new StreamWriter(Environment.CurrentDirectory + "\\Assets\\Data\\results.txt"))
        {
            // Iris
            foreach (var instance in instances)
            {
                outputFile.WriteLine($"{instance.SepalLength.ToString("N1")}    " +
                                     $"{instance.SepalWidth.ToString("N1")}    " +
                                     $"{instance.PetalLength.ToString("N1")}    " +
                                     $"{instance.PetalWidth.ToString("N1")}    " +
                                     $"{instance.Centroid}  " +
                                     $"{instance.Family}   ");
            }

            // Clusters
            var clusterId = 0;
            foreach (var cluster in centroidsList)
            {
                outputFile.WriteLine($"ID = {clusterId}:    " +
                                     $"{cluster.SepalLength.ToString("N1")}    " +
                                     $"{cluster.SepalWidth.ToString("N1")}    " +
                                     $"{cluster.PetalLength.ToString("N1")}    " +
                                     $"{cluster.PetalWidth.ToString("N1")}    ");

                clusterId++;
            }
        }

        // Instancia objetos
        foreach (var instance in instances)
        {
            var newPrefab = new GameObject();

            if (SceneManager.GetActiveScene().buildIndex == 0)
            {
                // Cena da Sépala
                newPrefab = Instantiate(IrisDataPrefab, new Vector3((float)instance.SepalLength * 1.5f, (float)instance.SepalWidth * 1.5f, 0), Quaternion.identity);
            }
            else if (SceneManager.GetActiveScene().buildIndex == 1)
            {
                // Cena da Pétala
                newPrefab = Instantiate(IrisDataPrefab, new Vector3((float)instance.PetalLength * 1.5f, (float)instance.PetalWidth * 1.5f, 0), Quaternion.identity);
            }

            if (instance.Centroid == 0)
            {
                newPrefab.GetComponent <MeshRenderer>().material.color = Color.red;
            }
            else if (instance.Centroid == 1)
            {
                newPrefab.GetComponent <MeshRenderer>().material.color = Color.blue;
            }
            else if (instance.Centroid == 2)
            {
                newPrefab.GetComponent <MeshRenderer>().material.color = Color.green;
            }
        }

        foreach (var centroid in centroidsList)
        {
            var newPrefab = new GameObject();

            if (SceneManager.GetActiveScene().buildIndex == 0)
            {
                // Cena da Sépala
                newPrefab = Instantiate(IrisDataPrefab, new Vector3((float)centroid.SepalLength * 1.5f, (float)centroid.SepalWidth * 1.5f, 0), Quaternion.identity);
            }
            else if (SceneManager.GetActiveScene().buildIndex == 1)
            {
                // Cena da Pétala
                newPrefab = Instantiate(IrisDataPrefab, new Vector3((float)centroid.PetalLength * 1.5f, (float)centroid.PetalWidth * 1.5f, 0), Quaternion.identity);
            }

            newPrefab.GetComponent <MeshRenderer>().material.color = Color.yellow;
        }
    }