Skip to content

Commit

Permalink
Add typehints to DecisionTree
Browse files Browse the repository at this point in the history
  • Loading branch information
akondas committed Mar 5, 2017
1 parent 01bb82a commit c6fbb83
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 39 deletions.
81 changes: 44 additions & 37 deletions src/Phpml/Classification/DecisionTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

namespace Phpml\Classification;

use Phpml\Exception\InvalidArgumentException;
use Phpml\Helper\Predictable;
use Phpml\Helper\Trainable;
use Phpml\Math\Statistic\Mean;
Expand All @@ -13,7 +14,7 @@ class DecisionTree implements Classifier
{
use Trainable, Predictable;

const CONTINUOS = 1;
const CONTINUOUS = 1;
const NOMINAL = 2;

/**
Expand Down Expand Up @@ -70,7 +71,7 @@ class DecisionTree implements Classifier
/**
* @param int $maxDepth
*/
public function __construct($maxDepth = 10)
public function __construct(int $maxDepth = 10)
{
$this->maxDepth = $maxDepth;
}
Expand All @@ -85,7 +86,7 @@ public function train(array $samples, array $targets)
$this->targets = array_merge($this->targets, $targets);

$this->featureCount = count($this->samples[0]);
$this->columnTypes = $this->getColumnTypes($this->samples);
$this->columnTypes = self::getColumnTypes($this->samples);
$this->labels = array_keys(array_count_values($this->targets));
$this->tree = $this->getSplitLeaf(range(0, count($this->samples) - 1));

Expand All @@ -105,23 +106,29 @@ public function train(array $samples, array $targets)
}
}

public static function getColumnTypes(array $samples)
/**
* @param array $samples
* @return array
*/
public static function getColumnTypes(array $samples) : array
{
$types = [];
$featureCount = count($samples[0]);
for ($i=0; $i < $featureCount; $i++) {
$values = array_column($samples, $i);
$isCategorical = self::isCategoricalColumn($values);
$types[] = $isCategorical ? self::NOMINAL : self::CONTINUOS;
$types[] = $isCategorical ? self::NOMINAL : self::CONTINUOUS;
}

return $types;
}

/**
* @param null|array $records
* @param array $records
* @param int $depth
* @return DecisionTreeLeaf
*/
protected function getSplitLeaf($records, $depth = 0)
protected function getSplitLeaf(array $records, int $depth = 0) : DecisionTreeLeaf
{
$split = $this->getBestSplit($records);
$split->level = $depth;
Expand Down Expand Up @@ -163,7 +170,7 @@ protected function getSplitLeaf($records, $depth = 0)
}
}

if (count($remainingTargets) == 1 || $allSame || $depth >= $this->maxDepth) {
if ($allSame || $depth >= $this->maxDepth || count($remainingTargets) === 1) {
$split->isTerminal = 1;
arsort($remainingTargets);
$split->classValue = key($remainingTargets);
Expand All @@ -175,14 +182,15 @@ protected function getSplitLeaf($records, $depth = 0)
$split->rightLeaf= $this->getSplitLeaf($rightRecords, $depth + 1);
}
}

return $split;
}

/**
* @param array $records
* @return DecisionTreeLeaf[]
* @return DecisionTreeLeaf
*/
protected function getBestSplit($records)
protected function getBestSplit(array $records) : DecisionTreeLeaf
{
$targets = array_intersect_key($this->targets, array_flip($records));
$samples = array_intersect_key($this->samples, array_flip($records));
Expand All @@ -199,18 +207,18 @@ protected function getBestSplit($records)
arsort($counts);
$baseValue = key($counts);
$gini = $this->getGiniIndex($baseValue, $colValues, $targets);
if ($bestSplit == null || $bestGiniVal > $gini) {
if ($bestSplit === null || $bestGiniVal > $gini) {
$split = new DecisionTreeLeaf();
$split->value = $baseValue;
$split->giniIndex = $gini;
$split->columnIndex = $i;
$split->isContinuous = $this->columnTypes[$i] == self::CONTINUOS;
$split->isContinuous = $this->columnTypes[$i] == self::CONTINUOUS;
$split->records = $records;

// If a numeric column is to be selected, then
// the original numeric value and the selected operator
// will also be saved into the leaf for future access
if ($this->columnTypes[$i] == self::CONTINUOS) {
if ($this->columnTypes[$i] == self::CONTINUOUS) {
$matches = [];
preg_match("/^([<>=]{1,2})\s*(.*)/", strval($split->value), $matches);
$split->operator = $matches[1];
Expand All @@ -221,6 +229,7 @@ protected function getBestSplit($records)
$bestGiniVal = $gini;
}
}

return $bestSplit;
}

Expand All @@ -239,10 +248,10 @@ protected function getBestSplit($records)
*
* @return array
*/
protected function getSelectedFeatures()
protected function getSelectedFeatures() : array
{
$allFeatures = range(0, $this->featureCount - 1);
if ($this->numUsableFeatures == 0 && ! $this->selectedFeatures) {
if ($this->numUsableFeatures === 0 && ! $this->selectedFeatures) {
return $allFeatures;
}

Expand All @@ -262,19 +271,20 @@ protected function getSelectedFeatures()
}

/**
* @param string $baseValue
* @param $baseValue
* @param array $colValues
* @param array $targets
* @return float
*/
public function getGiniIndex($baseValue, $colValues, $targets)
public function getGiniIndex($baseValue, array $colValues, array $targets) : float
{
$countMatrix = [];
foreach ($this->labels as $label) {
$countMatrix[$label] = [0, 0];
}
foreach ($colValues as $index => $value) {
$label = $targets[$index];
$rowIndex = $value == $baseValue ? 0 : 1;
$rowIndex = $value === $baseValue ? 0 : 1;
$countMatrix[$label][$rowIndex]++;
}
$giniParts = [0, 0];
Expand All @@ -288,21 +298,22 @@ public function getGiniIndex($baseValue, $colValues, $targets)
}
$giniParts[$i] = (1 - $part) * $sum;
}

return array_sum($giniParts) / count($colValues);
}

/**
* @param array $samples
* @return array
*/
protected function preprocess(array $samples)
protected function preprocess(array $samples) : array
{
// Detect and convert continuous data column values into
// discrete values by using the median as a threshold value
$columns = [];
for ($i=0; $i<$this->featureCount; $i++) {
$values = array_column($samples, $i);
if ($this->columnTypes[$i] == self::CONTINUOS) {
if ($this->columnTypes[$i] == self::CONTINUOUS) {
$median = Mean::median($values);
foreach ($values as &$value) {
if ($value <= $median) {
Expand All @@ -323,7 +334,7 @@ protected function preprocess(array $samples)
* @param array $columnValues
* @return bool
*/
protected static function isCategoricalColumn(array $columnValues)
protected static function isCategoricalColumn(array $columnValues) : bool
{
$count = count($columnValues);

Expand All @@ -337,15 +348,13 @@ protected static function isCategoricalColumn(array $columnValues)
if ($floatValues) {
return false;
}
if (count($numericValues) != $count) {
if (count($numericValues) !== $count) {
return true;
}

$distinctValues = array_count_values($columnValues);
if (count($distinctValues) <= $count / 5) {
return true;
}
return false;

return count($distinctValues) <= $count / 5;
}

/**
Expand All @@ -357,12 +366,12 @@ protected static function isCategoricalColumn(array $columnValues)
*
* @param int $numFeatures
* @return $this
* @throws Exception
* @throws InvalidArgumentException
*/
public function setNumFeatures(int $numFeatures)
{
if ($numFeatures < 0) {
throw new \Exception("Selected column count should be greater or equal to zero");
throw new InvalidArgumentException('Selected column count should be greater or equal to zero');
}

$this->numUsableFeatures = $numFeatures;
Expand All @@ -386,11 +395,12 @@ protected function setSelectedFeatures(array $selectedFeatures)
*
* @param array $names
* @return $this
* @throws InvalidArgumentException
*/
public function setColumnNames(array $names)
{
if ($this->featureCount != 0 && count($names) != $this->featureCount) {
throw new \Exception("Length of the given array should be equal to feature count ($this->featureCount)");
if ($this->featureCount !== 0 && count($names) !== $this->featureCount) {
throw new InvalidArgumentException(sprintf('Length of the given array should be equal to feature count %s', $this->featureCount));
}

$this->columnNames = $names;
Expand All @@ -411,7 +421,6 @@ public function getHtml()
* each column in the given dataset. The importance values are
* normalized and their total makes 1.<br/>
*
* @param array $labels
* @return array
*/
public function getFeatureImportances()
Expand Down Expand Up @@ -447,22 +456,20 @@ public function getFeatureImportances()

/**
* Collects and returns an array of internal nodes that use the given
* column as a split criteron
* column as a split criterion
*
* @param int $column
* @param DecisionTreeLeaf
* @param array $collected
*
* @param DecisionTreeLeaf $node
* @return array
*/
protected function getSplitNodesByColumn($column, DecisionTreeLeaf $node)
protected function getSplitNodesByColumn(int $column, DecisionTreeLeaf $node) : array
{
if (!$node || $node->isTerminal) {
return [];
}

$nodes = [];
if ($node->columnIndex == $column) {
if ($node->columnIndex === $column) {
$nodes[] = $node;
}

Expand Down
2 changes: 1 addition & 1 deletion src/Phpml/Classification/Linear/DecisionStump.php
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ protected function trainBinary(array $samples, array $targets)
'prob' => [], 'column' => 0,
'trainingErrorRate' => 1.0];
foreach ($columns as $col) {
if ($this->columnTypes[$col] == DecisionTree::CONTINUOS) {
if ($this->columnTypes[$col] == DecisionTree::CONTINUOUS) {
$split = $this->getBestNumericalSplit($col);
} else {
$split = $this->getBestNominalSplit($col);
Expand Down
5 changes: 4 additions & 1 deletion src/Phpml/Classification/WeightedClassifier.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@

abstract class WeightedClassifier implements Classifier
{
protected $weights = null;
/**
* @var array
*/
protected $weights;

/**
* Sets the array including a weight for each sample
Expand Down

0 comments on commit c6fbb83

Please sign in to comment.