如何实现树用C#(Visual Studio 2008中)的决定 - 帮助如何实现、Visual、Studio

2023-09-04 01:41:17 作者:嗜你如命

我有一个决策树,我需要求助于code在C#

I have a decision tree that i need to turn to a code in C#

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

The simple way of doing it is using if-else statements but in this solution i will need to create 4-5 nested conditions.

我要寻找一个更好的方式来做到这一点,到目前为止,我读了一些关于规则引擎。

I am looking for a better way to do it and so far i read a little bit about rule engines.

你有什么别的建议为制定决策树4-5嵌套条件的有效途径?

Do you have something else to suggest for an efficient way to develop decision tree with 4-5 nested conditions?

推荐答案

我实现了一个简单的决策树在我的书的样本。在code可在线此处,所以也许你可以把它作为一个重要启示。决定基本上是重新psented作为引用了分支分支,包含了一类$ P $函数,它的测试:

I implemented a simple decision tree as a sample in my book. The code is available online here, so perhaps you could use it as an inspiration. A decision is essentially represented as a class that has references to true branch and false branch and contains a function that does the test:

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);
  }
}

下面,的决定是一个包含一个基类评估方法和源中包含一个额外的派生类型包含树的最终决定(是/否)。类型客户端是使用树要分析一个样品的输入数据。

Here, Decision is a base class that contains Evaluate method and the source contains one additional derived type that contains a final decision of the tree (yes/no). The type Client is a sample input data that you're analysing using the tree.

要创建一个决策树,你可以写这样的:

To create a decision tree, you can write something like:

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

如果你只想写5嵌套的静态如果条款的话,说不定只是写如果是好的。使用这样一个类型的好处是,你可以很容易地撰写树 - 如重用树的一部分或模块化建设。

If you just want to write five nested static if clauses then maybe just writing if is fine. The benefit of using a type like this one is that you can easily compose trees - e.g. reuse a part of a tree or modularize the construction.