Skip to content

Commit

Permalink
php-cs-fixer - more rules (#118)
Browse files Browse the repository at this point in the history
* Add new cs-fixer rules and run them

* Do not align double arrows/equals
  • Loading branch information
marmichalski authored and akondas committed Aug 17, 2017
1 parent ed5fc89 commit 3ac658c
Show file tree
Hide file tree
Showing 43 changed files with 269 additions and 201 deletions.
18 changes: 16 additions & 2 deletions .php_cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,25 @@
return PhpCsFixer\Config::create()
->setRules([
'@PSR2' => true,
'declare_strict_types' => true,
'array_syntax' => ['syntax' => 'short'],
'binary_operator_spaces' => ['align_double_arrow' => false, 'align_equals' => false],
'blank_line_after_opening_tag' => true,
'blank_line_before_return' => true,
'cast_spaces' => true,
'concat_space' => ['spacing' => 'none'],
'declare_strict_types' => true,
'method_separation' => true,
'no_blank_lines_after_class_opening' => true,
'no_spaces_around_offset' => ['positions' => ['inside', 'outside']],
'no_unneeded_control_parentheses' => true,
'no_unused_imports' => true,
'phpdoc_align' => true,
'phpdoc_no_access' => true,
'phpdoc_separation' => true,
'pre_increment' => true,
'single_quote' => true,
'trim_array_spaces' => true,
'single_blank_line_before_namespace' => true,
'no_unused_imports' => true
])
->setFinder(
PhpCsFixer\Finder::create()
Expand Down
6 changes: 3 additions & 3 deletions src/Phpml/Classification/DecisionTree.php
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ protected function getSplitLeaf(array $records, int $depth = 0) : DecisionTreeLe
// otherwise group the records so that we can classify the leaf
// in case maximum depth is reached
$leftRecords = [];
$rightRecords= [];
$rightRecords = [];
$remainingTargets = [];
$prevRecord = null;
$allSame = true;
Expand All @@ -162,7 +162,7 @@ protected function getSplitLeaf(array $records, int $depth = 0) : DecisionTreeLe
if ($split->evaluate($record)) {
$leftRecords[] = $recordNo;
} else {
$rightRecords[]= $recordNo;
$rightRecords[] = $recordNo;
}

// Group remaining targets
Expand All @@ -183,7 +183,7 @@ protected function getSplitLeaf(array $records, int $depth = 0) : DecisionTreeLe
$split->leftLeaf = $this->getSplitLeaf($leftRecords, $depth + 1);
}
if ($rightRecords) {
$split->rightLeaf= $this->getSplitLeaf($rightRecords, $depth + 1);
$split->rightLeaf = $this->getSplitLeaf($rightRecords, $depth + 1);
}
}

Expand Down
38 changes: 23 additions & 15 deletions src/Phpml/Classification/DecisionTree/DecisionTreeLeaf.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class DecisionTreeLeaf
/**
* @var DecisionTreeLeaf
*/
public $rightLeaf= null;
public $rightLeaf = null;

/**
* @var array
Expand Down Expand Up @@ -71,6 +71,7 @@ class DecisionTreeLeaf

/**
* @param array $record
*
* @return bool
*/
public function evaluate($record)
Expand All @@ -79,9 +80,10 @@ public function evaluate($record)

if ($this->isContinuous) {
$op = $this->operator;
$value= $this->numericValue;
$value = $this->numericValue;
$recordField = strval($recordField);
eval("\$result = $recordField $op $value;");

return $result;
}

Expand All @@ -102,16 +104,16 @@ public function getNodeImpurityDecrease(int $parentRecordCount)
return 0.0;
}

$nodeSampleCount = (float)count($this->records);
$nodeSampleCount = (float) count($this->records);
$iT = $this->giniIndex;

if ($this->leftLeaf) {
$pL = count($this->leftLeaf->records)/$nodeSampleCount;
$pL = count($this->leftLeaf->records) / $nodeSampleCount;
$iT -= $pL * $this->leftLeaf->giniIndex;
}

if ($this->rightLeaf) {
$pR = count($this->rightLeaf->records)/$nodeSampleCount;
$pR = count($this->rightLeaf->records) / $nodeSampleCount;
$iT -= $pR * $this->rightLeaf->giniIndex;
}

Expand All @@ -122,6 +124,7 @@ public function getNodeImpurityDecrease(int $parentRecordCount)
* Returns HTML representation of the node including children nodes
*
* @param $columnNames
*
* @return string
*/
public function getHTML($columnNames = null)
Expand All @@ -135,29 +138,34 @@ public function getHTML($columnNames = null)
} else {
$col = "col_$this->columnIndex";
}
if (!preg_match("/^[<>=]{1,2}/", $value)) {
if (!preg_match('/^[<>=]{1,2}/', $value)) {
$value = "=$value";
}
$value = "<b>$col $value</b><br>Gini: ". number_format($this->giniIndex, 2);
$value = "<b>$col $value</b><br>Gini: ".number_format($this->giniIndex, 2);
}
$str = "<table ><tr><td colspan=3 align=center style='border:1px solid;'>
$value</td></tr>";

$str = "<table ><tr><td colspan=3 align=center style='border:1px solid;'>$value</td></tr>";

if ($this->leftLeaf || $this->rightLeaf) {
$str .='<tr>';
$str .= '<tr>';
if ($this->leftLeaf) {
$str .="<td valign=top><b>| Yes</b><br>" . $this->leftLeaf->getHTML($columnNames) . "</td>";
$str .= '<td valign=top><b>| Yes</b><br>'.$this->leftLeaf->getHTML($columnNames).'</td>';
} else {
$str .='<td></td>';
$str .= '<td></td>';
}
$str .='<td>&nbsp;</td>';

$str .= '<td>&nbsp;</td>';
if ($this->rightLeaf) {
$str .="<td valign=top align=right><b>No |</b><br>" . $this->rightLeaf->getHTML($columnNames) . "</td>";
$str .= '<td valign=top align=right><b>No |</b><br>'.$this->rightLeaf->getHTML($columnNames).'</td>';
} else {
$str .='<td></td>';
$str .= '<td></td>';
}

$str .= '</tr>';
}

$str .= '</table>';

return $str;
}

Expand Down
18 changes: 11 additions & 7 deletions src/Phpml/Classification/Ensemble/AdaBoost.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class AdaBoost implements Classifier

/**
* Actual labels given in the targets array
*
* @var array
*/
protected $labels = [];
Expand Down Expand Up @@ -86,7 +87,7 @@ public function __construct(int $maxIterations = 50)
* Sets the base classifier that will be used for boosting (default = DecisionStump)
*
* @param string $baseClassifier
* @param array $classifierOptions
* @param array $classifierOptions
*/
public function setBaseClassifier(string $baseClassifier = DecisionStump::class, array $classifierOptions = [])
{
Expand All @@ -105,7 +106,7 @@ public function train(array $samples, array $targets)
// Initialize usual variables
$this->labels = array_keys(array_count_values($targets));
if (count($this->labels) != 2) {
throw new \Exception("AdaBoost is a binary classifier and can classify between two classes only");
throw new \Exception('AdaBoost is a binary classifier and can classify between two classes only');
}

// Set all target values to either -1 or 1
Expand Down Expand Up @@ -175,14 +176,14 @@ protected function resample()
{
$weights = $this->weights;
$std = StandardDeviation::population($weights);
$mean= Mean::arithmetic($weights);
$mean = Mean::arithmetic($weights);
$min = min($weights);
$minZ= (int)round(($min - $mean) / $std);
$minZ = (int) round(($min - $mean) / $std);

$samples = [];
$targets = [];
foreach ($weights as $index => $weight) {
$z = (int)round(($weight - $mean) / $std) - $minZ + 1;
$z = (int) round(($weight - $mean) / $std) - $minZ + 1;
for ($i = 0; $i < $z; ++$i) {
if (rand(0, 1) == 0) {
continue;
Expand Down Expand Up @@ -220,21 +221,23 @@ protected function evaluateClassifier(Classifier $classifier)
* Calculates alpha of a classifier
*
* @param float $errorRate
*
* @return float
*/
protected function calculateAlpha(float $errorRate)
{
if ($errorRate == 0) {
$errorRate = 1e-10;
}

return 0.5 * log((1 - $errorRate) / $errorRate);
}

/**
* Updates the sample weights
*
* @param Classifier $classifier
* @param float $alpha
* @param float $alpha
*/
protected function updateWeights(Classifier $classifier, float $alpha)
{
Expand All @@ -254,6 +257,7 @@ protected function updateWeights(Classifier $classifier, float $alpha)

/**
* @param array $sample
*
* @return mixed
*/
public function predictSample(array $sample)
Expand All @@ -264,6 +268,6 @@ public function predictSample(array $sample)
$sum += $h * $alpha;
}

return $this->labels[ $sum > 0 ? 1 : -1];
return $this->labels[$sum > 0 ? 1 : -1];
}
}
9 changes: 7 additions & 2 deletions src/Phpml/Classification/Ensemble/Bagging.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,10 +84,11 @@ public function __construct(int $numClassifier = 50)
public function setSubsetRatio(float $ratio)
{
if ($ratio < 0.1 || $ratio > 1.0) {
throw new \Exception("Subset ratio should be between 0.1 and 1.0");
throw new \Exception('Subset ratio should be between 0.1 and 1.0');
}

$this->subsetRatio = $ratio;

return $this;
}

Expand All @@ -100,7 +101,7 @@ public function setSubsetRatio(float $ratio)
* names are neglected.
*
* @param string $classifier
* @param array $classifierOptions
* @param array $classifierOptions
*
* @return $this
*/
Expand Down Expand Up @@ -135,6 +136,7 @@ public function train(array $samples, array $targets)

/**
* @param int $index
*
* @return array
*/
protected function getRandomSubset(int $index)
Expand Down Expand Up @@ -168,6 +170,7 @@ protected function initClassifiers()

$classifiers[] = $this->initSingleClassifier($obj);
}

return $classifiers;
}

Expand All @@ -183,6 +186,7 @@ protected function initSingleClassifier($classifier)

/**
* @param array $sample
*
* @return mixed
*/
protected function predictSample(array $sample)
Expand All @@ -196,6 +200,7 @@ protected function predictSample(array $sample)
$counts = array_count_values($predictions);
arsort($counts);
reset($counts);

return key($counts);
}
}
12 changes: 7 additions & 5 deletions src/Phpml/Classification/Ensemble/RandomForest.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,15 @@ public function __construct(int $numClassifier = 50)
public function setFeatureSubsetRatio($ratio)
{
if (is_float($ratio) && ($ratio < 0.1 || $ratio > 1.0)) {
throw new \Exception("When a float given, feature subset ratio should be between 0.1 and 1.0");
throw new \Exception('When a float given, feature subset ratio should be between 0.1 and 1.0');
}

if (is_string($ratio) && $ratio != 'sqrt' && $ratio != 'log') {
throw new \Exception("When a string given, feature subset ratio can only be 'sqrt' or 'log' ");
}

$this->featureSubsetRatio = $ratio;

return $this;
}

Expand All @@ -74,7 +75,7 @@ public function setFeatureSubsetRatio($ratio)
public function setClassifer(string $classifier, array $classifierOptions = [])
{
if ($classifier != DecisionTree::class) {
throw new \Exception("RandomForest can only use DecisionTree as base classifier");
throw new \Exception('RandomForest can only use DecisionTree as base classifier');
}

return parent::setClassifer($classifier, $classifierOptions);
Expand Down Expand Up @@ -120,6 +121,7 @@ public function getFeatureImportances()
* when trying to print some information about the trees such as feature importances
*
* @param array $names
*
* @return $this
*/
public function setColumnNames(array $names)
Expand All @@ -137,11 +139,11 @@ public function setColumnNames(array $names)
protected function initSingleClassifier($classifier)
{
if (is_float($this->featureSubsetRatio)) {
$featureCount = (int)($this->featureSubsetRatio * $this->featureCount);
$featureCount = (int) ($this->featureSubsetRatio * $this->featureCount);
} elseif ($this->featureCount == 'sqrt') {
$featureCount = (int)sqrt($this->featureCount) + 1;
$featureCount = (int) sqrt($this->featureCount) + 1;
} else {
$featureCount = (int)log($this->featureCount, 2) + 1;
$featureCount = (int) log($this->featureCount, 2) + 1;
}

if ($featureCount >= $this->featureCount) {
Expand Down
6 changes: 3 additions & 3 deletions src/Phpml/Classification/Linear/Adaline.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ class Adaline extends Perceptron
/**
* Batch training is the default Adaline training algorithm
*/
const BATCH_TRAINING = 1;
const BATCH_TRAINING = 1;

/**
* Online training: Stochastic gradient descent learning
*/
const ONLINE_TRAINING = 2;
const ONLINE_TRAINING = 2;

/**
* Training type may be either 'Batch' or 'Online' learning
Expand Down Expand Up @@ -46,7 +46,7 @@ public function __construct(
int $trainingType = self::BATCH_TRAINING
) {
if (!in_array($trainingType, [self::BATCH_TRAINING, self::ONLINE_TRAINING])) {
throw new \Exception("Adaline can only be trained with batch and online/stochastic gradient descent algorithm");
throw new \Exception('Adaline can only be trained with batch and online/stochastic gradient descent algorithm');
}

$this->trainingType = $trainingType;
Expand Down
Loading

0 comments on commit 3ac658c

Please sign in to comment.