如何用c#实现决策树(visual studio 2008) – 帮助

我有一个决策树,我需要转向C#中的代码

这样做的简单方法是使用if-else语句,但在此解决方案中,我需要创建4-5个嵌套条件。

我正在寻找一种更好的方法来实现它,到目前为止我读了一些关于规则引擎的内容。

您是否有其他建议以有效的方式开发具有4-5个嵌套条件的决策树?

我在我的书中实现了一个简单的决策树作为样本。 这里的代码可以在线获取 ,所以也许您可以将它作为灵感来使用。 决策基本上表示为一个引用了true branch和false分支的类,并包含一个执行测试的函数:

 class DecisionQuery : Decision { public Decision Positive { get; set; } public Decision Negative { get; set; } // Primitive operation to be provided by the user public Func Test { get; set; } public override bool Evaluate(Client client) { // Test a client using the primitive operation bool res = Test(client); // Select a branch to follow return res ? Positive.Evaluate(client) : Negative.Evaluate(client); } } 

这里, Decision是一个包含Evaluate方法的基类,source包含一个额外的派生类型,它包含树的最终决策(是/否)。 Client类型是您使用树分析的示例输入数据。

要创建决策树,您可以编写如下内容:

 var tree = new DecisionQuery { Test = (client) => client.Income > 40000, Positive = otherTree, Negative = someOtherTree }; 

如果你只想写五个嵌套的静态if子句,那么可能只是写if 。 使用像这样的类型的好处是你可以轻松地组成树 – 例如重用树的一部分或模块化结构。

以下是答案https://stackoverflow.com/a/3889544/5288052中提到的Tomas Petricek的代码。

包含“Real-World Functional Programming”一书的所有源代码的zip文件可在此处获得https://www.manning.com/books/real-world-functional-programming 。

 // Section 8.4.2 Decision trees in C# // Listing 8.15 Object oriented decision tree (C#) abstract class Decision { // Tests the given client public abstract void Evaluate(Client client); } class DecisionResult : Decision { public bool Result { get; set; } public override void Evaluate(Client client) { // Print the final result Console.WriteLine("OFFER A LOAN: {0}", Result ? "YES" : "NO"); } } // Listing 8.16 Simplified implementation of Template method class DecisionQuery : Decision { public string Title { get; set; } public Decision Positive { get; set; } public Decision Negative { get; set; } // Primitive operation to be provided by the user public Func Test { get; set; } public override void Evaluate(Client client) { // Test a client using the primitive operation bool res = Test(client); Console.WriteLine(" - {0}? {1}", Title, res ? "yes" : "no"); // Select a branch to follow if (res) Positive.Evaluate(client); else Negative.Evaluate(client); } } static void MainDecisionTrees() { // The tree is constructed from a query var tree = new DecisionQuery { Title = "More than $40k", // Test is specified using a lambda function Test = (client) => client.Income > 40000, // Sub-trees can be 'DecisionResult' or 'DecisionQuery' Positive = new DecisionResult { Result = true }, Negative = new DecisionResult { Result = false } }; // Test a client using this tree // Create client using object initializer var john = new Client { Name = "John Doe", Income = 40000, YearsInJob = 1, UsesCreditCard = true, CriminalRecord = false }; tree.Evaluate(john); } private static void Main(string[] args) { MainDecisionTrees(); } 

只是因为…我有一个去,结果在这里…… https://github.com/jkennerley/DeeTree

我必须在C#中使用ID3算法实现决策树。

我在这里写了关于我的实现。 代码可以从GitHub下载。