Ejemplo n.º 1
0
        public double Predict(double[][] observations, int[] labels)
        {
            int[]  predicted = machine.Decide(observations);
            double error     = new AccuracyLoss(labels).Loss(predicted);

            return(1 - error);
        }
Ejemplo n.º 2
0
        public void not_seen_before_test()
        {
            // DecisionTree chokes on variable values it has never seen before #689
            int[][] training =
            {
                new [] { 0, 2, 4 },
                new [] { 1, 5, 2 },
                new [] { 1, 5, 6 },
            };

            int[][] testing =
            {
                new [] { 99,  2,  4 },
                new [] {  1,  5, 17 },
                new [] {  1, 15,  6 },
            };

            int[] outputs =
            {
                1, 1, 0
            };

            ID3Learning teacher = new ID3Learning();

            DecisionTree tree = teacher.Learn(training, outputs);

            int[] train = tree.Decide(training);
            int[] test  = tree.Decide(testing);

            Assert.IsTrue(train.IsEqual(new int[] { 1, 1, 0 }));
            Assert.IsTrue(test.IsEqual(new int[] { 1, 0, 0 }));
        }
Ejemplo n.º 3
0
        public int[] Predict(List <TrainingValue> predictionData)
        {
            if (!Trained)
            {
                throw new Exception("Train must be called first!");
            }

            double[][] featuresArray = new double[predictionData.Count][];

            for (int i = 0; i < featuresArray.Length; i++)
            {
                featuresArray[i] = predictionData[i].Features;
            }

            switch (type)
            {
            case ClassifierType.DecisionTree:
                return(tree.Decide(featuresArray));

            case ClassifierType.LDA:
                return(pipeline.Decide(featuresArray));

            case ClassifierType.SVM:
                return(convertBoolArray(svm.Decide(featuresArray)));

            case ClassifierType.Bayes:
                return(bayes.Decide(featuresArray));
            }

            return(null);
        }
        public void Probe()
        {
            pb = csv.ImportFromCsvFile(PROBE);
            for (int i = 0; i < pb.Rows.Count; i++)
            {
                int[] query = codebook.Transform(new[, ]
                {
                    { "Buying", pb.Rows[i].ItemArray[0].ToString() },
                    { "Maint", pb.Rows[i].ItemArray[1].ToString() },
                    { "doors", pb.Rows[i].ItemArray[2].ToString() },
                    { "persons", pb.Rows[i].ItemArray[3].ToString() },
                    { "Lug_boot", pb.Rows[i].ItemArray[4].ToString() },
                    { "Safety", pb.Rows[i].ItemArray[5].ToString() }
                });


                int predicted = tree.Decide(query);
                if (predicted != -1)
                {
                    string answer = codebook.Revert("CarType", predicted);
                    result += "BUYING--" + pb.Rows[i].ItemArray[0].ToString() + "-->" + "MAINT--" + pb.Rows[i].ItemArray[1].ToString() + "-->" + "DOORS--"
                              + pb.Rows[i].ItemArray[2].ToString() + "-->" + "PERSONS--" + pb.Rows[i].ItemArray[3].ToString() + "-->" + "LUG_BOOT--" + pb.Rows[i].ItemArray[4].ToString() + "-->" + "SAFETY--" + pb.Rows[i].ItemArray[4].ToString() + "-->" + answer.ToUpper();
                    result += "\r\n";
                }
                else
                {
                    result += "BUYING--" + pb.Rows[i].ItemArray[0].ToString() + "-->" + "MAINT--" + pb.Rows[i].ItemArray[1].ToString() + "-->" + "DOORS--"
                              + pb.Rows[i].ItemArray[2].ToString() + "-->" + "PERSONS--" + pb.Rows[i].ItemArray[3].ToString() + "-->" + "LUG_BOOT--" + pb.Rows[i].ItemArray[4].ToString() + "-->" + "SAFETY--" + pb.Rows[i].ItemArray[4].ToString() + "-->" + "Not Answer Found";
                    result += "\r\n";
                }
            }
        }
Ejemplo n.º 5
0
        private List <productos> revisarProductos(DataTable data)
        {
            var codebook = new Codification(data);

            int numCategorias = db.categorias.Count();

            DecisionVariable[] attributes =
            {
                new DecisionVariable("Categoria", numCategorias),  // 3 possible values (Sunny, overcast, rain)
                                new DecisionVariable("Precio", 5), // 3 possible values (Hot, mild, cool)  
                 
            };

            int classCount = 2; // 2 possible output values for playing tennis: yes or no

            DecisionTree tree = new DecisionTree(attributes, classCount);

            // Create a new instance of the ID3 algorithm
            ID3Learning id3learning = new ID3Learning(tree);

            // Translate our training data into integer symbols using our codebook:
            DataTable symbols = codebook.Apply(data);

            int[][] inputs  = symbols.ToIntArray("Categoria", "Precio");
            int[]   outputs = symbols.ToIntArray("recomendar").GetColumn(0);

            // Learn the training instances!
            id3learning.Run(inputs, outputs);

            // Compute the training error when predicting training instances
            double error = new ZeroOneLoss(outputs).Loss(tree.Decide(inputs));

            // The tree can now be queried for new examples through
            // its decide method. For example, we can create a query

            List <productos> product = db.productos.ToList();

            foreach (productos item in db.productos.ToList())
            {
                int[] query = codebook.Transform(new[, ] {
                    { "Categoria", Convert.ToString(item.fkCategoria) },
                    { "Precio", devolverTipoPrecio(item.precio) }
                });

                // And then predict the label using
                int predicted = tree.Decide(query);  // result will be 0

                // We can translate it back to strings using
                string answer = codebook.Revert("recomendar", predicted); // Answer will be: "No"
                if (answer.Equals("no"))
                {
                    product.Remove(item);
                }
            }
            return(product);
        }
        public override Task <List <GeneralConfusionMatrix> > ComputeFoldedConfusionMatrixAsync(ClassificationModel classificationModel, int folds)
        {
            return(Task.Factory.StartNew(() =>
            {
                int numFeatures = classificationModel.FeatureVectors.Count;
                DecisionVariable[] decisionVariables = Enumerable.ToArray(classificationModel.Bands.Select(b => DecisionVariable.Continuous(b.ToString())));

                double[][] input = new double[numFeatures][];
                int[] responses = new int[numFeatures];

                for (int featureIndex = 0; featureIndex < classificationModel.FeatureVectors.Count; ++featureIndex)
                {
                    var featureVector = classificationModel.FeatureVectors[featureIndex];

                    input[featureIndex] = Array.ConvertAll(featureVector.FeatureVector.BandIntensities, s => (double)s / ushort.MaxValue);
                    responses[featureIndex] = featureVector.FeatureClass;
                }

                List <GeneralConfusionMatrix> confusionMatrices = new List <GeneralConfusionMatrix>();

                // Create a new Cross-validation algorithm passing the data set size and the number of folds
                var crossvalidation = new CrossValidation(input.Length, folds);

                crossvalidation.Fitting = delegate(int k, int[] indicesTrain, int[] indicesValidation)
                {
                    // Lets now grab the training data:
                    var trainingInputs = input.Get(indicesTrain);
                    var trainingOutputs = responses.Get(indicesTrain);

                    // And now the validation data:
                    var validationInputs = input.Get(indicesValidation);
                    var validationOutputs = responses.Get(indicesValidation);

                    var tree = new DecisionTree(decisionVariables, Enum.GetValues(typeof(LandcoverTypeViewModel)).Length);
                    C45Learning id3Learning = new C45Learning(tree);
                    id3Learning.Learn(trainingInputs, trainingOutputs);

                    var predictedTraining = tree.Decide(trainingInputs);
                    var predictedValidation = tree.Decide(validationInputs);

                    double trainingError = new ZeroOneLoss(trainingOutputs).Loss(predictedTraining);
                    double validationError = new ZeroOneLoss(validationOutputs).Loss(predictedValidation);

                    GeneralConfusionMatrix confusionMatrix = new GeneralConfusionMatrix(Enum.GetValues(typeof(LandcoverTypeViewModel)).Length - 1, validationOutputs, predictedValidation);
                    confusionMatrices.Add(confusionMatrix);

                    // Return a new information structure containing the model and the errors achieved.
                    return new CrossValidationValues(trainingError, validationError);
                };

                var result = crossvalidation.Compute();

                return confusionMatrices;
            }));
        }
Ejemplo n.º 7
0
        public double Test(DataTable test)
        {
            DataTable convertedData = codeBook.Apply(test);

            //Convierte los valores traducidos a inputs y el output esperado.
            double[][] inputs  = convertedData.ToJagged(headers);
            int[]      outputs = convertedData.ToArray <int>("G3");

            double error = new ZeroOneLoss(outputs).Loss(tree.Decide(inputs));

            return(1 - error);
        }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            DataTable table = new Accord.IO.CsvReader("C:\\Users\\michael\\Downloads\\JulyToOct2015Test.csv", true).ToTable();

            // Convert the DataTable to input and output vectors
            double[][] inputs  = table.ToJagged <double>("BookToPrice", "DividendYield", "DebtToEquity", "MarketBeta", "SectorID");
            int[]      outputs = table.Columns["MonthlyReturn"].ToArray <int>();


            //SecurityID BookToPrice DividendYield EarningsYield   SalesGrowth AssetsToEquity  MarketCap MarketBeta  DebtToEquity    1YrVol  5YrVol  3YrVol ExposureToCurrencyGain  SectorID countryID

            DecisionTree tree = new DecisionTree(
                inputs: new List <DecisionVariable>
            {
                DecisionVariable.Continuous("BookToPrice"),
                DecisionVariable.Continuous("DividendYield"),
                DecisionVariable.Continuous("DebtToEquity"),
                DecisionVariable.Continuous("MarketBeta"),
                DecisionVariable.Discrete("SectorID", 11)
            },
                classes: 2);

            C45Learning teacher = new C45Learning(tree);

            teacher.Learn(inputs, outputs);
            int[] answers = tree.Decide(inputs);


            // Plot the results
            // ScatterplotBox.Show("Expected results", inputs, outputs);
            //ScatterplotBox.Show("Ans", inputs, answers)
            //    .Hold();
        }
Ejemplo n.º 9
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));
     }
 }
Ejemplo n.º 10
0
        public bool classifierDT(data d)
        {
            int D = d.d;

            double[] input = new double[D];
            int      output;

            for (int i = 0; i < D; ++i)
            {
                input[i] = d.msg[i];
            }

            output = tree.Decide(input);

            return(output == 1);
        }
Ejemplo n.º 11
0
    public void ChooseBuilding()
    {
        StopSound();
        _buildingDecision.Reset();
        foreach (System.Reflection.MethodInfo method in this.GetType().GetMethods())
        {
            if (((BuildingChoiceMethod[])method.GetCustomAttributes(typeof(BuildingChoiceMethod), true)).Length > 0)
            {
                DecisionTree <GameObject> .Percept p = _buildingDecision.GetPercept(method.Name);
                if (p != null && ((Func <bool>)Delegate.CreateDelegate(typeof(Func <bool>), this, method))())
                {
                    p.Activate();
                }
            }
        }
        GameObject nextBuild = _buildingDecision.Decide();
        bool       water     = (nextBuild.name == "FishermanHut");

        _target          = _village.AddBuilding(_construction, ChooseEmplacement(water)).GetComponent <ConstructionSite>();
        _target.Building = nextBuild;
        string[] props = Manager.Instance.Properties.GetElement("BuildingCost." + _target.Building.name).GetElements();
        for (int i = 1; i < props.Length; i++)
        {
            props[i] = props[i].Remove(0, _target.Building.name.Length + 1);
        }
        for (int i = 1; i < props.Length - 1; i++)
        {
            _target.Needed[props[i]] = (int)(float)Manager.Instance.Properties.GetElement("BuildingCost." + _target.Building.name + "." + props[i]).Value;
        }
        _target.Duration = (float)Manager.Instance.Properties.GetElement("BuildingCost." + _target.Building.name + ".Duration").Value;
    }
Ejemplo n.º 12
0
 private double computeError()
 {
     return(new ZeroOneLoss(outputs)
     {
         Mean = true
     }.Loss(tree.Decide(inputs)));
 }
Ejemplo n.º 13
0
        /// <summary>
        ///   Tests the previously created tree into a new set of data.
        /// </summary>
        ///
        private void btnTestingRun_Click(object sender, EventArgs e)
        {
            if (tree == null || dgvTestingSource.DataSource == null)
            {
                MessageBox.Show("Please create a machine first.");
                return;
            }


            // Creates a matrix from the entire source data table
            double[][] table = (dgvLearningSource.DataSource as DataTable).ToJagged(out columnNames);

            // Get only the input vector values (first two columns)
            double[][] inputs = table.GetColumns(0, 1);

            // Get the expected output labels (last column)
            int[] expected = table.GetColumn(2).ToInt32();


            // Compute the actual tree outputs
            int[] actual = tree.Decide(inputs);


            // Use confusion matrix to compute some statistics.
            ConfusionMatrix confusionMatrix = new ConfusionMatrix(actual, expected, 1, 0);

            dgvPerformance.DataSource = new [] { confusionMatrix };

            // Create performance scatter plot
            CreateResultScatterplot(zedGraphControl1, inputs, expected.ToDouble(), actual.ToDouble());
        }
Ejemplo n.º 14
0
        private void ComputeInference()
        {
            var codebook = new Codification();

            codebook.Learn(tradeTable);

            DataTable symbols = codebook.Apply(tradeTable);

            string[]   inputNames = new[] { "Strike", "MarketPrice", "Notional" };
            double[][] inputs     = tradeTable.ToJagged(inputNames);
            int[]      outputs    = tradeTable.ToArray <int>("Result");


            var teacher = new C45Learning()
            {
                Attributes = DecisionVariable.FromCodebook(codebook, inputNames)
            };


            DecisionTree tree = teacher.Learn(inputs, outputs);

            int[]       predicted = tree.Decide(inputs);
            double      error     = new ZeroOneLoss(outputs).Loss(predicted);
            DecisionSet rules     = tree.ToRules();

            var str = rules.ToString();

            textBoxInferredRules.Text = str;
        }
        public void Learn(List <BaseAttribute <T> > attributeColumns, BaseAttribute <T> outputAttributeColumn)
        {
            // Create a new instance of the ID3 algorithm
            ID3Learning id3learning = new ID3Learning(DecisionTree);

            // Translate our training data into integer symbols using our codebook:
            DataTable symbols = Codebook.Apply(Data);

            var columnNames = attributeColumns.Select(attribute => attribute.Name).ToArray();

            int[][] inputs  = symbols.ToJagged <int>(columnNames);
            int[]   outputs = symbols.ToJagged <int>(outputAttributeColumn.Name).GetColumn(0);

            // Learn the training instances!
            DecisionTree = id3learning.Learn(inputs, outputs);

            double error = new ZeroOneLoss(outputs).Loss(DecisionTree.Decide(inputs));

            Debug.WriteLine(error);

            // Moreover, we may decide to convert our tree to a set of rules:
            DecisionSet rules = DecisionTree.ToRules();
            // And using the codebook, we can inspect the tree reasoning:
            string ruleText = rules.ToString(Codebook as Codification <string>, outputAttributeColumn.Name,
                                             System.Globalization.CultureInfo.InvariantCulture);

            Debug.WriteLine(ruleText);
        }
Ejemplo n.º 16
0
    // Compute car control based on sensor readings
    void ComputeControl(float sensorL, float sensorF, float sensorR, float carVelocity, float forward)
    {
        // Inputs
        float[][] inputsT = new float[1][];
        inputsT[0]    = new float[4];
        inputsT[0][0] = sensorL;
        inputsT[0][1] = sensorF;
        inputsT[0][2] = sensorR;
        inputsT[0][3] = carVelocity;

        float[][] inputs = new float[1][];
        inputs[0]    = new float[5];
        inputs[0][0] = sensorL;
        inputs[0][1] = sensorF;
        inputs[0][2] = sensorR;
        inputs[0][3] = carVelocity;
        inputs[0][4] = forward;

        answerThrust = treeThrust.Decide(inputsT);
        answerSteer  = treeSteer.Decide(inputs);

        // Thrust

        if (answerThrust[0] == 1)
        {
            thrust = pod[1];
            //Debug.Log("Acelera!");
        }
        else if (answerThrust[0] == 0)
        {
            thrust = -pod[2];
            //Debug.Log("Freia!");
        }

        // Steer

        if (answerSteer[0] == 1)
        {
            if (sensorLeft > sensorRight)
            {
                steer = pod[3];
                //Debug.Log("Vire a Esquerda!");
            }
            else
            {
                steer = -pod[3];
                //Debug.Log("Vire a Direita!");
            }
        }
        else if (answerSteer[0] == 0)
        {
            steer = 0;
            //Debug.Log("Vai reto!");
        }

        // Command
        rb.AddRelativeForce(new Vector2(0f, thrust));
        rb.AddTorque(steer);
    }
Ejemplo n.º 17
0
        public string getRecommendationsByUsers(string id = "user4")
        {
            DataTable data = new DataTable("dataTable");

            PopulateHead(data);
            PopulateTable(data, id);

            Codification codification = new Codification(data);
            DataTable    codifiedData = codification.Apply(data);

            int[][] input = codifiedData.ToJagged <int>("Age", "Gender");

            int[] predictions = codifiedData.ToArray <int>("Best Genre");

            ID3Learning decisionTreeLearningAlgorithm = new ID3Learning {
            };

            try
            {
                var   customer = _context.Customers.Where(c => c.Username == id).FirstOrDefault();
                int[] query;
                if (customer.Age <= 12)
                {
                    query = codification.Transform(new[, ] {
                        { "Age", "0-12" }, { "Gender", customer.Gender.ToString() }
                    });
                }
                else if (12 < customer.Age && customer.Age <= 25)
                {
                    query = codification.Transform(new[, ] {
                        { "Age", "13-25" }, { "Gender", customer.Gender.ToString() }
                    });
                }
                else if (25 < customer.Age && customer.Age < 40)
                {
                    query = codification.Transform(new[, ] {
                        { "Age", "26-39" }, { "Gender", customer.Gender.ToString() }
                    });
                }
                else
                {
                    query = codification.Transform(new[, ] {
                        { "Age", "40+" }, { "Gender", customer.Gender.ToString() }
                    });
                }

                DecisionTree decisionTree = decisionTreeLearningAlgorithm.Learn(input, predictions);
                int          result       = decisionTree.Decide(query);
                string       diagnosis    = codification.Revert("Best Genre", result);
                return(diagnosis);
            }
            catch (Exception)
            {
                return("Unfortunatly No Matches Were Found");

                throw;
            }
        }
Ejemplo n.º 18
0
        public override Class Classify(TObj obj)
        {
            if (m_Result == null)
            {
                throw new MLException("Decision tree is empty");
            }

            return(m_Result.Decide(obj));
        }
Ejemplo n.º 19
0
        public string PredictTopic(DocumentData documentData)
        {
            ArgumentValidator.ValidateObject(documentData);

            var query = codeBook.Transform(input);

            decisionTree.Decide(query);
            throw new System.NotImplementedException();
        }
        public string Evaluate(string branch, string cType, string gender, string payment)
        {
            // The tree can now be queried for new examples through
            // its decide method. For example, we can create a query
            int[] query = codebook.Transform(new[, ]
            {
                { "Branch", branch },
                { "Customer type", cType },
                { "Gender", gender },
                { "Payment", payment }
            });

            // And then predict the label using
            int predicted = tree.Decide(query);  // result will be 0

            // We can translate it back to strings using
            return(codebook.Revert("Product line", predicted)); // Answer will be: "No"
        }
Ejemplo n.º 21
0
        public double treeDeciding()
        {
            double val = tree.Decide(new double[] { lam.Age, lam.Gender, lam.Total_Bilirubin, lam.Direct_Bilirubin
                                                    , lam.Alkaline_Phosphotase, lam.Alamine_Aminotransferase
                                                    , lam.Aspartate_Aminotransferase, lam.Total_Protiens
                                                    , lam.Albumin, lam.Albumin_and_Globulin_Ratio });

            return(val);
        }
Ejemplo n.º 22
0
        public static void Main(string[] args)
        {
            //getting example data
            Iris iris = new Iris();

            //we are creating training data arrays
            double[][] input  = new double[147][];
            int[]      output = new int[147];

            //we process 'Iris' data and delete 1 from each type for later test purpose
            int j = 0;

            for (int i = 0; i < 147; i++)
            {
                if (i != 0 || i != 50 || i != 100)
                {
                    input[j]  = new double[4];
                    output[j] = iris.ClassLabels[i];
                    for (int k = 0; k < 4; k++)
                    {
                        input[j][k] = iris.Instances[i][k];
                    }
                    j++;
                }
            }

            //learning algorithm for decision tree
            C45Learning teacher = new C45Learning(new[] {
                DecisionVariable.Continuous(iris.VariableNames[0]),
                DecisionVariable.Continuous(iris.VariableNames[1]),
                DecisionVariable.Continuous(iris.VariableNames[2]),
                DecisionVariable.Continuous(iris.VariableNames[3]),
            });

            //model learning
            DecisionTree tree = teacher.Learn(input, output);

            //If we would have some other irises we could just wrote like this
            //DecisionTree tree = teacher.Learn(iris.Instances, iris.ClassLabels);
            //but we prefer to left some for test purpose (to check if our programm is working fine)

            //testing our model
            double[][] test    = { iris.Instances[0], iris.Instances[50], iris.Instances[100] };
            int[]      answers = tree.Decide(test);

            Console.WriteLine("Answer should be as follow:\n0,1,2,\nAnswer is:");

            foreach (int ans in answers)
            {
                Console.Write(ans + ",");
            }

            Console.Write("\nPress any key to continue . . . ");
            Console.ReadKey(true);
        }
Ejemplo n.º 23
0
        /// <summary>
        ///   Creates and learns a Decision Tree to recognize the
        ///   previously loaded dataset using the current settings.
        /// </summary>
        ///
        private void btnCreate_Click(object sender, EventArgs e)
        {
            if (dgvLearningSource.DataSource == null)
            {
                MessageBox.Show("Please load some data first.");
                return;
            }

            // Finishes and save any pending changes to the given data
            dgvLearningSource.EndEdit();



            // Creates a matrix from the entire source data table
            double[,] table = (dgvLearningSource.DataSource as DataTable).ToMatrix(out columnNames);

            // Get only the input vector values (first two columns)
            double[][] inputs = table.GetColumns(0, 1).ToJagged();

            // Get only the output labels (last column)
            int[] outputs = table.GetColumn(2).ToInt32();


            // Specify the input variables
            DecisionVariable[] variables =
            {
                new DecisionVariable("x", DecisionVariableKind.Continuous),
                new DecisionVariable("y", DecisionVariableKind.Continuous),
            };

            // Create the C4.5 learning algorithm
            var c45 = new C45Learning(variables);

            // Learn the decision tree using C4.5
            tree = c45.Learn(inputs, outputs);

            // Show the learned tree in the view
            decisionTreeView1.TreeSource = tree;


            // Get the ranges for each variable (X and Y)
            DoubleRange[] ranges = table.GetRange(0);

            // Generate a Cartesian coordinate system
            double[][] map = Matrix.Cartesian(
                Vector.Interval(ranges[0], 0.05),
                Vector.Interval(ranges[1], 0.05));

            // Classify each point in the Cartesian coordinate system
            double[,] surface = map.ToMatrix().InsertColumn(tree.Decide(map));

            CreateScatterplot(zedGraphControl2, surface);

            lbStatus.Text = "Learning finished! Click the other tabs to explore results!";
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Prepare truth and prediction for given test set
        /// </summary>
        /// <param name="testData"></param>
        /// <param name="decisionTree"></param>
        /// <param name="truth"></param>
        /// <param name="predictions"></param>
        private static void EvaluateDecisionTree(List <double[]> testData, DecisionTree decisionTree, out double[] truth, out double[] predictions)
        {
            // Prepare test data
            var input = testData.ToArray()
                        .GetColumns(Vector.Range(0, GlobalVariables.Dimensions));

            truth       = testData.Select(t => t[t.Length - 1]).ToArray();
            predictions = decisionTree
                          .Decide(input)
                          .To <double[]>();
        }
Ejemplo n.º 25
0
        static void Main(string[] args)
        {
            var data = new ExcelReader(@"c:\temp\accordemo\accordemo\titanic.xls").GetWorksheet("titanic3");

            data.Rows.RemoveAt(data.Rows.Count - 1);
            var          d     = new Elimination("age").Apply(data);
            var          fdata = new Codification(d, "sex").Apply(d);
            var          outp  = fdata.Columns["survived"].ToArray <int>();
            var          input = fdata.ToArray <double>("pclass", "sex", "age", "parch", "sibsp");
            DecisionTree T     = new DecisionTree(
                DecisionVariable.FromData(input), 2);
            var learn = new C45Learning(T);

            learn.Run(input, outp);
            var r1 = T.Decide(new double[] { 0, 1, 23, 0, 0 });
            var r2 = T.Decide(new double[] { 1, 0, 30, 1, 1 });

            Console.WriteLine($"Male={r1}, Female={r2}");
            Console.ReadKey();
        }
Ejemplo n.º 26
0
        public override ClassScore[] PredictTokens(TObj obj, int cnt)
        {
            if (m_Result == null)
            {
                throw new MLException("Decision tree is empty");
            }

            var cls   = m_Result.Decide(obj);
            var score = new ClassScore(cls, 1);

            return(new ClassScore[] { score });
        }
Ejemplo n.º 27
0
    // Update is called once per frame
    void Update()
    {
        timer -= Time.deltaTime;
        if (timer <= 0f)
        {
            game_state_representation.state[0] = customvalue;

            string result = DecisionModule.Decide(game_state_representation);
            Debug.Log(result);
            timer = 1;
        }
    }
        public string Decide(List <BaseAttribute <T> > attributes, BaseAttribute <T> attributeColumn)
        {
            var columnNames = attributes.Select(attribute => attribute.Name).ToArray();
            var values      = attributes.Select(attribute => attribute.Value).ToArray();

            int[] query = Codebook.Transform(columnNames, values);

            int output = DecisionTree.Decide(query);

            var answer = Codebook.Revert(attributeColumn.Name, output);

            return(answer.ToString());
        }
        private double computeError()
        {
            int error = 0;

            for (int i = 0; i < inputs.Length; i++)
            {
                int actual   = tree.Decide(inputs[i]);
                int expected = outputs[i];
                if (actual != expected)
                {
                    error++;
                }
            }

            return(error / (double)inputs.Length);
        }
Ejemplo n.º 30
0
    void Update()
    {
        if (GameOver.reset)                                                                     // Resetando as variáveis caso o jogo seja reiniciado
        {
            answer             = null;
            firstKeyCollected  = null;
            secondKeyCollected = null;
            thirdKeyCollected  = null;
            exit1.GetComponent <MeshRenderer> ().enabled = true;
            exit2.GetComponent <MeshRenderer> ().enabled = true;
            firstExitOpen                   = false;
            secondExitOpen                  = false;
            PlayerControl.score             = 0;
            CollisionBehaviors.keyCollected = null;

            GameOver.reset = false;
        }


        if (firstKeyCollected != null &&                                                // Quando as três chaves forem coletadas, a condição será atendida
            secondKeyCollected != null &&
            thirdKeyCollected != null)
        {
            int[] query = codebook.Transform(new[, ] {                          //	Tabela cujo valor será tratado
                { "First key", firstKeyCollected },
                { "Second key", secondKeyCollected },
                { "Third key", thirdKeyCollected }
            });

            // Passando a tabela a ser tratada como argumento da árvore treinada | tree.Decide(tabelaParaTratar)
            // O resultado tratado (predicted) será em integer symbol
            int predicted = tree.Decide(query);
            answer = codebook.Revert("Exit", predicted);                        // Traduzindo o integer symbol para string
            Debug.Log(answer);

            if (answer == "First")
            {
                exit1.GetComponent <MeshRenderer> ().enabled = false;
                firstExitOpen = true;
            }
            else if (answer == "Second")
            {
                exit2.GetComponent <MeshRenderer> ().enabled = false;
                secondExitOpen = true;
            }
        }
    }