Complex classes like DecisionTree often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use DecisionTree, and based on these observations, apply Extract Interface, too.
| 1 | <?php |
||
| 13 | class DecisionTree implements Classifier |
||
| 14 | { |
||
| 15 | use Trainable; |
||
| 16 | use Predictable; |
||
| 17 | |||
| 18 | public const CONTINUOUS = 1; |
||
| 19 | |||
| 20 | public const NOMINAL = 2; |
||
| 21 | |||
| 22 | /** |
||
| 23 | * @var int |
||
| 24 | */ |
||
| 25 | public $actualDepth = 0; |
||
| 26 | |||
| 27 | /** |
||
| 28 | * @var array |
||
| 29 | */ |
||
| 30 | protected $columnTypes = []; |
||
| 31 | |||
| 32 | /** |
||
| 33 | * @var DecisionTreeLeaf |
||
| 34 | */ |
||
| 35 | protected $tree; |
||
| 36 | |||
| 37 | /** |
||
| 38 | * @var int |
||
| 39 | */ |
||
| 40 | protected $maxDepth; |
||
| 41 | |||
| 42 | /** |
||
| 43 | * @var array |
||
| 44 | */ |
||
| 45 | private $labels = []; |
||
| 46 | |||
| 47 | /** |
||
| 48 | * @var int |
||
| 49 | */ |
||
| 50 | private $featureCount = 0; |
||
| 51 | |||
| 52 | /** |
||
| 53 | * @var int |
||
| 54 | */ |
||
| 55 | private $numUsableFeatures = 0; |
||
| 56 | |||
| 57 | /** |
||
| 58 | * @var array |
||
| 59 | */ |
||
| 60 | private $selectedFeatures = []; |
||
| 61 | |||
| 62 | /** |
||
| 63 | * @var array|null |
||
| 64 | */ |
||
| 65 | private $featureImportances; |
||
| 66 | |||
| 67 | /** |
||
| 68 | * @var array |
||
| 69 | */ |
||
| 70 | private $columnNames = []; |
||
| 71 | |||
| 72 | public function __construct(int $maxDepth = 10) |
||
| 73 | { |
||
| 74 | $this->maxDepth = $maxDepth; |
||
| 75 | } |
||
| 76 | |||
| 77 | public function train(array $samples, array $targets): void |
||
| 78 | { |
||
| 79 | $this->samples = array_merge($this->samples, $samples); |
||
| 80 | $this->targets = array_merge($this->targets, $targets); |
||
| 81 | |||
| 82 | $this->featureCount = count($this->samples[0]); |
||
| 83 | $this->columnTypes = self::getColumnTypes($this->samples); |
||
| 84 | $this->labels = array_keys(array_count_values($this->targets)); |
||
| 85 | $this->tree = $this->getSplitLeaf(range(0, count($this->samples) - 1)); |
||
| 86 | |||
| 87 | // Each time the tree is trained, feature importances are reset so that |
||
| 88 | // we will have to compute it again depending on the new data |
||
| 89 | $this->featureImportances = null; |
||
| 90 | |||
| 91 | // If column names are given or computed before, then there is no |
||
| 92 | // need to init it and accidentally remove the previous given names |
||
| 93 | if ($this->columnNames === []) { |
||
| 94 | $this->columnNames = range(0, $this->featureCount - 1); |
||
| 95 | } elseif (count($this->columnNames) > $this->featureCount) { |
||
| 96 | $this->columnNames = array_slice($this->columnNames, 0, $this->featureCount); |
||
| 97 | } elseif (count($this->columnNames) < $this->featureCount) { |
||
| 98 | $this->columnNames = array_merge( |
||
| 99 | $this->columnNames, |
||
| 100 | range(count($this->columnNames), $this->featureCount - 1) |
||
| 101 | ); |
||
| 102 | } |
||
| 103 | } |
||
| 104 | |||
| 105 | public static function getColumnTypes(array $samples): array |
||
| 106 | { |
||
| 107 | $types = []; |
||
| 108 | $featureCount = count($samples[0]); |
||
| 109 | for ($i = 0; $i < $featureCount; ++$i) { |
||
| 110 | $values = array_column($samples, $i); |
||
| 111 | $isCategorical = self::isCategoricalColumn($values); |
||
| 112 | $types[] = $isCategorical ? self::NOMINAL : self::CONTINUOUS; |
||
| 113 | } |
||
| 114 | |||
| 115 | return $types; |
||
| 116 | } |
||
| 117 | |||
| 118 | /** |
||
| 119 | * @param mixed $baseValue |
||
| 120 | */ |
||
| 121 | public function getGiniIndex($baseValue, array $colValues, array $targets): float |
||
| 122 | { |
||
| 123 | $countMatrix = []; |
||
| 124 | foreach ($this->labels as $label) { |
||
| 125 | $countMatrix[$label] = [0, 0]; |
||
| 126 | } |
||
| 127 | |||
| 128 | foreach ($colValues as $index => $value) { |
||
| 129 | $label = $targets[$index]; |
||
| 130 | $rowIndex = $value === $baseValue ? 0 : 1; |
||
| 131 | ++$countMatrix[$label][$rowIndex]; |
||
| 132 | } |
||
| 133 | |||
| 134 | $giniParts = [0, 0]; |
||
| 135 | for ($i = 0; $i <= 1; ++$i) { |
||
| 136 | $part = 0; |
||
| 137 | $sum = array_sum(array_column($countMatrix, $i)); |
||
| 138 | if ($sum > 0) { |
||
| 139 | foreach ($this->labels as $label) { |
||
| 140 | $part += pow($countMatrix[$label][$i] / (float) $sum, 2); |
||
| 141 | } |
||
| 142 | } |
||
| 143 | |||
| 144 | $giniParts[$i] = (1 - $part) * $sum; |
||
| 145 | } |
||
| 146 | |||
| 147 | return array_sum($giniParts) / count($colValues); |
||
| 148 | } |
||
| 149 | |||
| 150 | /** |
||
| 151 | * This method is used to set number of columns to be used |
||
| 152 | * when deciding a split at an internal node of the tree. <br> |
||
| 153 | * If the value is given 0, then all features are used (default behaviour), |
||
| 154 | * otherwise the given value will be used as a maximum for number of columns |
||
| 155 | * randomly selected for each split operation. |
||
| 156 | * |
||
| 157 | * @return $this |
||
| 158 | * |
||
| 159 | * @throws InvalidArgumentException |
||
| 160 | */ |
||
| 161 | public function setNumFeatures(int $numFeatures) |
||
| 162 | { |
||
| 163 | if ($numFeatures < 0) { |
||
| 164 | throw new InvalidArgumentException('Selected column count should be greater or equal to zero'); |
||
| 165 | } |
||
| 166 | |||
| 167 | $this->numUsableFeatures = $numFeatures; |
||
| 168 | |||
| 169 | return $this; |
||
| 170 | } |
||
| 171 | |||
| 172 | /** |
||
| 173 | * A string array to represent columns. Useful when HTML output or |
||
| 174 | * column importances are desired to be inspected. |
||
| 175 | * |
||
| 176 | * @return $this |
||
| 177 | * |
||
| 178 | * @throws InvalidArgumentException |
||
| 179 | */ |
||
| 180 | public function setColumnNames(array $names) |
||
| 181 | { |
||
| 182 | if ($this->featureCount !== 0 && count($names) !== $this->featureCount) { |
||
| 183 | throw new InvalidArgumentException(sprintf('Length of the given array should be equal to feature count %s', $this->featureCount)); |
||
| 184 | } |
||
| 185 | |||
| 186 | $this->columnNames = $names; |
||
| 187 | |||
| 188 | return $this; |
||
| 189 | } |
||
| 190 | |||
| 191 | public function getHtml(): string |
||
| 192 | { |
||
| 193 | return $this->tree->getHTML($this->columnNames); |
||
| 194 | } |
||
| 195 | |||
| 196 | /** |
||
| 197 | * This will return an array including an importance value for |
||
| 198 | * each column in the given dataset. The importance values are |
||
| 199 | * normalized and their total makes 1.<br/> |
||
| 200 | */ |
||
| 201 | public function getFeatureImportances(): array |
||
| 202 | { |
||
| 203 | if ($this->featureImportances !== null) { |
||
| 204 | return $this->featureImportances; |
||
| 205 | } |
||
| 206 | |||
| 207 | $sampleCount = count($this->samples); |
||
| 208 | $this->featureImportances = []; |
||
| 209 | foreach ($this->columnNames as $column => $columnName) { |
||
| 210 | $nodes = $this->getSplitNodesByColumn($column, $this->tree); |
||
| 211 | |||
| 212 | $importance = 0; |
||
| 213 | foreach ($nodes as $node) { |
||
| 214 | $importance += $node->getNodeImpurityDecrease($sampleCount); |
||
| 215 | } |
||
| 216 | |||
| 217 | $this->featureImportances[$columnName] = $importance; |
||
| 218 | } |
||
| 219 | |||
| 220 | // Normalize & sort the importances |
||
| 221 | $total = array_sum($this->featureImportances); |
||
| 222 | if ($total > 0) { |
||
| 223 | array_walk($this->featureImportances, function (&$importance) use ($total): void { |
||
| 224 | $importance /= $total; |
||
| 225 | }); |
||
| 226 | arsort($this->featureImportances); |
||
| 227 | } |
||
| 228 | |||
| 229 | return $this->featureImportances; |
||
| 230 | } |
||
| 231 | |||
| 232 | protected function getSplitLeaf(array $records, int $depth = 0): DecisionTreeLeaf |
||
| 291 | |||
| 292 | protected function getBestSplit(array $records): DecisionTreeLeaf |
||
| 335 | |||
| 336 | /** |
||
| 337 | * Returns available features/columns to the tree for the decision making |
||
| 338 | * process. <br> |
||
| 339 | * |
||
| 340 | * If a number is given with setNumFeatures() method, then a random selection |
||
| 341 | * of features up to this number is returned. <br> |
||
| 342 | * |
||
| 343 | * If some features are manually selected by use of setSelectedFeatures(), |
||
| 344 | * then only these features are returned <br> |
||
| 345 | * |
||
| 346 | * If any of above methods were not called beforehand, then all features |
||
| 347 | * are returned by default. |
||
| 348 | */ |
||
| 349 | protected function getSelectedFeatures(): array |
||
| 371 | |||
| 372 | protected function preprocess(array $samples): array |
||
| 397 | |||
| 398 | protected static function isCategoricalColumn(array $columnValues): bool |
||
| 421 | |||
| 422 | /** |
||
| 423 | * Used to set predefined features to consider while deciding which column to use for a split |
||
| 424 | */ |
||
| 425 | protected function setSelectedFeatures(array $selectedFeatures): void |
||
| 429 | |||
| 430 | /** |
||
| 431 | * Collects and returns an array of internal nodes that use the given |
||
| 432 | * column as a split criterion |
||
| 433 | */ |
||
| 434 | protected function getSplitNodesByColumn(int $column, DecisionTreeLeaf $node): array |
||
| 457 | |||
| 458 | /** |
||
| 459 | * @return mixed |
||
| 460 | */ |
||
| 461 | protected function predictSample(array $sample) |
||
| 478 | } |
||
| 479 |