2014-01-13 50 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))))