Пример #1
0
    /// <summary>
    /// Makes a decision and returns a tree action recursively
    /// </summary>
    /// <returns>The Action.</returns>
    /// <param name="root">Root Node</param>
    public override TreeAction MakeDecision(DecisionTreeNode root)
    {
        if(root == null)
            return null;

        if(root is TreeAction)
        {
            TreeAction action = (TreeAction) root;
            return action;
        }

        return MakeDecision(root.GetBranch());
    }
Пример #2
0
        private void FillNode(ref Dictionary <IDecisionTreeNode, double> validityIndexByNode, InstanceModel model, ref Dictionary <IDecisionTreeNode, IEnumerable <Tuple <Instance, double> > > instancesByNode,
                              Feature classFeature, ref Dictionary <IDecisionTreeNode, int> levelByNode, List <SelectorContext> currentContext, ref int leafCount)
        {
            IDecisionTreeNode node           = null;
            double            bestIndexValue = Double.MinValue;

            foreach (var currentNode in validityIndexByNode.Keys)
            {
                if (bestIndexValue < validityIndexByNode[currentNode])
                {
                    bestIndexValue = validityIndexByNode[currentNode];
                    node           = currentNode;
                }
            }

            if (node != null)
            {
                int level     = levelByNode[node];
                var instances = instancesByNode[node];

                int whichBetterToFind = 1;
                if (OnSelectingWhichBetterSplit != null)
                {
                    whichBetterToFind = OnSelectingWhichBetterSplit(node, level);
                }
                WiningSplitSelector winingSplitSelector = new WiningSplitSelector(whichBetterToFind)
                {
                    CanAcceptChildSelector = this.CanAcceptChildSelector,
                };
                foreach (var feature in OnSelectingFeaturesToConsider(model.Features, level))
                {
                    if (feature != classFeature)
                    {
                        ISplitIterator splitIterator = SplitIteratorProvider.GetSplitIterator(model, feature, classFeature);
                        if (splitIterator == null)
                        {
                            throw new InvalidOperationException(string.Format("Undefined iterator for feature {0}",
                                                                              feature));
                        }
                        splitIterator.Initialize(feature, instances);
                        while (splitIterator.FindNext())
                        {
                            double currentGain = DistributionEvaluator.Evaluate(node.Data,
                                                                                splitIterator.CurrentDistribution);
                            if (currentGain > MinimalSplitGain || leafCount < ClusterCount)
                            {
                                if (OnSplitEvaluation != null)
                                {
                                    OnSplitEvaluation(node, splitIterator, currentContext);
                                }
                                winingSplitSelector.EvaluateThis(currentGain, splitIterator, level);
                            }
                        }
                    }
                }

                if (winingSplitSelector.IsWinner())
                {
                    IChildSelector maxSelector = winingSplitSelector.WinningSelector;
                    node.ChildSelector = maxSelector;
                    node.Children      = new IDecisionTreeNode[maxSelector.ChildrenCount];
                    var instancesPerChildNode =
                        childrenInstanceCreator.CreateChildrenInstances(instances, maxSelector, double.MinValue);

                    for (int i = 0; i < maxSelector.ChildrenCount; i++)
                    {
                        var childNode = new DecisionTreeNode {
                            Parent = node
                        };
                        node.Children[i] = childNode;
                        childNode.Data   = winingSplitSelector.WinningDistribution[i];
                        SelectorContext context = null;
                        if (OnSplitEvaluation != null)
                        {
                            context = new SelectorContext
                            {
                                Index    = i,
                                Selector = node.ChildSelector,
                            };
                            currentContext.Add(context);
                        }

                        double currentBestValidityIndex = double.MinValue;
                        foreach (var feature in OnSelectingFeaturesToConsider(model.Features, level))
                        {
                            if (feature != classFeature)
                            {
                                ISplitIterator splitIterator = SplitIteratorProvider.GetSplitIterator(model, feature, classFeature);
                                if (splitIterator == null)
                                {
                                    throw new InvalidOperationException(string.Format("Undefined iterator for feature {0}",
                                                                                      feature));
                                }
                                splitIterator.Initialize(feature, instancesPerChildNode[i]);
                                while (splitIterator.FindNext())
                                {
                                    double currentGain = DistributionEvaluator.Evaluate(node.Data,
                                                                                        splitIterator.CurrentDistribution);
                                    if (currentGain > currentBestValidityIndex)
                                    {
                                        if (OnSplitEvaluation != null)
                                        {
                                            OnSplitEvaluation(node, splitIterator, currentContext);
                                        }

                                        currentBestValidityIndex = currentGain;
                                    }
                                }
                            }
                        }

                        if (currentBestValidityIndex > validityIndexByNode[node] || leafCount < ClusterCount)
                        {
                            validityIndexByNode.Add(childNode, currentBestValidityIndex);
                            instancesByNode.Add(childNode, instancesPerChildNode[i]);
                            levelByNode.Add(childNode, level + 1);
                        }

                        if (OnSplitEvaluation != null)
                        {
                            currentContext.Remove(context);
                        }
                    }

                    validityIndexByNode.Remove(node);
                    instancesByNode.Remove(node);
                    levelByNode.Remove(node);
                    leafCount++;

                    if (leafCount < 4 * ClusterCount)
                    {
                        FillNode(ref validityIndexByNode, model, ref instancesByNode, classFeature, ref levelByNode, currentContext, ref leafCount);
                    }
                }
            }
        }
Пример #3
0
 public DecisionTree(DecisionTreeNode[] tree)
 {
     nodes = tree;
     first = tree[0];
 }
Пример #4
0
 public LinkGenerationDecisionTree(IReadOnlyList <OutboundMatch> entries)
 {
     _root = DecisionTreeBuilder <OutboundMatch> .GenerateTree(
         entries,
         new OutboundMatchClassifier());
 }
Пример #5
0
    /// <summary>
    /// Constructor for Decision Tree
    /// </summary>
    /// <param name="agent"></param>
    /// <param name="inventory"></param>
    /// <param name="actions"></param>
    /// <param name="data"></param>
    /// <param name="sensing"></param>
    /// <param name="debugging"></param>
    public DecisionTreeRoot(DecisionTreeBlackboard blackboard, bool debugging = false)
    {
        blackboard.m_debugMode = debugging;
        // setting variables that can be retrieved via properties

        Condition testCondition = new Condition(DecisionTreeConditionList.TestCondition);

        Action testAction = new Action(DecisionTreeActionList.TestAction);

        DecisionTreeAction testDTAction = new DecisionTreeAction("Test Action", blackboard, testAction);

        DecisionTreeCondition testDTCondtition = new DecisionTreeCondition("Test Condition", blackboard, testCondition, testDTAction, testDTAction);

        m_decisionTreeRoot = testDTCondtition;
        //setting all the condition
        //Condition flagInSight                       = new Condition(DecisionTreeConditionList.IsFlagInSight);
        //Condition isEnemyInSight                    = new Condition(DecisionTreeConditionList.IsEnemyInSight);
        //Condition hasPowerUp                        = new Condition(DecisionTreeConditionList.HasPowerUp);
        //Condition isItemInView                      = new Condition(DecisionTreeConditionList.HasCollectableInSight);
        //Condition hasFlagInInventory                = new Condition(DecisionTreeConditionList.HasFlagInInventory);
        //Condition isFriendlyTooClose                = new Condition(DecisionTreeConditionList.IsFriendlyTooClose);
        //Condition hasHalfHPandHealthKit             = new Condition(DecisionTreeConditionList.IsHalfHPWithHealthKit);
        //Condition isEnemyNearFriendlyFlagAndBase    = new Condition(DecisionTreeConditionList.IsEnemyCloseToFriendlyFlagAndBase);

        ////setting up all actions
        //Action moveRand         = new Action(DecisionTreeActionList.MoveToRandomLocation);
        //Action attackEnem       = new Action(DecisionTreeActionList.AttackEnemyInSight);
        //Action collectFlag      = new Action(DecisionTreeActionList.CollectFlagInSight);
        //Action collectItem      = new Action(DecisionTreeActionList.CollectItemInSight);
        //Action usePowerUp       = new Action(DecisionTreeActionList.UsePowerUp);
        //Action returnFlagToBase = new Action(DecisionTreeActionList.ReturnFlagToBase);
        //Action avoidFriendly    = new Action(DecisionTreeActionList.AvoidFriendly);
        //Action useHealthkit     = new Action(DecisionTreeActionList.UseHealthKit);
        //Action interceptEnemy   = new Action(DecisionTreeActionList.InterceptEnemy);


        //// Creating the decision tree leaf nodes aka Actions
        //DecisionTreeAction moveRandomlyDTAction         = new DecisionTreeAction("Random", this, moveRand);
        //DecisionTreeAction attackEnemyDTAction          = new DecisionTreeAction("Random", this, attackEnem);
        //DecisionTreeAction collectFlagDTAction          = new DecisionTreeAction("Collecting Flag", this, collectFlag);
        //DecisionTreeAction collectItemDTAction          = new DecisionTreeAction("Collectin Item", this, collectItem);
        //DecisionTreeAction usePowerUpDTAction           = new DecisionTreeAction("Using Power Up", this, usePowerUp);
        //DecisionTreeAction returnFlagToBaseDTAction     = new DecisionTreeAction("Return to Base", this, returnFlagToBase);
        //DecisionTreeAction avoidFriendlyDTAction        = new DecisionTreeAction("Avoid Friendly", this, avoidFriendly);
        //DecisionTreeAction useHealthKitDTAction         = new DecisionTreeAction("Use Health kit at low HP", this, useHealthkit);
        //DecisionTreeAction interceptEnemyDTAction       = new DecisionTreeAction("Intercepting Enemy", this, interceptEnemy);


        //// Creating the decision tree nodes.
        ////Note that the order is important as you have to add the child nodes before the node exists.
        ////this way the decision tree is build up from its deepest level to its highest
        //DecisionTreeCondition isFriendlyTooCloseDTCondition     = new DecisionTreeCondition("Is Friendly too close", this, isFriendlyTooClose, moveRandomlyDTAction, avoidFriendlyDTAction);
        //DecisionTreeCondition powerUpInInventoryDTCondition     = new DecisionTreeCondition("Power Up In Inventory", this, hasPowerUp, attackEnemyDTAction, usePowerUpDTAction);
        //DecisionTreeCondition collectableInViewDTCondition      = new DecisionTreeCondition("CollectableInViewDTCondition", this, isItemInView, isFriendlyTooCloseDTCondition, collectItemDTAction);
        //DecisionTreeCondition enemyNearFlagAndBaseDTCondition   = new DecisionTreeCondition("Checking if Enemy is near Friendly Flag", this, isEnemyNearFriendlyFlagAndBase, powerUpInInventoryDTCondition, interceptEnemyDTAction);
        //DecisionTreeCondition enemyInSightDTCondition           = new DecisionTreeCondition("Enemy In Sight", this, isEnemyInSight, collectableInViewDTCondition, enemyNearFlagAndBaseDTCondition);
        //DecisionTreeCondition hasFlagInSightDTCondition         = new DecisionTreeCondition("Check For Enemy Flag", this, flagInSight, enemyInSightDTCondition, collectFlagDTAction);

        //DecisionTreeCondition hasFlagInInventoryDTCondition     = new DecisionTreeCondition("Has Flag In Inventory", this, hasFlagInInventory, hasFlagInSightDTCondition, returnFlagToBaseDTAction);
        //DecisionTreeCondition hasLowHPandHealthKitDTCondition   = new DecisionTreeCondition("Check Health and search Inventory for Health Kit", this, hasHalfHPandHealthKit, hasFlagInInventoryDTCondition, useHealthKitDTAction);



        ////Set a starting point for the decision tree
        //m_decisionTreeRoot = hasLowHPandHealthKitDTCondition;
    }
Пример #6
0
 public DecisionTree(DecisionTreeNode root)
 {
     this.root = root;
 }
Пример #7
0
        private static void RecurseAndPartition(List <LabeledPoint> trainingPoints, List <SplittingQuestion> splittingQuestions,
                                                int currentRecursionLevel, DecisionTreeOptions options, DecisionTreeNode currentNode, Random random)
        {
            Console.WriteLine($"{new String('-', currentRecursionLevel)}{currentRecursionLevel}");

            if (currentRecursionLevel >= options.MaximumNumberOfRecursionLevels)
            {
                // create leaf node
                MakeLeafNode(currentNode, trainingPoints);
            }
            else
            {
                double            currentShannonEntropy = ComputeShannonEntropy(trainingPoints);
                double            highestGain           = double.MinValue;
                SplittingQuestion bestSplittingQuestion = null;

                //for (int s = 0; s < splittingQuestions.Count; s++)
                Parallel.For(0, splittingQuestions.Count, s =>
                {
                    //Console.Write(".");
                    //Interlocked.Increment(ref t);
                    //Console.WriteLine($"{t}/{splittingQuestions.Count}");

                    //List<LabeledPoint> leftBucket1 = new List<LabeledPoint>();
                    //List<LabeledPoint> rightBucket1 = new List<LabeledPoint>();

                    List <LabeledPointGroup> leftBucket = new List <LabeledPointGroup>();
                    leftBucket.Add(new LabeledPointGroup
                    {
                        Count = 0,
                        Class = 0
                    });
                    leftBucket.Add(new LabeledPointGroup
                    {
                        Count = 0,
                        Class = 1
                    });
                    List <LabeledPointGroup> rightBucket = new List <LabeledPointGroup>();
                    rightBucket.Add(new LabeledPointGroup
                    {
                        Count = 0,
                        Class = 0
                    });
                    rightBucket.Add(new LabeledPointGroup
                    {
                        Count = 0,
                        Class = 1
                    });

                    SplittingQuestion splittingQuestion = splittingQuestions[s];

                    for (int p = 0; p < trainingPoints.Count; p++)
                    {
                        //if (random.NextDouble() < .1 || trainingPoints.Count < 1000)
                        {
                            LabeledPoint trainingPoint = trainingPoints[p];

                            SplitDirection split = ComputeSplitDirection(trainingPoint, splittingQuestion, options);

                            if (split == SplitDirection.Left)
                            {
                                leftBucket[trainingPoint.Label].Count++;
                                //leftBucket1.Add(trainingPoint);
                            }
                            else
                            {
                                //rightBucket1.Add(trainingPoint);
                                rightBucket[trainingPoint.Label].Count++;
                            }
                        }
                    }

                    //double gain = ComputeGain(currentShannonEntropy, leftBucket1, rightBucket1);
                    double gain = ComputeGain(currentShannonEntropy, leftBucket, rightBucket);

                    lock (typeof(DecisionTreeBuilder))
                    {
                        if (gain > highestGain)
                        {
                            highestGain           = gain;
                            bestSplittingQuestion = splittingQuestion;
                        }
                    }
                });

                if (highestGain > options.SufficientGainLevel)
                {
                    List <LabeledPoint> bestLeftBucket  = new List <LabeledPoint>();
                    List <LabeledPoint> bestRightBucket = new List <LabeledPoint>();

                    for (int p = 0; p < trainingPoints.Count; p++)
                    {
                        LabeledPoint trainingPoint = trainingPoints[p];

                        SplitDirection split = ComputeSplitDirection(trainingPoint, bestSplittingQuestion, options);

                        if (split == SplitDirection.Left)
                        {
                            bestLeftBucket.Add(trainingPoint);
                        }
                        else
                        {
                            bestRightBucket.Add(trainingPoint);
                        }
                    }

                    currentNode.Question    = bestSplittingQuestion;
                    currentNode.LeftBranch  = new DecisionTreeNode();
                    currentNode.RightBranch = new DecisionTreeNode();
                    currentNode.IsLeaf      = false;

                    //System.Console.WriteLine("left: " + bestLeftBucket.Count.ToString());
                    //System.Console.WriteLine("right: " + bestRightBucket.Count.ToString());

                    //splittingQuestions =
                    //    GenerateSplittingQuestions(random, options);

                    RecurseAndPartition(bestLeftBucket, splittingQuestions,
                                        currentRecursionLevel + 1, options, currentNode.LeftBranch, random);

                    RecurseAndPartition(bestRightBucket, splittingQuestions,
                                        currentRecursionLevel + 1, options, currentNode.RightBranch, random);
                }
                else
                {
                    MakeLeafNode(currentNode, trainingPoints);
                }
            }
        }
Пример #8
0
 public DecisionTree(DecisionTreeNode[] tree)
 {
     nodes = tree;
     root  = nodes[0];
 }
Пример #9
0
 /// <summary>
 /// Makes a decision and returns a tree action recursively
 /// </summary>
 /// <returns>The Action.</returns>
 /// <param name="root">Root Node</param>
 public abstract TreeAction MakeDecision(DecisionTreeNode root);
Пример #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DecisionTreeNode"/> class.
 /// </summary>
 /// <param name="_falseNode">_false node.</param>
 /// <param name="_trueNode">_true node.</param>
 public DecisionTreeNode(DecisionTreeNode _falseNode, DecisionTreeNode _trueNode)
 {
     this.trueNode = _trueNode;
     this.falseNode = _falseNode;
 }
Пример #11
0
    public void IsThisYourChoice(DecisionTreeNode node, DecisionTreeNode parentNode, bool lastAnswer)
    {
        if (!node.IsLeafNode)
        {
            //ask the user the y or n question
            string ask = node.QuestionToAsk.question;
            Debug.Log(ask);
            // while(!Input.GetKeyDown(KeyCode.Y) && !Input.GetKeyDown(KeyCode.N))
            //  {
            if (Input.GetKeyDown(KeyCode.Y))
            {
                Debug.Log("You Pressed Y for Yes!");
                IsThisYourChoice(node.TrueResponseNode, node, true);
            }
            else if (Input.GetKeyDown(KeyCode.N))
            {
                Debug.Log("You Pressed N for No!");
                IsThisYourChoice(node.FalseResponseNode, node, false);
            }

            // }
        }
        else
        {
            string ask = node.QuestionToAsk.question;
            Debug.Log(ask);
            if (Input.GetKeyDown(KeyCode.Y))
            {
                Debug.Log("You Pressed Y for Yes!");
                Debug.Log("You Win, and the Game is Over. Congratulations!!!");
            }
            else if (Input.GetKeyDown(KeyCode.N))
            {
                Debug.Log("You Pressed N for No!");
                Debug.Log("What is the Answer?");
                string userInput = Console.ReadLine();
                Debug.Log("What is a question that could differentiate this question from the last?");
                string           newQuestion     = Console.ReadLine();
                DecisionTreeNode newQuestionNode = new DecisionTreeNode();
                newQuestionNode.IsLeafNode             = false;
                newQuestionNode.QuestionToAsk.question = newQuestion;
                DecisionTreeNode newLeafNode = new DecisionTreeNode();
                newLeafNode.IsLeafNode             = true;
                newLeafNode.QuestionToAsk.question = userInput;


                newQuestionNode.FalseResponseNode = node;
                newQuestionNode.TrueResponseNode  = newLeafNode;


                if (lastAnswer == true)
                {
                    parentNode.TrueResponseNode = newQuestionNode;
                }
                else
                {
                    parentNode.FalseResponseNode = newQuestionNode;
                }
            }
        }
    }
Пример #12
0
 //preorder traversal to save the tree
 void SaveTree(DecisionTreeNode node)
 {
     SaveValue(node);
     SaveTree(node.FalseResponseNode);
     SaveTree(node.TrueResponseNode);
 }
Пример #13
0
 public BooleanDecisionNode(DecisionTreeNode tN, DecisionTreeNode fN, System.Func <bool> func) :
     base(tN, fN)
 {
     booleanFunc = func;
 }
 public DecisionTreeCondition(string name, DecisionTreeBlackboard blackboard, Condition condition, DecisionTreeNode left, DecisionTreeNode right) : base(name, blackboard)
 {
     m_conditon  = condition;
     m_rightNode = right;
     m_leftNode  = left;
 }
Пример #15
0
 /// <summary>
 /// Sets nodes in the tree to corresponding true or false position
 /// </summary>
 /// <param name="_falseNode">_false node.</param>
 /// <param name="_trueNode">_true node.</param>
 public void SetNodes(DecisionTreeNode _falseNode, DecisionTreeNode _trueNode)
 {
     this.trueNode = _trueNode;
     this.falseNode = _falseNode;
 }
Пример #16
0
        private static DecisionTree.Models.DecisionTree GetContext()
        {
            var x1 = new DecisionTreeNode()
            {
                AttributeInfo = new NodeInfo
                {
                    Index = 0,
                }
            };

            var x21 = new DecisionTreeNode()
            {
                AttributeInfo = new NodeInfo
                {
                    Index = 1,
                },
                Branch = new NodeInfo
                {
                    Index = 0
                }
            };

            var x22 = new DecisionTreeNode()
            {
                AttributeInfo = new NodeInfo
                {
                    Index = 1,
                },
                Branch = new NodeInfo
                {
                    Index = 1
                }
            };

            x1.Childs.AddRange(new List <DecisionTreeNode> {
                x21, x22
            });

            var l00 = new DecisionTreeNode()
            {
                LeafInfo = new NodeInfo
                {
                    Index = 0,
                },
                Branch = new NodeInfo
                {
                    Index = 0
                }
            };

            var l01 = new DecisionTreeNode()
            {
                LeafInfo = new NodeInfo
                {
                    Index = 1,
                },
                Branch = new NodeInfo
                {
                    Index = 1
                }
            };

            var l11 = new DecisionTreeNode()
            {
                LeafInfo = new NodeInfo
                {
                    Index = 0,
                },
                Branch = new NodeInfo
                {
                    Index = 1
                }
            };

            var l10 = new DecisionTreeNode()
            {
                LeafInfo = new NodeInfo
                {
                    Index = 1,
                },
                Branch = new NodeInfo
                {
                    Index = 0
                }
            };

            x21.Childs.AddRange(new List <DecisionTreeNode> {
                l01, l00
            });
            x22.Childs.AddRange(new List <DecisionTreeNode> {
                l11, l10
            });

            return(new DecisionTree.Models.DecisionTree(It.IsAny <DecisionVariable[]>(), It.IsAny <DecisionVariable>())
            {
                Root = x1,
            });
        }
 public void AddLink(object value, DecisionTreeNode next)
 {
     links.Add(value, next);
 }
 public DecisionTreeAlgorithm(DecisionTreeNode decisionTreeRoot)
 {
     this.decisionTreeRoot = decisionTreeRoot;
 }
Пример #19
0
 private DecisionTree(DecisionTreeNode[] tree)
 {
     nodes = tree;
     first = tree[0];
 }
Пример #20
0
 public DecisionTree(Character _character) : base(_character)
 {
     root = new CanSeeEnemy(_character);
 }
Пример #21
0
        private void Split(DecisionTreeNode root, int[][] inputs, int[] outputs, int[] mappings)
        {
            var solveEntropy = Measure.CalcEntropy(outputs, _numberOfOuputRange);

            if (Math.Abs(solveEntropy) < double.Epsilon)
            {
                if (outputs.Length > 0)
                {
                    var outputIndex = outputs[0];
                    root.LeafInfo.Index = outputIndex;
                    root.LeafInfo.Name  = _tree.SolveAttribute.NameRange[outputIndex];
                }
                else
                {
                    /*
                     * what make if e == 0, and output is empty???
                     * what we should assign to leaf ?
                     * and it possible ?
                     */
                }

                return;
            }

            var gainScores = new double[inputs[0].Length];

            for (var i = 0; i < gainScores.Length; ++i)
            {
                var realId = mappings[i];
                gainScores[i] = InformationGain(inputs, outputs, solveEntropy, i, realId);
            }

            gainScores.Max(out var maxGainAttrIndex);
            var realMaxGainIndex = mappings[maxGainAttrIndex];
            var newMappings      = RecalculateMappings(mappings, maxGainAttrIndex);

            var currentAttribute = _tree.Attributes[realMaxGainIndex];

            root.AttributeInfo = new NodeInfo()
            {
                Index = realMaxGainIndex,
                Name  = currentAttribute.Name,
            };

            var childCount = _numberOfInputsRange[realMaxGainIndex];
            var children   = new DecisionTreeNode[childCount];

            for (var i = 0; i < children.Length; ++i)
            {
                children[i] = new DecisionTreeNode()
                {
                    Parent = root,
                    Branch = new NodeInfo
                    {
                        Name  = currentAttribute.NameRange[i],
                        Index = i
                    }
                };

                SplitLearnSet(
                    inputs, outputs,
                    maxGainAttrIndex, i,
                    out var newInput, out var newOutput);

                Split(children[i], newInput, newOutput, newMappings);
            }

            root.Childs.AddRange(children);
        }
Пример #22
0
        public void determineResult()
        {
            //Given
            DecisionTreeNode a = new DecisionTreeNode(ds);

            a.recursivelyConstructDecisionTreeLevels(a);
            Dictionary <String, String> conditions = new Dictionary <String, String>
            {
                { "CreditHistory", "UNKNOWN" },
                { "Debt", "HIGH" },
                { "Collateral", "NO" },
                { "Income", "R15k - R35k" }
            };
            //When
            String result = a.determineResult(a, conditions);

            //Then
            Assert.AreEqual(result, "HIGH");
            //=========================================================================
            //Given
            DecisionTreeNode a1 = new DecisionTreeNode(ds);

            a1.recursivelyConstructDecisionTreeLevels(a1);
            Dictionary <String, String> conditions1 = new Dictionary <String, String>
            {
                { "CreditHistory", "UNKNOWN" },
                { "Debt", "HIGH" },
                { "Collateral", "YES" },
                { "Income", "R15k - R35k" }
            };
            //When
            String result1 = a1.determineResult(a1, conditions1);

            //Then
            Assert.AreEqual(result1, "HIGH");
            //=========================================================================
            //Given
            DecisionTreeNode a2 = new DecisionTreeNode(ds);

            a2.recursivelyConstructDecisionTreeLevels(a2);
            Dictionary <String, String> conditions2 = new Dictionary <String, String>
            {
                { "CreditHistory", "UNKNOWN" },
                { "Debt", "HIGH" },
                { "Collateral", "YES" },
                { "Income", "< R15k" }
            };
            //When
            String result2 = a2.determineResult(a2, conditions2);

            //Then
            Assert.AreEqual(result2, "HIGH");
            //=========================================================================
            //Given
            DecisionTreeNode a3 = new DecisionTreeNode(ds);

            a3.recursivelyConstructDecisionTreeLevels(a3);
            Dictionary <String, String> conditions3 = new Dictionary <String, String>
            {
                { "CreditHistory", "GOOD" },
                { "Debt", "HIGH" },
                { "Collateral", "YES" },
                { "Income", "> R35k" }
            };
            //When
            String result3 = a3.determineResult(a3, conditions3);

            //Then
            Assert.AreEqual(result3, "LOW");
        }
Пример #23
0
    // Update is called once per frame
    void FixedUpdate()
    {
        bool bWantToFire   = false;
        bool bWantToShield = false;


        // This would be better to traverse and set based on what each node is. For now, this is good enough if gross.
        ((Decision)dTree).testData = mEffector.ShieldStatus;
        ((ShotApproachingDecision)(((Decision)dTree).trueNode)).testData = CheckForNearestShellDistance();
        ((IsGunReadyDecision)(((ShotApproachingDecision)(((Decision)dTree).trueNode)).trueNode)).testData = mEffector.IsGunReady();
        ((FacingEnemyDecision)(((IsGunReadyDecision)(((ShotApproachingDecision)(((Decision)dTree).trueNode)).trueNode)).trueNode)).testData = AngleToTarget();

        ((Decision)(((Decision)dTree).falseNode)).testData = mEffector.ShieldStatus;
        ((ShotApproachingDecision)(((Decision)(((Decision)dTree).falseNode)).trueNode)).testData = CheckForNearestShellDistance();
        ((IsGunReadyDecision)(((Decision)(((Decision)dTree).falseNode)).falseNode)).testData     = mEffector.IsGunReady();
        ((FacingEnemyDecision)((IsGunReadyDecision)(((Decision)(((Decision)dTree).falseNode)).falseNode)).trueNode).testData = AngleToTarget();

        ((IsGunReadyDecision)(((ShotApproachingDecision)(((Decision)(((Decision)dTree).falseNode)).trueNode)).falseNode)).testData = mEffector.IsGunReady();
        ((FacingEnemyDecision)(((IsGunReadyDecision)(((ShotApproachingDecision)(((Decision)(((Decision)dTree).falseNode)).trueNode)).falseNode)).trueNode)).testData = AngleToTarget();

        DecisionTreeNode node = dTree.MakeDecision();

        if (node is ShieldOnAction)
        {
            bWantToShield = true;
        }
        if (node is ShieldOffAction)
        {
            bWantToShield = false; // Seems to be a bug here, shield isn't wanting to turn off. *Might be a logic issue with toggling a button to enable/disable stuff?)
        }
        if (node is ShootGunAction)
        {
            bWantToFire = true;
        }

        steering = new SteeringOutput();

        // Blend Steering
        //steering += Seek.GetSteering(target._static.position, self._static.position, tank.maxSpeed).Weight(1.0f);
        sm.Update();
        //steering += Flee.GetSteering(target._static.position, self._static.position, tank.maxSpeed).Weight(1.0f);
        //steering += AlignToTarget2.GetSteering(target._static.position, self._static.position, self._static.orientation).Weight(1.0f);
        Rigidbody srb = tank.GetComponentInChildren <Rigidbody>();
        //steering.Crop();
        float angle = Vector3.SignedAngle(steering.velocity.normalized, srb.transform.forward, transform.up);

        //Horizontal = Input.GetAxisRaw("Horizontal");
        //Vertical = Input.GetAxisRaw("Vertical");

        ResetMovement();

        if (steering.velocity.magnitude > 0)
        {
            if (angle > -90 && angle < 90)
            {
                MoveForward = true;
            }
            if (angle < -90 || angle > 90)
            {
                MoveBackward = true;
            }
            if (angle > 0)
            {
                TurnLeft = true;
            }
            if (angle < 0)
            {
                TurnRight = true;
            }
        }
        if (steering.rotation < 0)
        {
            TurnLeft = true;
        }
        if (steering.rotation > 0)
        {
            TurnRight = true;
        }

        // Disable movement direction if inputs are contradicting each other.
        if (TurnLeft && TurnRight)
        {
            TurnLeft = TurnRight = false;
        }
        if (MoveForward && MoveBackward)
        {
            MoveForward = MoveBackward = false;
        }

        Fire   = bWantToFire;
        Shield = bWantToShield;

        //Debug.Log(string.Format("MoveLeft: {0} MoveRight: {1} MoveUp: {2} MoveDown: {3}", MoveLeft, MoveRight, MoveUp, MoveDown));
    }
Пример #24
0
        // We need to recursively walk the decision tree based on the provided route data
        // (context.Values + context.AmbientValues) to find all entries that match. This process is
        // virtually identical to action selection.
        //
        // Each entry has a collection of 'required link values' that must be satisfied. These are
        // key-value pairs that make up the decision tree.
        //
        // A 'require link value' is considered satisfied IF:
        //  1. The value in context.Values matches the required value OR
        //  2. There is no value in context.Values and the value in context.AmbientValues matches OR
        //  3. The required value is 'null' and there is no value in context.Values.
        //
        // Ex:
        //  entry requires { area = null, controller = Store, action = Buy }
        //  context.Values = { controller = Store, action = Buy }
        //  context.AmbientValues = { area = Help, controller = AboutStore, action = HowToBuyThings }
        //
        //  In this case the entry is a match. The 'controller' and 'action' are both supplied by context.Values,
        //  and the 'area' is satisfied because there's NOT a value in context.Values. It's OK to ignore ambient
        //  values in link generation.
        //
        //  If another entry existed like { area = Help, controller = Store, action = Buy }, this would also
        //  match.
        //
        // The decision tree uses a tree data structure to execute these rules across all candidates at once.
        private void Walk(
            List <OutboundMatchResult> results,
            RouteValueDictionary values,
            RouteValueDictionary ambientValues,
            DecisionTreeNode <OutboundMatch> node,
            bool isFallbackPath)
        {
            // Any entries in node.Matches have had all their required values satisfied, so add them
            // to the results.
            for (var i = 0; i < node.Matches.Count; i++)
            {
                results.Add(new OutboundMatchResult(node.Matches[i], isFallbackPath));
            }

            for (var i = 0; i < node.Criteria.Count; i++)
            {
                var criterion = node.Criteria[i];
                var key       = criterion.Key;

                if (values.TryGetValue(key, out var value))
                {
                    if (criterion.Branches.TryGetValue(value ?? string.Empty, out var branch))
                    {
                        Walk(results, values, ambientValues, branch, isFallbackPath);
                    }
                    else
                    {
                        // If an explicitly specified value doesn't match any branch, then speculatively walk the
                        // "null" path if the value doesn't match any known value.
                        //
                        // This can happen when linking from a page <-> action. We want to be
                        // able to use "page" and "action" as normal route parameters.
                        var knownValues = _knownValues[key];
                        if (!knownValues.Contains(value ?? string.Empty) && criterion.Branches.TryGetValue(string.Empty, out branch))
                        {
                            Walk(results, values, ambientValues, branch, isFallbackPath: true);
                        }
                    }
                }
                else
                {
                    // If a value wasn't explicitly supplied, match BOTH the ambient value and the empty value
                    // if an ambient value was supplied. The path explored with the empty value is considered
                    // the fallback path.
                    DecisionTreeNode <OutboundMatch> branch;
                    if (ambientValues.TryGetValue(key, out value) &&
                        !criterion.Branches.Comparer.Equals(value, string.Empty))
                    {
                        if (criterion.Branches.TryGetValue(value, out branch))
                        {
                            Walk(results, values, ambientValues, branch, isFallbackPath);
                        }
                    }

                    if (criterion.Branches.TryGetValue(string.Empty, out branch))
                    {
                        Walk(results, values, ambientValues, branch, isFallbackPath: true);
                    }
                }
            }
        }
Пример #25
0
 public LinkGenerationDecisionTree(IReadOnlyList <TreeRouteLinkGenerationEntry> entries)
 {
     _root = DecisionTreeBuilder <TreeRouteLinkGenerationEntry> .GenerateTree(
         entries,
         new AttributeRouteLinkGenerationEntryClassifier());
 }
Пример #26
0
        private void RecurseAndPartition(DecisionTreeNode parentNode, SplittingQuestion[] splittingQuestions,
                                         RecordPair[] allPairs, int level, double subsamplingPercentage, double minGainToBreak,
                                         Stack <Tuple <SplittingQuestion, bool> > splittingQuestionsThatGotUsHere)
        {
            Console.WriteLine($"Level {level}. {splittingQuestions.Length} splitting questions on {allPairs.Length} record pairs.");

            // find the best splitting question.
            SplittingQuestion bestQuestion = null;
            int numberDone  = 0;
            int displayLeft = Console.CursorLeft;
            int displayTop  = Console.CursorTop;

            bool reachedLeafNode = false;

            // is this precomputed? if not, then we need to compute it.
            if (parentNode.Question == null)
            {
                double highestGain    = 0.0;
                double currentEntropy = ComputeShannonEntropy(allPairs);

                //Console.WriteLine("F mode....");
                //foreach (SplittingQuestion splittingQuestion in splittingQuestions)
                Parallel.ForEach(splittingQuestions, splittingQuestion =>
                {
                    List <RecordPair> leftBucket  = new List <RecordPair>();
                    List <RecordPair> rightBucket = new List <RecordPair>();

                    //Random rand = new Random();

                    int matchesInLeft = 0, noMatchesInLeft = 0,
                    matchesInRight    = 0, noMatchesInRight = 0;

                    int pairNumber = 0;
                    foreach (RecordPair pair in allPairs)
                    {
                        //if(pairNumber%10000==0)
                        //    Console.WriteLine($"{pairNumber} of {allPairs.Length}");
                        pairNumber++;
                        //if (rand.NextDouble() <= subsamplingPercentage)
                        {
                            bool goLeft = ComputeSplitDirection(splittingQuestion, pair);

                            if (goLeft)
                            {
                                if (pair.IsMatch)
                                {
                                    matchesInLeft++;
                                }
                                else
                                {
                                    noMatchesInLeft++;
                                }
                            }
                            else
                            {
                                if (pair.IsMatch)
                                {
                                    matchesInRight++;
                                }
                                else
                                {
                                    noMatchesInRight++;
                                }
                            }
                        }
                    }

                    double leftEntropy  = ComputeShannonEntropy(matchesInLeft, noMatchesInLeft);
                    double rightEntropy = ComputeShannonEntropy(matchesInRight, noMatchesInRight);

                    double gain = ComputeGain(currentEntropy, leftEntropy, (noMatchesInLeft + matchesInLeft),
                                              rightEntropy, (matchesInRight + noMatchesInRight));

                    lock (splittingQuestions)
                    {
                        if (gain > highestGain)
                        {
                            highestGain  = gain;
                            bestQuestion = splittingQuestion;
                        }
                    }
                    lock (splittingQuestions)
                    {
                        numberDone++;
                        //Console.SetCursorPosition(displayLeft, displayTop);
                        //Console.WriteLine($"{(int)((numberDone / (splittingQuestions.Length * 1.0)) * 100)}%");
                    }
                });

                reachedLeafNode = highestGain <= minGainToBreak;

                if (reachedLeafNode)
                {
                    parentNode.IsLeaf = true;
                    int matchCount   = allPairs.Count(n => n.IsMatch);
                    int noMatchCount = allPairs.Count(n => !n.IsMatch);

                    if (matchCount > noMatchCount)
                    {
                        parentNode.IsMatch = true;
                    }
                    else
                    {
                        parentNode.IsMatch = false;
                    }
                }

                Console.WriteLine("\tGain limit met. Anything reaching this leaf will be labeled as " + (parentNode.IsMatch ? "match." : "no match"));
            }
            else
            {
                // otherwise it's precomputed, just take the current question as the "best question"
                bestQuestion    = parentNode.Question;
                reachedLeafNode = parentNode.IsLeaf;

                Console.WriteLine("\tPrecomputed. Anything reaching this leaf will be labeled as " + (parentNode.IsMatch ? "match." : "no match"));
            }

            //if (reachedLeafNode)
            //{


            //    StringBuilder sb = new StringBuilder(1024);
            //    sb.AppendLine($"Level {level}, IsMatch {parentNode.IsMatch}");
            //    sb.AppendLine("Questions:");
            //    foreach (Tuple<SplittingQuestion, bool> questionAnswer in splittingQuestionsThatGotUsHere)
            //    {
            //        sb.AppendLine($"\t{questionAnswer.Item1}:{questionAnswer.Item2}");
            //    }
            //    sb.AppendLine($"match: {matchCount}, nomatch: {noMatchCount}");
            //    File.WriteAllText(
            //        $"c:/users/brush/desktop/treeresults/{Guid.NewGuid().ToString().Replace("-", "")}",
            //        sb.ToString());

            //    Console.WriteLine("\tGain limit met. Anything reaching this leaf will be labeled as " + (parentNode.IsMatch ? "match." : "no match"));
            //}
            if (!reachedLeafNode)
            {
                Console.WriteLine($"\tBest question at this level is {bestQuestion}");

                List <RecordPair> bestLeftBucket = new List <RecordPair>(), bestRightBucket = new List <RecordPair>();
                Parallel.ForEach(allPairs, pair =>
                {
                    bool goLeft = ComputeSplitDirection(bestQuestion, pair);

                    if (goLeft)
                    {
                        lock (bestLeftBucket)
                        {
                            bestLeftBucket.Add(pair);
                        }
                    }
                    else
                    {
                        lock (bestRightBucket)
                        {
                            bestRightBucket.Add(pair);
                        }
                    }
                });

                parentNode.Question = bestQuestion;
                if (parentNode.LeftBranch == null)
                {
                    parentNode.LeftBranch = new DecisionTreeNode();
                }

                if (parentNode.RightBranch == null)
                {
                    parentNode.RightBranch = new DecisionTreeNode();
                }

                splittingQuestionsThatGotUsHere.Push(new Tuple <SplittingQuestion, bool>(bestQuestion, true));
                RecurseAndPartition(parentNode.LeftBranch, splittingQuestions, bestLeftBucket.ToArray(),
                                    level + 1, subsamplingPercentage, minGainToBreak, splittingQuestionsThatGotUsHere);
                splittingQuestionsThatGotUsHere.Pop();

                splittingQuestionsThatGotUsHere.Push(new Tuple <SplittingQuestion, bool>(bestQuestion, false));
                RecurseAndPartition(parentNode.RightBranch, splittingQuestions, bestRightBucket.ToArray(),
                                    level + 1, subsamplingPercentage, minGainToBreak, splittingQuestionsThatGotUsHere);
                splittingQuestionsThatGotUsHere.Pop();
            }
        }
Пример #27
0
 public DecisionNode(DecisionTreeNode tN, DecisionTreeNode fN)
 {
     trueNode  = tN;
     falseNode = fN;
 }
Пример #28
0
 /// <summary>
 /// Makes the decision.
 /// </summary>
 /// <returns>This defined action</returns>
 /// <param name="root">Root Node</param>
 public override TreeAction MakeDecision(DecisionTreeNode root)
 {
     return this;
 }
Пример #29
0
 private void LoadTreeComplete(DecisionTreeNode tree)
 {
     //Debugger.Log("Load decision tree done");
     isLoaded = true;
     root     = tree;
 }
Пример #30
0
        static void Test()
        {
            BinaryFormatter bf = new BinaryFormatter();

            using (FileStream fs = File.OpenRead("serialized.dat"))
            {
                DecisionTreeNode node = bf.Deserialize(fs) as DecisionTreeNode;


                DecisionTreeOptions options = new DecisionTreeOptions
                {
                    // TODO: Fill in
                    MaximumNumberOfRecursionLevels = 25,
                    NumberOfFeatures        = 300,
                    NumberOfThresholds      = 35,
                    OffsetXMax              = 40,
                    OffsetXMin              = -40,
                    OffsetYMax              = 40,
                    OffsetYMin              = -40,
                    OutOfRangeValue         = 1000000,
                    SplittingThresholdMax   = .2f,
                    SufficientGainLevel     = 0,
                    PercentageOfPixelsToUse = .9f,
                    //DistanceThreshold = .1f,
                };


                MRCFile file = MRCParser.Parse(Path.Combine("/home/brush/tomography2_fullsirtcliptrim.mrc"));

                MRCFrame frame = file.Frames[145];

                LabeledTomogram tom = new LabeledTomogram();
                tom.Width  = frame.Width;
                tom.Height = frame.Height;
                tom.Data   = new float[frame.Width * frame.Height];

                for (int i = 0; i < frame.Data.Length; i++)
                {
                    tom.Data[i] = frame.Data[i];
                }

                //for (int y = 264, i = 0; y < 364; y++)
                //{
                //    for (int x = 501; x < 601; x++, i++)
                //    {
                //        tom.Data[i] = frame.Data[y * frame.Width + x];
                //    }
                //}


                float[] labels = DecisionTreeBuilder.Predict(tom, node, options);
                //Bitmap bmp = DataManipulator.Tomogram2Bitmap(tom);
                Bitmap bmp = Drawing.TomogramDrawing.PaintClassifiedPixelsOnTomogram(tom, labels);
                bmp.Save("/var/www/html/static/labeled_real.png", System.Drawing.Imaging.ImageFormat.Png);

                LabeledTomogram tom2 = DataReader.ReadDatFile("/home/brush/tom4/0.dat");

                labels = DecisionTreeBuilder.Predict(tom2, node, options);
                //Bitmap bmp = DataManipulator.Tomogram2Bitmap(tom);
                bmp = Drawing.TomogramDrawing.PaintClassifiedPixelsOnTomogram(tom2, labels);
                bmp.Save("/var/www/html/static/labeled_simulated.png", System.Drawing.Imaging.ImageFormat.Png);
            }
        }
Пример #31
0
    private void FixedUpdate()
    {
        shootPlayerAction.targetPosition  = target.transform.position;
        arrivePlayerAction.targetPosition = target.transform.position;
        avoidPlayerAction.targetPosition  = target.transform.position;

        float          duration = Time.deltaTime;
        SteeringOutput steer    = new SteeringOutput();
        float          angle    = 0.0f;

        DecisionTreeNode node = null;

        GameObject[] healthPacks = GameObject.FindGameObjectsWithTag("Health");

        if (healthPacks.Length > 0)
        {
            seekHealthAction.targetPosition = healthPacks[0].transform.position;
            foreach (var hp in healthPacks)
            {
                float currentDistance = (seekHealthAction.targetPosition - transform.position).magnitude;
                float indexDistance   = (hp.transform.position - transform.position).magnitude;

                if (indexDistance < currentDistance)
                {
                    seekHealthAction.targetPosition = hp.transform.position;
                }
            }
        }

        if (currentState == AI_STATE.HEALTH_LOW)
        {
            node = lowHealthTargetNearby.makeDecision();
        }
        else if (currentState == AI_STATE.HEALTH_HIGH)
        {
            node = highHealthTargetNearby.makeDecision();
        }
        if (node is DecisionTreeAction)
        {
            ((DecisionTreeAction)node).doSomething();

            if (node is ShootPlayerAction)
            {
#if DEBUG
                heading.x = Mathf.Cos(transform.rotation.eulerAngles.z * Mathf.Deg2Rad);
                heading.y = Mathf.Sin(transform.rotation.eulerAngles.z * Mathf.Deg2Rad);
                Vector3 headingLine = new Vector3(heading.x, heading.y, 0);
                Debug.DrawLine(transform.position, transform.position + (headingLine * 2), Color.red);
#endif

                if (lastFired <= 0)
                {
                    GameObject bullet = Instantiate(projectile, transform.position + (heading * 1.5f), transform.rotation);
                    bullet.GetComponent <Rigidbody2D>().AddForce(heading * PROJECTILE_SPEED, ForceMode2D.Impulse);
                    lastFired = timeLeftBeforeFiring;
                }
            }
        }
        if (lastFired > 0)
        {
            lastFired -= Time.deltaTime * 100;
        }
    }
Пример #32
0
 public Decision(DecisionTreeNode _falseNode, DecisionTreeNode _trueNode, Func<object[], bool> _determining)
     : base(_falseNode, _trueNode)
 {
     this.determining = _determining;
 }