internal string Evaluate(RandomTreeNode node, RandomForestInstance instance) { var stack = new Stack <RandomTreeNode>(); stack.Push(node); while (stack.Any()) { var next = stack.Pop(); if (next.Evaluate(instance)) { // its not a leaf if (next.OutputClass == null) { foreach (var child in next.Children) { stack.Push(child); } } // its a leaf else { return(next.OutputClass); } } } // tree could not classify instance... return(RandomTreeNode.NoClass); }
private void LogTree(RandomTreeNode root) { var stack = new Stack <RandomTreeNode>(); stack.Push(root); while (stack.Any()) { var next = stack.Pop(); next.LogNode(); foreach (var child in next.Children) { stack.Push(child); } } }
internal static RandomTreeNode BuildFromString(string predicateLine, int id, int precision) { var node = new RandomTreeNode { // get the level, i.e., the number of '|' in the string Level = DetermineLevel(predicateLine), Id = id }; // parse predicate. They look like: | AvgDepsForOutputPips < 3446.5 // or: AvgTagCountForOutputPips < 10.13 : Shared (4/1) var predicateText = predicateLine.Substring(predicateLine.Contains("|") ? predicateLine.LastIndexOf("|") + 1 : 0).Trim(); // now, split by spaces var pieces = predicateText.Split(' '); // here, 0 is the name, 1 is the op and 2 is the value node.EvaluationPredicate = PredicateBuilder.BuildPredicate(pieces[0], pieces[1], pieces[2], precision); // now, check if this outputs something if (predicateLine.Contains(":")) { node.OutputClass = pieces[4]; } return(node); }
internal static RandomTree FromStream(StreamReader reader, string firstLine, int nodePrecision, int id) { var output = new RandomTree() { Id = id }; var keepReading = true; RandomTreeNode previous = null; int initialId = 0; bool first = true; while (keepReading) { ++initialId; try { var line = first ? firstLine : reader.ReadLine(); var node = RandomTreeNode.BuildFromString(line, initialId, nodePrecision); output.NumNodes = +1; if (node.Level == 0) { // for roots output.Roots.Add(node); previous = node; first = false; } else { // count the levels if (node.Level > previous.Level) { // child previous.Children.Add(node); node.Parent = previous; } else if (node.Level < previous.Level) { // predecessor: travel backwards and look for the first parent with level = level while (previous != null) { if (previous.Level == node.Level - 1) { // we found its parent previous.Children.Add(node); node.Parent = previous; break; } previous = previous.Parent; } } else { // same level, they are siblings previous.Parent.Children.Add(node); node.Parent = previous.Parent; } previous = node; } } #pragma warning disable ERP022 catch (Exception) { // we could not read, so we are in the line after we finished.. how do we know? cause we could not build a predicate break; } #pragma warning disable ERP022 } // done... return(output); }