如何用 C# 实现决策树 (Visual Studio 2008) - 帮助

发布于 2024-09-27 02:54:15 字数 176 浏览 4 评论 0原文

我有一个决策树,我需要将其转换为 C# 代码。

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

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

对于开发具有 4-5 个嵌套条件的决策树的有效方法,您还有其他建议吗?

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

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.

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

苹果你个爱泡泡 2024-10-04 02:54:15

我在书中实现了一个简单的决策树作为示例。该代码可以在线获取,因此也许您可以将其用作灵感。决策本质上表示为一个类,该类引用 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);
  }
}

此处为 Decision是一个包含 Evaluate 方法的基类,源包含一个附加的派生类型,其中包含树的最终决策(是/否)。 Client 类型是您使用树分析的示例输入数据。

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

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

如果您只想编写五个嵌套的静态 if 子句,那么也许只编写 if 就可以了。使用此类类型的好处是您可以轻松地构建树 - 例如,重用树的一部分或模块化构造。

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

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.

攒眉千度 2024-10-04 02:54:15

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

包含《真实世界函数式编程》一书所有源代码的 zip 可在此处获取 https://www.manning.com/books/real-world-function-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<Client, bool> 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();
}

Below is the Tomas Petricek's code mentioned in the answer https://stackoverflow.com/a/3889544/5288052 .

The zip containing all the source code of the book "Real-World Functional Programming" is available here 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<Client, bool> 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();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文