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

Che*_*hen 18 .net c# classification decision-tree

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

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

我正在寻找一种更好的方法来做到这一点,到目前为止我读了一些关于规则引擎的内容.

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

Tom*_*cek 22

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

class DecisionQuery : Decision {
  public Decision Positive { get; set; }
  public Decision Negative { get; set; }
  // Primitive operation to be provided by the user
  public Func<Client, bool> 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

如果你只想写五个嵌套的静态if子句,那么写作if就好了.使用类似这样的类型的好处是您可以轻松地组合树 - 例如重用树的一部分或模块化构造.

  • 该代码不再在http://code.msdn.microsoft.com/realworldfp/上提供.你能把它贴在其他地方吗? (4认同)