| 1 | <?php |
||
| 7 | |||
| 8 | namespace Phpml\Classification\DecisionTree; |
||
| 9 | |||
| 10 | class DecisionTreeLeaf |
||
| 11 | { |
||
| 12 | const OPERATOR_EQ = '='; |
||
| 13 | /** |
||
| 14 | * @var string |
||
| 15 | */ |
||
| 16 | public $value; |
||
| 17 | |||
| 18 | /** |
||
| 19 | * @var int |
||
| 20 | */ |
||
| 21 | public $columnIndex; |
||
| 22 | |||
| 23 | /** |
||
| 24 | * @var DecisionTreeLeaf |
||
| 25 | */ |
||
| 26 | public $leftLeaf = null; |
||
| 27 | |||
| 28 | /** |
||
| 29 | * @var DecisionTreeLeaf |
||
| 30 | */ |
||
| 31 | public $rightLeaf= null; |
||
| 32 | |||
| 33 | /** |
||
| 34 | * @var array |
||
| 35 | */ |
||
| 36 | public $records = []; |
||
| 37 | |||
| 38 | /** |
||
| 39 | * Class value represented by the leaf, this value is non-empty |
||
| 40 | * only for terminal leaves |
||
| 41 | * |
||
| 42 | * @var string |
||
| 43 | */ |
||
| 44 | public $classValue = ''; |
||
| 45 | |||
| 46 | /** |
||
| 47 | * @var bool |
||
| 48 | */ |
||
| 49 | public $isTerminal = false; |
||
| 50 | |||
| 51 | /** |
||
| 52 | * @var float |
||
| 53 | */ |
||
| 54 | public $giniIndex = 0; |
||
| 55 | |||
| 56 | /** |
||
| 57 | * @var int |
||
| 58 | */ |
||
| 59 | public $level = 0; |
||
| 60 | |||
| 61 | /** |
||
| 62 | * @param array $record |
||
| 63 | * @return bool |
||
| 64 | */ |
||
| 65 | public function evaluate($record) |
||
| 66 | { |
||
| 67 | $recordField = $record[$this->columnIndex]; |
||
| 68 | if (preg_match("/^([<>=]{1,2})\s*(.*)/", $this->value, $matches)) { |
||
| 69 | $op = $matches[1]; |
||
| 70 | $value= floatval($matches[2]); |
||
| 71 | $recordField = strval($recordField); |
||
| 72 | eval("\$result = $recordField $op $value;"); |
||
| 73 | return $result; |
||
| 74 | } |
||
| 75 | return $recordField == $this->value; |
||
| 76 | } |
||
| 77 | |||
| 78 | public function __toString() |
||
| 79 | { |
||
| 80 | if ($this->isTerminal) { |
||
| 81 | $value = "<b>$this->classValue</b>"; |
||
| 82 | } else { |
||
| 83 | $value = $this->value; |
||
| 84 | $col = "col_$this->columnIndex"; |
||
| 85 | if (! preg_match("/^[<>=]{1,2}/", $value)) { |
||
| 86 | $value = "=$value"; |
||
| 87 | } |
||
| 88 | $value = "<b>$col $value</b><br>Gini: ". number_format($this->giniIndex, 2); |
||
| 89 | } |
||
| 90 | $str = "<table ><tr><td colspan=3 align=center style='border:1px solid;'> |
||
| 91 | $value</td></tr>"; |
||
| 92 | if ($this->leftLeaf || $this->rightLeaf) { |
||
| 93 | $str .='<tr>'; |
||
| 94 | if ($this->leftLeaf) { |
||
| 95 | $str .="<td valign=top><b>| Yes</b><br>$this->leftLeaf</td>"; |
||
| 96 | } else { |
||
| 97 | $str .='<td></td>'; |
||
| 98 | } |
||
| 99 | $str .='<td> </td>'; |
||
| 100 | if ($this->rightLeaf) { |
||
| 101 | $str .="<td valign=top align=right><b>No |</b><br>$this->rightLeaf</td>"; |
||
| 102 | } else { |
||
| 103 | $str .='<td></td>'; |
||
| 104 | } |
||
| 105 | $str .= '</tr>'; |
||
| 106 | } |
||
| 107 | $str .= '</table>'; |
||
| 108 | return $str; |
||
| 111 |