Exemplo n.º 1
0
        public void Train(List <Person> people, int numberOfTrees, int skillSetSize)
        {
            double[][] inputs = _dataPointService.GenerateDataPointsFromPeople(people, skillSetSize);

            int[] expectedResults = _dataPointService.GenerateExpectedResultFromPeople(people);

            // Create the forest learning algorithm
            var teacher = new RandomForestLearning()
            {
                NumberOfTrees = numberOfTrees, // use 10 trees in the forest
            };

            // Finally, learn a random forest from data
            _randomForest = teacher.Learn(inputs, expectedResults);

            // We can estimate class labels using
            trainingPredictions = _randomForest.Decide(inputs);

            // And the classification error (0.0006) can be computed as
            double error = new ZeroOneLoss(expectedResults).Loss(_randomForest.Decide(inputs));

            File.WriteAllLines(
                @"C:\Users\Niall\Documents\Visual Studio 2015\Projects\LinkedInSearchUi\LinkedIn Dataset\XML\random_forest_predictions.txt" // <<== Put the file name here
                , trainingPredictions.Select(d => d.ToString()).ToArray());
        }
Exemplo n.º 2
0
 static void BestClassificator(RandomForest forest, DecisionTree tree, KNearestNeighbors knn, double[] precision)
 {
     if (precision[0] > precision[1])
     {
         Console.WriteLine("Geriausias parinktas klasifikavimo metodas: {0}", "Random Forest");
         Console.Write("Iveskite penkiu kortu rinkini, skaicius atskirdamo tarpu: ");
         string[] val  = Console.ReadLine().Split(' ');
         double[] hand = new double[10];
         for (int i = 0; i < 10; i++)
         {
             hand[i] = Convert.ToDouble(val[i]);
         }
         Console.WriteLine(forest.Decide(hand));
     }
     else
     {
         Console.WriteLine("Geriausias parinktas klasifikavimo metodas: %s", "Decision Tree");
         Console.Write("Iveskite penkiu kortu rinkini, skaicius atskirdamo tarpu: ");
         string[] val  = Console.ReadLine().Split(' ');
         double[] hand = new double[10];
         for (int i = 0; i < 10; i++)
         {
             hand[i] = Convert.ToDouble(val[i]);
         }
         Console.WriteLine(tree.Decide(hand));
     }
 }
Exemplo n.º 3
0
 public void Test(List <Person> testingPeople, int skillSetSize)
 {
     double[][] inputs = _dataPointService.GenerateDataPointsFromPeople(testingPeople, skillSetSize);
     testPredictions = _randomForest.Decide(inputs);
     //calculate
     File.WriteAllLines(
         @"C:\Users\Niall\Documents\Visual Studio 2015\Projects\LinkedInSearchUi\LinkedIn Dataset\XML\random_forest_test_predictions.txt" // <<== Put the file name here
         , testPredictions.Select(d => d.ToString()).ToArray());
 }
Exemplo n.º 4
0
        private static void Predict()
        {
            var lgrPred = -1;
            var lgrProb = -1.0;

            if (MultinomialLogisticRegression != null)
            {
                lgrPred = MultinomialLogisticRegression.Decide(CurrPredictionPoints);
                lgrProb = MultinomialLogisticRegression.Probability(CurrPredictionPoints);
                PredictedFrequencyClassifiers = lgrPred;
                if (Classification.IsValidation)
                {
                    Console.WriteLine($"Real Frequency: {BrainStorm0.ClassificationShape.Hertz} Logistic Regression Predicted Frequency: {lgrPred} Probability: {lgrProb}");
                }
            }

            var mmdPred  = -1;
            var mmdScore = -1.0;

            if (MinimumMeanDistance != null)
            {
                mmdPred  = MinimumMeanDistance.Decide(CurrPredictionPoints);
                mmdScore = MinimumMeanDistance.Score(CurrPredictionPoints);
                if (Classification.IsValidation)
                {
                    Console.WriteLine(
                        $"Real Frequency: {BrainStorm0.ClassificationShape.Hertz} Minimun Distance Predicted Frequency: {PredictedFrequencyClassifiers}");
                }
                else
                {
                    Console.WriteLine(
                        $"MMD Predicted Frequency: {mmdPred} {mmdScore}");
                }
            }

            var rfPred = -1;

            if (RandomForest != null)
            {
                rfPred = RandomForest.Decide(CurrPredictionPoints);
                if (Classification.IsValidation)
                {
                    Console.WriteLine(
                        $"Real Frequency: {BrainStorm0.ClassificationShape.Hertz} Random Forest Predicted Frequency: {rfPred}");
                }
                else
                {
                    Console.WriteLine(
                        $"Random Forest Predicted Frequency: {rfPred}");
                }
            }
            if (IsTyping)
            {
                UpdateTypingPredictions();
            }
        }
Exemplo n.º 5
0
        public void Uczenie(string[] naglowki, string[][] dane)
        {
            Codification kody = new Codification(naglowki, dane);

            int[][] symbole       = kody.Transform(dane);
            int[][] daneWejsciowe = symbole.Get(null, 0, -1);

            KolumnaWynikow = symbole.GetColumn(-1);

            RandomForestLearning nauczyciel = new RandomForestLearning()
            {
                SampleRatio = IloscDanychModelu
            };

            RandomForest las = nauczyciel.Learn(daneWejsciowe, KolumnaWynikow);

            Rezultaty = las.Decide(daneWejsciowe);
        }
        /// <summary>
        /// Trains the classifier and computes the training error if option provided.
        /// </summary>
        /// <param name="trainingData">The training data that will be used to train classifier.</param>
        /// <param name="trainingLabels">The training labels related to provided training data.</param>
        /// <param name="calculateError">The boolean check to tell if the training error should be calculated.</param>
        public override void Train(List <double[]> trainingData, List <int> trainingLabels, bool calculateError = true)
        {
            LearningAlgorithm = new RandomForestLearning();
            if (NumTrees > 0)
            {
                LearningAlgorithm.NumberOfTrees = NumTrees;
            }

            if (SamplePropotion > 0)
            {
                LearningAlgorithm.SampleRatio = SamplePropotion;
            }

            Model = LearningAlgorithm.Learn(trainingData.ToArray(), trainingLabels.ToArray());
            if (calculateError == true)
            {
                TrainingError = new ZeroOneLoss(trainingLabels.ToArray()).Loss(Model.Decide(trainingData.ToArray()));
            }
        }
Exemplo n.º 7
0
        private static void randomForest(double[][] inputs, int[] outputs)
        {
            var teacher = new RandomForestLearning()
            {
                NumberOfTrees = 100, // Use 100 decision trees to cover this problem
            };

            // Use the learning algorithm to induce the tree
            RandomForest rf = teacher.Learn(inputs, outputs);

            // Classify the samples using the RF
            int[] predicted = rf.Decide(inputs);

            // Create a confusion matrix to check the quality of the predictions:
            var cm = new ConfusionMatrix(predicted: predicted, expected: outputs);

            // Check the accuracy measure:
            double accuracy = cm.Accuracy; // (should be 1.0 or 100%)
        }
Exemplo n.º 8
0
        public bool[] classify(double[][] oinputs)
        {
            // We can estimate class labels using
            int[]  predicted = forest.Decide(oinputs);
            bool[] answers   = new bool[predicted.Length];

            for (int i = 0; i < predicted.Length; i++)
            {
                if (predicted[i] == 0)
                {
                    answers[i] = false;
                }
                else
                {
                    answers[i] = true;
                }
            }

            return(answers);
        }
Exemplo n.º 9
0
        public override void Train(List <double[]> trainingData, List <double> trainingLabels, bool calculateError = true)
        {
            LearningAlgorithm = new RandomForestLearning();
            if (NumTrees > 0)
            {
                LearningAlgorithm.NumberOfTrees = NumTrees;
            }

            if (SamplePropotion > 0)
            {
                LearningAlgorithm.SampleRatio = SamplePropotion;
            }
            int[][] TrainingData   = TypeCasters.DoubleMultiArrayToInt(trainingData).ToArray();
            int[]   TrainingLabels = TypeCasters.DoubleArrayToInt(trainingLabels).ToArray();

            Model = LearningAlgorithm.Learn(TrainingData, TrainingLabels);
            if (calculateError == true)
            {
                TrainingError = new ZeroOneLoss(TrainingLabels).Loss(Model.Decide(TrainingData));
            }
        }
 /// <summary>
 /// Perform classification from loaded model and returns the infered class.
 /// </summary>
 /// <param name="vector">The input vector that should be list of double.</param>
 /// <returns>Resultant class as an integer</returns>
 public override int Classify(List <double> vector)
 {
     return(Model.Decide(vector.ToArray()));
 }
Exemplo n.º 11
0
 public override double Classify(List <double> featureVector)
 {
     return(Model.Decide(featureVector.ToArray()));
 }
Exemplo n.º 12
0
 public int[] Predict(double[][] inputs)
 {
     int[] predicted = _forest.Decide(inputs);
     return(predicted);
 }
        private void Video1_Proccess1()
        {
            //if (_capture1 != null && _capture1.Ptr != IntPtr.Zero)
            //{

            int  war_at_frame = 0;
            bool warning      = false;

            while (camera_1.frameNum < total_frames1 - 10)
            {
                //Console.WriteLine(camera_1.frameNum);
                if (camera_1.frameNum % 20 == 0)
                {
                    count = 0;
                }

                abnormal_vote = 0;
                normal_vote   = 0;
                try
                {
                    double[] fe = F_E.extract(vid1, camera_1.frameNum);
                    if (fe[0] == null || fe[1] == null)
                    {
                        fe[0] = 240;
                        fe[0] = 170;
                    }
                    int[] fff = new int[] { (int)fe[0], (int)fe[1] };

                    //int knn_answer = knn.Decide(fe);
                    int  RF_answer = RF.Decide(fe);
                    bool LR_answer = LR.Decide(fe);
                    //bool SVM_answer = SVM.Decide(fe);
                    int    NB_answer = NB.Decide(fff);
                    double fl1       = HMM.LogLikelihood(fff);

                    if (chocking || lying)
                    {
                        Console.WriteLine(fl1);
                        if (fl1.CompareTo(-8.3) == 1)
                        {
                            hmm_count++;
                        }
                    }


                    else if (violence)
                    {
                        if (RF_answer == 1)
                        {
                            abnormal_vote += 0.978546619845336;
                        }
                        else
                        {
                            normal_vote += 0.978546619845336;
                        }

                        if (LR_answer)
                        {
                            abnormal_vote += 0.8428031393318365;
                        }
                        else
                        {
                            normal_vote += 0.8428031393318365;
                        }

                        if (NB_answer == 1)
                        {
                            abnormal_vote += 0.8746569953754341;
                        }
                        else
                        {
                            normal_vote += 0.8746569953754341;
                        }

                        if (abnormal_vote.CompareTo(normal_vote) == 1)
                        {
                            count++;
                        }
                    }

                    if (hmm_count >= 2 || count >= 4)
                    {
                        if (count >= 4)
                        {
                            count = 0;
                        }
                        if (hmm_count >= 2)
                        {
                            hmm_count = 0;
                        }

                        this.pictureBox3.Invoke((MethodInvoker) delegate
                        {
                            // Running on the UI thread
                            pictureBox3.Image = Properties.Resources.warning;
                        });

                        if (alarm)
                        {
                            wplayer.URL = "D:\\2\\Real-Time Abnormal Event Detection And Tracking In Video\\Alarm.mp3";
                            wplayer.controls.play();
                        }



                        //pictureBox3.Image = Properties.Resources.warning;
                        warning      = true;
                        war_at_frame = camera_1.frameNum;

                        Media.Crop_video(vid1, (int)camera_1.frameNum / (fbs + 5), 30);
                        Media.thumbnail(vid1, (int)camera_1.frameNum / (fbs + 5));
                        Image image = Image.FromFile(@"D:\2\Real-Time Abnormal Event Detection And Tracking In Video\croped_videos\crop" + Media.num.ToString() + ".jpg");
                        dataGridView1.Rows.Add(image, @"D:\2\Real-Time Abnormal Event Detection And Tracking In Video\croped_videos\crop" + Media.num.ToString() + ".mpg");
                        Media.num++;
                    }

                    if (warning && camera_1.frameNum >= (war_at_frame + 10))
                    {
                        this.pictureBox3.Invoke((MethodInvoker) delegate
                        {
                            // Running on the UI thread
                            pictureBox3.Image = Properties.Resources._checked;
                        });
                        //pictureBox3.Image = Properties.Resources._checked;
                        warning = false;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("1--- ", e.Message);
                }
            }
        }