2014-01-13 39 views
1

假设我有以下的树形结构:功能,构建二元决策树

type Tree = 
    | Branch of (string*string) * (Tree*Tree) 
    | Leaf of float 

例如,它可能是这个样子:

Branch (("X1",">4.5"), (Branch (("X2",">4.5"), (Leaf 3.4, Leaf 5.5)), Branch (("X3",">4.5"), (Leaf 6.5, Leaf 4.5)))) 

这将是一个功能的主要部分创建一个这样的树(从数据,随机或其他)? 我知道我的问题与how to make a tree from a given data with F#类似,但是我正在将最难的时间翻译到我的树上。

编辑:我试图建立一个决策树,我开始与树here看起来像这样:

type DecisionTreeNode = 
    // Attribute name and value/child node list 
    | DecisionNode of string * (string * DecisionTreeNode) seq 
    // Decision and corresponding evidence 
    | Leaf of bool * Record seq 

然而,我的是一个回归树,所以它应该有漂浮的叶子,我只想要二进制分割,所以我想我可以使用元组而不是seq作为节点。 在那棵树再次寻找后,我想知道如果我的应该是这样的:

type Tree = 
    | Branch of string*((string*Tree)*(string*Tree)) 
    | Leaf of float 
+3

你被困在什么特定部分?所以我不在这里写所有我的代码问题 –

+0

我有点澄清了这个问题。 – dood

回答

2

我还没有decision trees工作,但阅读您的要求

  1. 二元分割
  2. 浮动的叶子

l ooking在link并考虑使用谷歌搜索图片的一些例子中,例如,

我会用:

型树=
|字符串*(字符串*树)*(字符串*树)的分支
|浮子

的叶并用
符合使用

匹配节点的节点|分支(决定,(v1,l),(v2,r)) - > //做点什么
|叶值 - > //做一些事情

而且你会比较对值v1v2,并选择适当的分支,lr

注:我删除了()周围((string*Tree)*(string*Tree)),使您可以使用的

Branch (decision, (v1,l), (v2,r))代替
Branch (decision, ((v1,l), (v2,r)))

还请注意,我没有测试或编译的代码,但它应该让你开始。

+0

这让我朝着正确的方向前进,但是我真正追求的是我的回答。这是处理这个问题的正确方法吗?我希望得到公平的分数。 – dood

0

我想清楚了我原来的样子。这样的功能(与“虽然我> 0”的逻辑,不管你创建的树代替),这是基于@GuyCoder的答案给出的树形结构:

type Tree = 
| Branch of string*(string*Tree)*(string*Tree) 
| Leaf of float 

let rec buildTree i = 
    if i<1 then Leaf 1. 
    else Branch ("Branch", ("Condition1", (buildTree (i-1))), ("Condition1", (buildTree (i-1))))