From 653c7c772dc3ee85848f01204f6315efc9af139a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20Votruba?= Date: Tue, 14 Nov 2017 21:21:23 +0100 Subject: [PATCH] Upgrade to PHP 7.1 (#150) * upgrade to PHP 7.1 * bump travis and composer to PHP 7.1 * fix tests --- .travis.yml | 5 +-- composer.json | 2 +- src/Phpml/Association/Apriori.php | 12 +++--- src/Phpml/Classification/DecisionTree.php | 8 ++-- .../Classification/Ensemble/AdaBoost.php | 8 ++-- src/Phpml/Classification/Ensemble/Bagging.php | 4 +- .../Classification/KNearestNeighbors.php | 2 +- src/Phpml/Classification/Linear/Adaline.php | 4 +- .../Classification/Linear/DecisionStump.php | 14 +++---- .../Linear/LogisticRegression.php | 12 +++--- .../Classification/Linear/Perceptron.php | 10 +++-- src/Phpml/Classification/MLPClassifier.php | 2 +- src/Phpml/Classification/NaiveBayes.php | 10 ++--- src/Phpml/Classification/SVC.php | 2 +- .../Classification/WeightedClassifier.php | 2 +- src/Phpml/Clustering/DBSCAN.php | 2 +- src/Phpml/Clustering/FuzzyCMeans.php | 8 ++-- src/Phpml/Clustering/KMeans.php | 4 +- src/Phpml/Clustering/KMeans/Cluster.php | 8 ++-- src/Phpml/Clustering/KMeans/Point.php | 4 +- src/Phpml/Clustering/KMeans/Space.php | 6 +-- src/Phpml/CrossValidation/RandomSplit.php | 2 +- src/Phpml/CrossValidation/Split.php | 4 +- .../CrossValidation/StratifiedRandomSplit.php | 2 +- src/Phpml/Dataset/FilesDataset.php | 4 +- .../EigenTransformerBase.php | 2 +- src/Phpml/DimensionReduction/KernelPCA.php | 10 ++--- src/Phpml/DimensionReduction/LDA.php | 2 +- src/Phpml/DimensionReduction/PCA.php | 4 +- .../FeatureExtraction/TfIdfTransformer.php | 8 ++-- .../TokenCountVectorizer.php | 18 ++++----- src/Phpml/Helper/OneVsRest.php | 10 ++--- .../Helper/Optimizer/ConjugateGradient.php | 4 +- src/Phpml/Helper/Optimizer/GD.php | 8 ++-- src/Phpml/Helper/Optimizer/StochasticGD.php | 4 +- src/Phpml/Helper/Trainable.php | 2 +- .../LinearAlgebra/EigenvalueDecomposition.php | 10 ++--- src/Phpml/Math/Statistic/Covariance.php | 6 +-- src/Phpml/Math/Statistic/Mean.php | 2 +- src/Phpml/Metric/ClassificationReport.php | 4 +- src/Phpml/Metric/ConfusionMatrix.php | 2 +- src/Phpml/ModelManager.php | 2 +- src/Phpml/NeuralNetwork/Layer.php | 6 +-- .../NeuralNetwork/Network/LayeredNetwork.php | 4 +- .../Network/MultilayerPerceptron.php | 24 ++++++------ src/Phpml/NeuralNetwork/Node/Input.php | 2 +- src/Phpml/NeuralNetwork/Node/Neuron.php | 6 +-- .../NeuralNetwork/Node/Neuron/Synapse.php | 4 +- .../Training/Backpropagation.php | 2 +- src/Phpml/Pipeline.php | 8 ++-- src/Phpml/Preprocessing/Imputer.php | 10 ++--- src/Phpml/Preprocessing/Normalizer.php | 16 ++++---- src/Phpml/Regression/LeastSquares.php | 4 +- src/Phpml/Regression/SVR.php | 2 +- src/Phpml/SupportVectorMachine/Kernel.php | 8 ++-- .../SupportVectorMachine.php | 12 +++--- src/Phpml/SupportVectorMachine/Type.php | 10 ++--- tests/Phpml/Association/AprioriTest.php | 30 +++++++-------- .../DecisionTree/DecisionTreeLeafTest.php | 2 +- .../Phpml/Classification/DecisionTreeTest.php | 14 +++---- .../Classification/Ensemble/AdaBoostTest.php | 2 +- .../Classification/Ensemble/BaggingTest.php | 14 +++---- .../Ensemble/RandomForestTest.php | 2 +- .../Classification/KNearestNeighborsTest.php | 8 ++-- .../Classification/Linear/AdalineTest.php | 4 +- .../Linear/DecisionStumpTest.php | 2 +- .../Classification/Linear/PerceptronTest.php | 4 +- .../Classification/MLPClassifierTest.php | 22 +++++------ tests/Phpml/Classification/NaiveBayesTest.php | 6 +-- tests/Phpml/Classification/SVCTest.php | 6 +-- tests/Phpml/Clustering/DBSCANTest.php | 4 +- tests/Phpml/Clustering/FuzzyCMeansTest.php | 2 +- tests/Phpml/Clustering/KMeansTest.php | 6 +-- .../Phpml/CrossValidation/RandomSplitTest.php | 12 +++--- .../StratifiedRandomSplitTest.php | 4 +- tests/Phpml/Dataset/ArrayDatasetTest.php | 4 +- tests/Phpml/Dataset/CsvDatasetTest.php | 8 ++-- tests/Phpml/Dataset/Demo/GlassDatasetTest.php | 2 +- tests/Phpml/Dataset/Demo/IrisDatasetTest.php | 2 +- tests/Phpml/Dataset/Demo/WineDatasetTest.php | 2 +- tests/Phpml/Dataset/FilesDatasetTest.php | 4 +- .../DimensionReduction/KernelPCATest.php | 4 +- tests/Phpml/DimensionReduction/LDATest.php | 4 +- tests/Phpml/DimensionReduction/PCATest.php | 6 +-- .../Phpml/FeatureExtraction/StopWordsTest.php | 10 ++--- .../TfIdfTransformerTest.php | 2 +- .../TokenCountVectorizerTest.php | 6 +-- tests/Phpml/Math/ComparisonTest.php | 4 +- tests/Phpml/Math/Distance/ChebyshevTest.php | 10 ++--- tests/Phpml/Math/Distance/EuclideanTest.php | 10 ++--- tests/Phpml/Math/Distance/ManhattanTest.php | 10 ++--- tests/Phpml/Math/Distance/MinkowskiTest.php | 12 +++--- tests/Phpml/Math/Kernel/RBFTest.php | 2 +- .../LinearAlgebra/EigenDecompositionTest.php | 2 +- tests/Phpml/Math/MatrixTest.php | 38 +++++++++---------- tests/Phpml/Math/ProductTest.php | 2 +- tests/Phpml/Math/SetTest.php | 20 +++++----- .../Phpml/Math/Statistic/CorrelationTest.php | 4 +- tests/Phpml/Math/Statistic/CovarianceTest.php | 2 +- tests/Phpml/Math/Statistic/GaussianTest.php | 2 +- tests/Phpml/Math/Statistic/MeanTest.php | 14 +++---- .../Math/Statistic/StandardDeviationTest.php | 6 +-- tests/Phpml/Metric/AccuracyTest.php | 8 ++-- .../Phpml/Metric/ClassificationReportTest.php | 10 ++--- tests/Phpml/Metric/ConfusionMatrixTest.php | 6 +-- tests/Phpml/ModelManagerTest.php | 4 +- .../ActivationFunction/BinaryStepTest.php | 2 +- .../ActivationFunction/GaussianTest.php | 2 +- .../HyperboliTangentTest.php | 2 +- .../ActivationFunction/PReLUTest.php | 2 +- .../ActivationFunction/SigmoidTest.php | 2 +- .../ThresholdedReLUTest.php | 2 +- tests/Phpml/NeuralNetwork/LayerTest.php | 10 ++--- .../Network/LayeredNetworkTest.php | 6 +-- tests/Phpml/NeuralNetwork/Node/BiasTest.php | 2 +- tests/Phpml/NeuralNetwork/Node/InputTest.php | 4 +- .../NeuralNetwork/Node/Neuron/SynapseTest.php | 4 +- tests/Phpml/NeuralNetwork/Node/NeuronTest.php | 8 ++-- tests/Phpml/PipelineTest.php | 8 ++-- tests/Phpml/Preprocessing/ImputerTest.php | 14 +++---- tests/Phpml/Preprocessing/NormalizerTest.php | 12 +++--- tests/Phpml/Regression/LeastSquaresTest.php | 8 ++-- tests/Phpml/Regression/SVRTest.php | 6 +-- .../DataTransformerTest.php | 4 +- .../SupportVectorMachineTest.php | 12 +++--- .../Tokenization/WhitespaceTokenizerTest.php | 4 +- .../Phpml/Tokenization/WordTokenizerTest.php | 4 +- 127 files changed, 419 insertions(+), 420 deletions(-) diff --git a/.travis.yml b/.travis.yml index 7c5b9bb..48162fd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -4,9 +4,6 @@ matrix: fast_finish: true include: - - os: linux - php: '7.0' - - os: linux php: '7.1' @@ -18,7 +15,7 @@ matrix: language: generic env: - _OSX=10.11 - - _PHP: php70 + - _PHP: php71 before_install: - if [[ "${TRAVIS_OS_NAME}" == "osx" ]]; then /usr/bin/env bash tools/prepare_osx_env.sh ; fi diff --git a/composer.json b/composer.json index 18ae994..8db4934 100644 --- a/composer.json +++ b/composer.json @@ -17,7 +17,7 @@ } }, "require": { - "php": ">=7.0.0" + "php": "^7.1" }, "require-dev": { "phpunit/phpunit": "^6.0", diff --git a/src/Phpml/Association/Apriori.php b/src/Phpml/Association/Apriori.php index ee9c383..f1398d2 100644 --- a/src/Phpml/Association/Apriori.php +++ b/src/Phpml/Association/Apriori.php @@ -11,13 +11,13 @@ class Apriori implements Associator { use Trainable, Predictable; - const ARRAY_KEY_ANTECEDENT = 'antecedent'; + public const ARRAY_KEY_ANTECEDENT = 'antecedent'; - const ARRAY_KEY_CONFIDENCE = 'confidence'; + public const ARRAY_KEY_CONFIDENCE = 'confidence'; - const ARRAY_KEY_CONSEQUENT = 'consequent'; + public const ARRAY_KEY_CONSEQUENT = 'consequent'; - const ARRAY_KEY_SUPPORT = 'support'; + public const ARRAY_KEY_SUPPORT = 'support'; /** * Minimum relative probability of frequent transactions. @@ -116,7 +116,7 @@ class Apriori implements Associator /** * Generate rules for each k-length frequent item set. */ - private function generateAllRules() + private function generateAllRules(): void { for ($k = 2; !empty($this->large[$k]); ++$k) { foreach ($this->large[$k] as $frequent) { @@ -130,7 +130,7 @@ class Apriori implements Associator * * @param mixed[] $frequent */ - private function generateRules(array $frequent) + private function generateRules(array $frequent): void { foreach ($this->antecedents($frequent) as $antecedent) { if ($this->confidence <= ($confidence = $this->confidence($frequent, $antecedent))) { diff --git a/src/Phpml/Classification/DecisionTree.php b/src/Phpml/Classification/DecisionTree.php index f99b032..653b1bf 100644 --- a/src/Phpml/Classification/DecisionTree.php +++ b/src/Phpml/Classification/DecisionTree.php @@ -14,8 +14,8 @@ class DecisionTree implements Classifier { use Trainable, Predictable; - const CONTINUOUS = 1; - const NOMINAL = 2; + public const CONTINUOUS = 1; + public const NOMINAL = 2; /** * @var array @@ -72,7 +72,7 @@ class DecisionTree implements Classifier $this->maxDepth = $maxDepth; } - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); @@ -354,7 +354,7 @@ class DecisionTree implements Classifier /** * Used to set predefined features to consider while deciding which column to use for a split */ - protected function setSelectedFeatures(array $selectedFeatures) + protected function setSelectedFeatures(array $selectedFeatures): void { $this->selectedFeatures = $selectedFeatures; } diff --git a/src/Phpml/Classification/Ensemble/AdaBoost.php b/src/Phpml/Classification/Ensemble/AdaBoost.php index 9fdd65b..5bdca1b 100644 --- a/src/Phpml/Classification/Ensemble/AdaBoost.php +++ b/src/Phpml/Classification/Ensemble/AdaBoost.php @@ -84,7 +84,7 @@ class AdaBoost implements Classifier /** * Sets the base classifier that will be used for boosting (default = DecisionStump) */ - public function setBaseClassifier(string $baseClassifier = DecisionStump::class, array $classifierOptions = []) + public function setBaseClassifier(string $baseClassifier = DecisionStump::class, array $classifierOptions = []): void { $this->baseClassifier = $baseClassifier; $this->classifierOptions = $classifierOptions; @@ -93,7 +93,7 @@ class AdaBoost implements Classifier /** * @throws \Exception */ - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { // Initialize usual variables $this->labels = array_keys(array_count_values($targets)); @@ -149,7 +149,7 @@ class AdaBoost implements Classifier $classifier->setSampleWeights($this->weights); $classifier->train($this->samples, $this->targets); } else { - list($samples, $targets) = $this->resample(); + [$samples, $targets] = $this->resample(); $classifier->train($samples, $targets); } @@ -216,7 +216,7 @@ class AdaBoost implements Classifier /** * Updates the sample weights */ - protected function updateWeights(Classifier $classifier, float $alpha) + protected function updateWeights(Classifier $classifier, float $alpha): void { $sumOfWeights = array_sum($this->weights); $weightsT1 = []; diff --git a/src/Phpml/Classification/Ensemble/Bagging.php b/src/Phpml/Classification/Ensemble/Bagging.php index ebc7528..8d2bbf9 100644 --- a/src/Phpml/Classification/Ensemble/Bagging.php +++ b/src/Phpml/Classification/Ensemble/Bagging.php @@ -106,7 +106,7 @@ class Bagging implements Classifier return $this; } - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); @@ -117,7 +117,7 @@ class Bagging implements Classifier $this->classifiers = $this->initClassifiers(); $index = 0; foreach ($this->classifiers as $classifier) { - list($samples, $targets) = $this->getRandomSubset($index); + [$samples, $targets] = $this->getRandomSubset($index); $classifier->train($samples, $targets); ++$index; } diff --git a/src/Phpml/Classification/KNearestNeighbors.php b/src/Phpml/Classification/KNearestNeighbors.php index c7783d8..a261631 100644 --- a/src/Phpml/Classification/KNearestNeighbors.php +++ b/src/Phpml/Classification/KNearestNeighbors.php @@ -26,7 +26,7 @@ class KNearestNeighbors implements Classifier /** * @param Distance|null $distanceMetric (if null then Euclidean distance as default) */ - public function __construct(int $k = 3, Distance $distanceMetric = null) + public function __construct(int $k = 3, ?Distance $distanceMetric = null) { if (null === $distanceMetric) { $distanceMetric = new Euclidean(); diff --git a/src/Phpml/Classification/Linear/Adaline.php b/src/Phpml/Classification/Linear/Adaline.php index 2a649ad..64d25a4 100644 --- a/src/Phpml/Classification/Linear/Adaline.php +++ b/src/Phpml/Classification/Linear/Adaline.php @@ -9,12 +9,12 @@ class Adaline extends Perceptron /** * Batch training is the default Adaline training algorithm */ - const BATCH_TRAINING = 1; + public const BATCH_TRAINING = 1; /** * Online training: Stochastic gradient descent learning */ - const ONLINE_TRAINING = 2; + public const ONLINE_TRAINING = 2; /** * Training type may be either 'Batch' or 'Online' learning diff --git a/src/Phpml/Classification/Linear/DecisionStump.php b/src/Phpml/Classification/Linear/DecisionStump.php index 014dceb..e1486a6 100644 --- a/src/Phpml/Classification/Linear/DecisionStump.php +++ b/src/Phpml/Classification/Linear/DecisionStump.php @@ -14,7 +14,7 @@ class DecisionStump extends WeightedClassifier { use Predictable, OneVsRest; - const AUTO_SELECT = -1; + public const AUTO_SELECT = -1; /** * @var int @@ -86,7 +86,7 @@ class DecisionStump extends WeightedClassifier /** * @throws \Exception */ - protected function trainBinary(array $samples, array $targets, array $labels) + protected function trainBinary(array $samples, array $targets, array $labels): void { $this->binaryLabels = $labels; $this->featureCount = count($samples[0]); @@ -146,7 +146,7 @@ class DecisionStump extends WeightedClassifier * points to be probed. The more split counts, the better performance but * worse processing time (Default value is 10.0) */ - public function setNumericalSplitCount(float $count) + public function setNumericalSplitCount(float $count): void { $this->numSplitCount = $count; } @@ -171,7 +171,7 @@ class DecisionStump extends WeightedClassifier // Before trying all possible split points, let's first try // the average value for the cut point $threshold = array_sum($values) / (float) count($values); - list($errorRate, $prob) = $this->calculateErrorRate($targets, $threshold, $operator, $values); + [$errorRate, $prob] = $this->calculateErrorRate($targets, $threshold, $operator, $values); if ($split == null || $errorRate < $split['trainingErrorRate']) { $split = ['value' => $threshold, 'operator' => $operator, 'prob' => $prob, 'column' => $col, @@ -181,7 +181,7 @@ class DecisionStump extends WeightedClassifier // Try other possible points one by one for ($step = $minValue; $step <= $maxValue; $step += $stepSize) { $threshold = (float) $step; - list($errorRate, $prob) = $this->calculateErrorRate($targets, $threshold, $operator, $values); + [$errorRate, $prob] = $this->calculateErrorRate($targets, $threshold, $operator, $values); if ($errorRate < $split['trainingErrorRate']) { $split = ['value' => $threshold, 'operator' => $operator, 'prob' => $prob, 'column' => $col, @@ -203,7 +203,7 @@ class DecisionStump extends WeightedClassifier foreach (['=', '!='] as $operator) { foreach ($distinctVals as $val) { - list($errorRate, $prob) = $this->calculateErrorRate($targets, $val, $operator, $values); + [$errorRate, $prob] = $this->calculateErrorRate($targets, $val, $operator, $values); if ($split == null || $split['trainingErrorRate'] < $errorRate) { $split = ['value' => $val, 'operator' => $operator, @@ -289,7 +289,7 @@ class DecisionStump extends WeightedClassifier return $this->binaryLabels[1]; } - protected function resetBinary() + protected function resetBinary(): void { } diff --git a/src/Phpml/Classification/Linear/LogisticRegression.php b/src/Phpml/Classification/Linear/LogisticRegression.php index bfbeb44..e8881be 100644 --- a/src/Phpml/Classification/Linear/LogisticRegression.php +++ b/src/Phpml/Classification/Linear/LogisticRegression.php @@ -11,17 +11,17 @@ class LogisticRegression extends Adaline /** * Batch training: Gradient descent algorithm (default) */ - const BATCH_TRAINING = 1; + public const BATCH_TRAINING = 1; /** * Online training: Stochastic gradient descent learning */ - const ONLINE_TRAINING = 2; + public const ONLINE_TRAINING = 2; /** * Conjugate Batch: Conjugate Gradient algorithm */ - const CONJUGATE_GRAD_TRAINING = 3; + public const CONJUGATE_GRAD_TRAINING = 3; /** * Cost function to optimize: 'log' and 'sse' are supported
@@ -97,7 +97,7 @@ class LogisticRegression extends Adaline * Sets the learning rate if gradient descent algorithm is * selected for training */ - public function setLearningRate(float $learningRate) + public function setLearningRate(float $learningRate): void { $this->learningRate = $learningRate; } @@ -106,7 +106,7 @@ class LogisticRegression extends Adaline * Lambda (λ) parameter of regularization term. If 0 is given, * then the regularization term is cancelled */ - public function setLambda(float $lambda) + public function setLambda(float $lambda): void { $this->lambda = $lambda; } @@ -139,7 +139,7 @@ class LogisticRegression extends Adaline /** * Executes Conjugate Gradient method to optimize the weights of the LogReg model */ - protected function runConjugateGradient(array $samples, array $targets, \Closure $gradientFunc) + protected function runConjugateGradient(array $samples, array $targets, \Closure $gradientFunc): void { if (empty($this->optimizer)) { $this->optimizer = (new ConjugateGradient($this->featureCount)) diff --git a/src/Phpml/Classification/Linear/Perceptron.php b/src/Phpml/Classification/Linear/Perceptron.php index d5f424b..77eb717 100644 --- a/src/Phpml/Classification/Linear/Perceptron.php +++ b/src/Phpml/Classification/Linear/Perceptron.php @@ -88,12 +88,12 @@ class Perceptron implements Classifier, IncrementalEstimator $this->maxIterations = $maxIterations; } - public function partialTrain(array $samples, array $targets, array $labels = []) + public function partialTrain(array $samples, array $targets, array $labels = []): void { $this->trainByLabel($samples, $targets, $labels); } - public function trainBinary(array $samples, array $targets, array $labels) + public function trainBinary(array $samples, array $targets, array $labels): void { if ($this->normalizer) { $this->normalizer->transform($samples); @@ -111,7 +111,7 @@ class Perceptron implements Classifier, IncrementalEstimator $this->runTraining($samples, $targets); } - protected function resetBinary() + protected function resetBinary(): void { $this->labels = []; $this->optimizer = null; @@ -148,6 +148,8 @@ class Perceptron implements Classifier, IncrementalEstimator /** * Trains the perceptron model with Stochastic Gradient Descent optimization * to get the correct set of weights + * + * @return void|mixed */ protected function runTraining(array $samples, array $targets) { @@ -169,7 +171,7 @@ class Perceptron implements Classifier, IncrementalEstimator * Executes a Gradient Descent algorithm for * the given cost function */ - protected function runGradientDescent(array $samples, array $targets, \Closure $gradientFunc, bool $isBatch = false) + protected function runGradientDescent(array $samples, array $targets, \Closure $gradientFunc, bool $isBatch = false): void { $class = $isBatch ? GD::class : StochasticGD::class; diff --git a/src/Phpml/Classification/MLPClassifier.php b/src/Phpml/Classification/MLPClassifier.php index 64e6f50..b76091d 100644 --- a/src/Phpml/Classification/MLPClassifier.php +++ b/src/Phpml/Classification/MLPClassifier.php @@ -45,7 +45,7 @@ class MLPClassifier extends MultilayerPerceptron implements Classifier /** * @param mixed $target */ - protected function trainSample(array $sample, $target) + protected function trainSample(array $sample, $target): void { // Feed-forward. diff --git a/src/Phpml/Classification/NaiveBayes.php b/src/Phpml/Classification/NaiveBayes.php index 08073da..97f734a 100644 --- a/src/Phpml/Classification/NaiveBayes.php +++ b/src/Phpml/Classification/NaiveBayes.php @@ -13,9 +13,9 @@ class NaiveBayes implements Classifier { use Trainable, Predictable; - const CONTINUOS = 1; - const NOMINAL = 2; - const EPSILON = 1e-10; + public const CONTINUOS = 1; + public const NOMINAL = 2; + public const EPSILON = 1e-10; /** * @var array @@ -57,7 +57,7 @@ class NaiveBayes implements Classifier */ private $labels = []; - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); @@ -77,7 +77,7 @@ class NaiveBayes implements Classifier * Calculates vital statistics for each label & feature. Stores these * values in private array in order to avoid repeated calculation */ - private function calculateStatistics(string $label, array $samples) + private function calculateStatistics(string $label, array $samples): void { $this->std[$label] = array_fill(0, $this->featureCount, 0); $this->mean[$label] = array_fill(0, $this->featureCount, 0); diff --git a/src/Phpml/Classification/SVC.php b/src/Phpml/Classification/SVC.php index 8cabcbc..de71bbe 100644 --- a/src/Phpml/Classification/SVC.php +++ b/src/Phpml/Classification/SVC.php @@ -14,7 +14,7 @@ class SVC extends SupportVectorMachine implements Classifier int $kernel = Kernel::LINEAR, float $cost = 1.0, int $degree = 3, - float $gamma = null, + ?float $gamma = null, float $coef0 = 0.0, float $tolerance = 0.001, int $cacheSize = 100, diff --git a/src/Phpml/Classification/WeightedClassifier.php b/src/Phpml/Classification/WeightedClassifier.php index 0a5f192..c9b1f97 100644 --- a/src/Phpml/Classification/WeightedClassifier.php +++ b/src/Phpml/Classification/WeightedClassifier.php @@ -14,7 +14,7 @@ abstract class WeightedClassifier implements Classifier /** * Sets the array including a weight for each sample */ - public function setSampleWeights(array $weights) + public function setSampleWeights(array $weights): void { $this->weights = $weights; } diff --git a/src/Phpml/Clustering/DBSCAN.php b/src/Phpml/Clustering/DBSCAN.php index 70cf302..1968b83 100644 --- a/src/Phpml/Clustering/DBSCAN.php +++ b/src/Phpml/Clustering/DBSCAN.php @@ -24,7 +24,7 @@ class DBSCAN implements Clusterer */ private $distanceMetric; - public function __construct(float $epsilon = 0.5, int $minSamples = 3, Distance $distanceMetric = null) + public function __construct(float $epsilon = 0.5, int $minSamples = 3, ?Distance $distanceMetric = null) { if (null === $distanceMetric) { $distanceMetric = new Euclidean(); diff --git a/src/Phpml/Clustering/FuzzyCMeans.php b/src/Phpml/Clustering/FuzzyCMeans.php index d14c0be..6eccea0 100644 --- a/src/Phpml/Clustering/FuzzyCMeans.php +++ b/src/Phpml/Clustering/FuzzyCMeans.php @@ -71,7 +71,7 @@ class FuzzyCMeans implements Clusterer $this->maxIterations = $maxIterations; } - protected function initClusters() + protected function initClusters(): void { // Membership array is a matrix of cluster number by sample counts // We initilize the membership array with random values @@ -80,7 +80,7 @@ class FuzzyCMeans implements Clusterer $this->updateClusters(); } - protected function generateRandomMembership(int $rows, int $cols) + protected function generateRandomMembership(int $rows, int $cols): void { $this->membership = []; for ($i = 0; $i < $rows; ++$i) { @@ -98,7 +98,7 @@ class FuzzyCMeans implements Clusterer } } - protected function updateClusters() + protected function updateClusters(): void { $dim = $this->space->getDimension(); if (!$this->clusters) { @@ -136,7 +136,7 @@ class FuzzyCMeans implements Clusterer return $sum; } - protected function updateMembershipMatrix() + protected function updateMembershipMatrix(): void { for ($i = 0; $i < $this->clustersNumber; ++$i) { for ($k = 0; $k < $this->sampleCount; ++$k) { diff --git a/src/Phpml/Clustering/KMeans.php b/src/Phpml/Clustering/KMeans.php index 0a776a4..a4e85bc 100644 --- a/src/Phpml/Clustering/KMeans.php +++ b/src/Phpml/Clustering/KMeans.php @@ -9,8 +9,8 @@ use Phpml\Exception\InvalidArgumentException; class KMeans implements Clusterer { - const INIT_RANDOM = 1; - const INIT_KMEANS_PLUS_PLUS = 2; + public const INIT_RANDOM = 1; + public const INIT_KMEANS_PLUS_PLUS = 2; /** * @var int diff --git a/src/Phpml/Clustering/KMeans/Cluster.php b/src/Phpml/Clustering/KMeans/Cluster.php index b7c7ecf..22545b6 100644 --- a/src/Phpml/Clustering/KMeans/Cluster.php +++ b/src/Phpml/Clustering/KMeans/Cluster.php @@ -64,17 +64,17 @@ class Cluster extends Point implements IteratorAggregate, Countable return $point; } - public function attachAll(SplObjectStorage $points) + public function attachAll(SplObjectStorage $points): void { $this->points->addAll($points); } - public function detachAll(SplObjectStorage $points) + public function detachAll(SplObjectStorage $points): void { $this->points->removeAll($points); } - public function updateCentroid() + public function updateCentroid(): void { if (!$count = count($this->points)) { return; @@ -109,7 +109,7 @@ class Cluster extends Point implements IteratorAggregate, Countable return count($this->points); } - public function setCoordinates(array $newCoordinates) + public function setCoordinates(array $newCoordinates): void { $this->coordinates = $newCoordinates; } diff --git a/src/Phpml/Clustering/KMeans/Point.php b/src/Phpml/Clustering/KMeans/Point.php index 08fa11e..f90de8a 100644 --- a/src/Phpml/Clustering/KMeans/Point.php +++ b/src/Phpml/Clustering/KMeans/Point.php @@ -93,7 +93,7 @@ class Point implements ArrayAccess * @param mixed $offset * @param mixed $value */ - public function offsetSet($offset, $value) + public function offsetSet($offset, $value): void { $this->coordinates[$offset] = $value; } @@ -101,7 +101,7 @@ class Point implements ArrayAccess /** * @param mixed $offset */ - public function offsetUnset($offset) + public function offsetUnset($offset): void { unset($this->coordinates[$offset]); } diff --git a/src/Phpml/Clustering/KMeans/Space.php b/src/Phpml/Clustering/KMeans/Space.php index bf2a345..4412d53 100644 --- a/src/Phpml/Clustering/KMeans/Space.php +++ b/src/Phpml/Clustering/KMeans/Space.php @@ -47,7 +47,7 @@ class Space extends SplObjectStorage /** * @param null $data */ - public function addPoint(array $coordinates, $data = null) + public function addPoint(array $coordinates, $data = null): void { $this->attach($this->newPoint($coordinates), $data); } @@ -56,7 +56,7 @@ class Space extends SplObjectStorage * @param Point $point * @param null $data */ - public function attach($point, $data = null) + public function attach($point, $data = null): void { if (!$point instanceof Point) { throw new InvalidArgumentException('can only attach points to spaces'); @@ -180,7 +180,7 @@ class Space extends SplObjectStorage private function initializeRandomClusters(int $clustersNumber) : array { $clusters = []; - list($min, $max) = $this->getBoundaries(); + [$min, $max] = $this->getBoundaries(); for ($n = 0; $n < $clustersNumber; ++$n) { $clusters[] = new Cluster($this, $this->getRandomPoint($min, $max)->getCoordinates()); diff --git a/src/Phpml/CrossValidation/RandomSplit.php b/src/Phpml/CrossValidation/RandomSplit.php index 7ec1875..8507ee5 100644 --- a/src/Phpml/CrossValidation/RandomSplit.php +++ b/src/Phpml/CrossValidation/RandomSplit.php @@ -8,7 +8,7 @@ use Phpml\Dataset\Dataset; class RandomSplit extends Split { - protected function splitDataset(Dataset $dataset, float $testSize) + protected function splitDataset(Dataset $dataset, float $testSize): void { $samples = $dataset->getSamples(); $labels = $dataset->getTargets(); diff --git a/src/Phpml/CrossValidation/Split.php b/src/Phpml/CrossValidation/Split.php index 77eab3c..e485ffb 100644 --- a/src/Phpml/CrossValidation/Split.php +++ b/src/Phpml/CrossValidation/Split.php @@ -29,7 +29,7 @@ abstract class Split */ protected $testLabels = []; - public function __construct(Dataset $dataset, float $testSize = 0.3, int $seed = null) + public function __construct(Dataset $dataset, float $testSize = 0.3, ?int $seed = null) { if (0 >= $testSize || 1 <= $testSize) { throw InvalidArgumentException::percentNotInRange('testSize'); @@ -61,7 +61,7 @@ abstract class Split return $this->testLabels; } - protected function seedGenerator(int $seed = null) + protected function seedGenerator(?int $seed = null): void { if (null === $seed) { mt_srand(); diff --git a/src/Phpml/CrossValidation/StratifiedRandomSplit.php b/src/Phpml/CrossValidation/StratifiedRandomSplit.php index 41f5d34..153cb8f 100644 --- a/src/Phpml/CrossValidation/StratifiedRandomSplit.php +++ b/src/Phpml/CrossValidation/StratifiedRandomSplit.php @@ -9,7 +9,7 @@ use Phpml\Dataset\Dataset; class StratifiedRandomSplit extends RandomSplit { - protected function splitDataset(Dataset $dataset, float $testSize) + protected function splitDataset(Dataset $dataset, float $testSize): void { $datasets = $this->splitByTarget($dataset); diff --git a/src/Phpml/Dataset/FilesDataset.php b/src/Phpml/Dataset/FilesDataset.php index 73bc4b0..ca04a3e 100644 --- a/src/Phpml/Dataset/FilesDataset.php +++ b/src/Phpml/Dataset/FilesDataset.php @@ -17,14 +17,14 @@ class FilesDataset extends ArrayDataset $this->scanRootPath($rootPath); } - private function scanRootPath(string $rootPath) + private function scanRootPath(string $rootPath): void { foreach (glob($rootPath.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR) as $dir) { $this->scanDir($dir); } } - private function scanDir(string $dir) + private function scanDir(string $dir): void { $target = basename($dir); diff --git a/src/Phpml/DimensionReduction/EigenTransformerBase.php b/src/Phpml/DimensionReduction/EigenTransformerBase.php index df18d11..a6352ba 100644 --- a/src/Phpml/DimensionReduction/EigenTransformerBase.php +++ b/src/Phpml/DimensionReduction/EigenTransformerBase.php @@ -48,7 +48,7 @@ abstract class EigenTransformerBase * top eigenVectors along with the largest eigenValues. The total explained variance * of these eigenVectors will be no less than desired $totalVariance value */ - protected function eigenDecomposition(array $matrix) + protected function eigenDecomposition(array $matrix): void { $eig = new EigenvalueDecomposition($matrix); $eigVals = $eig->getRealEigenvalues(); diff --git a/src/Phpml/DimensionReduction/KernelPCA.php b/src/Phpml/DimensionReduction/KernelPCA.php index 1c7cecb..d11e1a6 100644 --- a/src/Phpml/DimensionReduction/KernelPCA.php +++ b/src/Phpml/DimensionReduction/KernelPCA.php @@ -10,10 +10,10 @@ use Phpml\Math\Matrix; class KernelPCA extends PCA { - const KERNEL_RBF = 1; - const KERNEL_SIGMOID = 2; - const KERNEL_LAPLACIAN = 3; - const KERNEL_LINEAR = 4; + public const KERNEL_RBF = 1; + public const KERNEL_SIGMOID = 2; + public const KERNEL_LAPLACIAN = 3; + public const KERNEL_LINEAR = 4; /** * Selected kernel function @@ -50,7 +50,7 @@ class KernelPCA extends PCA * * @throws \Exception */ - public function __construct(int $kernel = self::KERNEL_RBF, float $totalVariance = null, int $numFeatures = null, float $gamma = null) + public function __construct(int $kernel = self::KERNEL_RBF, ?float $totalVariance = null, ?int $numFeatures = null, ?float $gamma = null) { $availableKernels = [self::KERNEL_RBF, self::KERNEL_SIGMOID, self::KERNEL_LAPLACIAN, self::KERNEL_LINEAR]; if (!in_array($kernel, $availableKernels)) { diff --git a/src/Phpml/DimensionReduction/LDA.php b/src/Phpml/DimensionReduction/LDA.php index 8a94f46..26b2324 100644 --- a/src/Phpml/DimensionReduction/LDA.php +++ b/src/Phpml/DimensionReduction/LDA.php @@ -47,7 +47,7 @@ class LDA extends EigenTransformerBase * * @throws \Exception */ - public function __construct(float $totalVariance = null, int $numFeatures = null) + public function __construct(?float $totalVariance = null, ?int $numFeatures = null) { if ($totalVariance !== null && ($totalVariance < 0.1 || $totalVariance > 0.99)) { throw new \Exception('Total variance can be a value between 0.1 and 0.99'); diff --git a/src/Phpml/DimensionReduction/PCA.php b/src/Phpml/DimensionReduction/PCA.php index f5cb219..25b7186 100644 --- a/src/Phpml/DimensionReduction/PCA.php +++ b/src/Phpml/DimensionReduction/PCA.php @@ -32,7 +32,7 @@ class PCA extends EigenTransformerBase * * @throws \Exception */ - public function __construct(float $totalVariance = null, int $numFeatures = null) + public function __construct(?float $totalVariance = null, ?int $numFeatures = null) { if ($totalVariance !== null && ($totalVariance < 0.1 || $totalVariance > 0.99)) { throw new \Exception('Total variance can be a value between 0.1 and 0.99'); @@ -73,7 +73,7 @@ class PCA extends EigenTransformerBase return $this->reduce($data); } - protected function calculateMeans(array $data, int $n) + protected function calculateMeans(array $data, int $n): void { // Calculate means for each dimension $this->means = []; diff --git a/src/Phpml/FeatureExtraction/TfIdfTransformer.php b/src/Phpml/FeatureExtraction/TfIdfTransformer.php index c5e1e59..6efd90f 100644 --- a/src/Phpml/FeatureExtraction/TfIdfTransformer.php +++ b/src/Phpml/FeatureExtraction/TfIdfTransformer.php @@ -13,14 +13,14 @@ class TfIdfTransformer implements Transformer */ private $idf; - public function __construct(array $samples = null) + public function __construct(?array $samples = null) { if ($samples) { $this->fit($samples); } } - public function fit(array $samples) + public function fit(array $samples): void { $this->countTokensFrequency($samples); @@ -30,7 +30,7 @@ class TfIdfTransformer implements Transformer } } - public function transform(array &$samples) + public function transform(array &$samples): void { foreach ($samples as &$sample) { foreach ($sample as $index => &$feature) { @@ -39,7 +39,7 @@ class TfIdfTransformer implements Transformer } } - private function countTokensFrequency(array $samples) + private function countTokensFrequency(array $samples): void { $this->idf = array_fill_keys(array_keys($samples[0]), 0); diff --git a/src/Phpml/FeatureExtraction/TokenCountVectorizer.php b/src/Phpml/FeatureExtraction/TokenCountVectorizer.php index eb7a4ac..e00fc69 100644 --- a/src/Phpml/FeatureExtraction/TokenCountVectorizer.php +++ b/src/Phpml/FeatureExtraction/TokenCountVectorizer.php @@ -34,7 +34,7 @@ class TokenCountVectorizer implements Transformer */ private $frequencies; - public function __construct(Tokenizer $tokenizer, StopWords $stopWords = null, float $minDF = 0.0) + public function __construct(Tokenizer $tokenizer, ?StopWords $stopWords = null, float $minDF = 0.0) { $this->tokenizer = $tokenizer; $this->stopWords = $stopWords; @@ -44,12 +44,12 @@ class TokenCountVectorizer implements Transformer $this->frequencies = []; } - public function fit(array $samples) + public function fit(array $samples): void { $this->buildVocabulary($samples); } - public function transform(array &$samples) + public function transform(array &$samples): void { foreach ($samples as &$sample) { $this->transformSample($sample); @@ -63,7 +63,7 @@ class TokenCountVectorizer implements Transformer return array_flip($this->vocabulary); } - private function buildVocabulary(array &$samples) + private function buildVocabulary(array &$samples): void { foreach ($samples as $index => $sample) { $tokens = $this->tokenizer->tokenize($sample); @@ -73,7 +73,7 @@ class TokenCountVectorizer implements Transformer } } - private function transformSample(string &$sample) + private function transformSample(string &$sample): void { $counts = []; $tokens = $this->tokenizer->tokenize($sample); @@ -113,7 +113,7 @@ class TokenCountVectorizer implements Transformer return $this->vocabulary[$token] ?? false; } - private function addTokenToVocabulary(string $token) + private function addTokenToVocabulary(string $token): void { if ($this->isStopWord($token)) { return; @@ -129,7 +129,7 @@ class TokenCountVectorizer implements Transformer return $this->stopWords && $this->stopWords->isStopWord($token); } - private function updateFrequency(string $token) + private function updateFrequency(string $token): void { if (!isset($this->frequencies[$token])) { $this->frequencies[$token] = 0; @@ -138,7 +138,7 @@ class TokenCountVectorizer implements Transformer ++$this->frequencies[$token]; } - private function checkDocumentFrequency(array &$samples) + private function checkDocumentFrequency(array &$samples): void { if ($this->minDF > 0) { $beyondMinimum = $this->getBeyondMinimumIndexes(count($samples)); @@ -148,7 +148,7 @@ class TokenCountVectorizer implements Transformer } } - private function resetBeyondMinimum(array &$sample, array $beyondMinimum) + private function resetBeyondMinimum(array &$sample, array $beyondMinimum): void { foreach ($beyondMinimum as $index) { $sample[$index] = 0; diff --git a/src/Phpml/Helper/OneVsRest.php b/src/Phpml/Helper/OneVsRest.php index 5ae126c..15d62d8 100644 --- a/src/Phpml/Helper/OneVsRest.php +++ b/src/Phpml/Helper/OneVsRest.php @@ -28,7 +28,7 @@ trait OneVsRest /** * Train a binary classifier in the OvR style */ - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { // Clears previous stuff. $this->reset(); @@ -36,7 +36,7 @@ trait OneVsRest $this->trainBylabel($samples, $targets); } - protected function trainByLabel(array $samples, array $targets, array $allLabels = []) + protected function trainByLabel(array $samples, array $targets, array $allLabels = []): void { // Overwrites the current value if it exist. $allLabels must be provided for each partialTrain run. if (!empty($allLabels)) { @@ -63,7 +63,7 @@ trait OneVsRest $this->classifiers[$label] = $this->getClassifierCopy(); } - list($binarizedTargets, $classifierLabels) = $this->binarizeTargets($targets, $label); + [$binarizedTargets, $classifierLabels] = $this->binarizeTargets($targets, $label); $this->classifiers[$label]->trainBinary($samples, $binarizedTargets, $classifierLabels); } } @@ -80,7 +80,7 @@ trait OneVsRest /** * Resets the classifier and the vars internally used by OneVsRest to create multiple classifiers. */ - public function reset() + public function reset(): void { $this->classifiers = []; $this->allLabels = []; @@ -158,7 +158,7 @@ trait OneVsRest * * @return void */ - abstract protected function resetBinary(); + abstract protected function resetBinary(): void; /** * Each classifier that make use of OvR approach should be able to diff --git a/src/Phpml/Helper/Optimizer/ConjugateGradient.php b/src/Phpml/Helper/Optimizer/ConjugateGradient.php index 7333b9a..c119eae 100644 --- a/src/Phpml/Helper/Optimizer/ConjugateGradient.php +++ b/src/Phpml/Helper/Optimizer/ConjugateGradient.php @@ -61,7 +61,7 @@ class ConjugateGradient extends GD */ protected function gradient(array $theta) : array { - list(, $gradient) = parent::gradient($theta); + [, $gradient] = parent::gradient($theta); return $gradient; } @@ -71,7 +71,7 @@ class ConjugateGradient extends GD */ protected function cost(array $theta) : float { - list($cost) = parent::gradient($theta); + [$cost] = parent::gradient($theta); return array_sum($cost) / $this->sampleCount; } diff --git a/src/Phpml/Helper/Optimizer/GD.php b/src/Phpml/Helper/Optimizer/GD.php index ae3c6e2..38b4253 100644 --- a/src/Phpml/Helper/Optimizer/GD.php +++ b/src/Phpml/Helper/Optimizer/GD.php @@ -31,7 +31,7 @@ class GD extends StochasticGD $theta = $this->theta; // Calculate update terms for each sample - list($errors, $updates, $totalPenalty) = $this->gradient($theta); + [$errors, $updates, $totalPenalty] = $this->gradient($theta); $this->updateWeightsWithUpdates($updates, $totalPenalty); @@ -61,7 +61,7 @@ class GD extends StochasticGD $target = $this->targets[$index]; $result = ($this->gradientCb)($theta, $sample, $target); - list($cost, $grad, $penalty) = array_pad($result, 3, 0); + [$cost, $grad, $penalty] = array_pad($result, 3, 0); $costs[] = $cost; $gradient[] = $grad; @@ -73,7 +73,7 @@ class GD extends StochasticGD return [$costs, $gradient, $totalPenalty]; } - protected function updateWeightsWithUpdates(array $updates, float $penalty) + protected function updateWeightsWithUpdates(array $updates, float $penalty): void { // Updates all weights at once for ($i = 0; $i <= $this->dimensions; ++$i) { @@ -96,7 +96,7 @@ class GD extends StochasticGD /** * Clears the optimizer internal vars after the optimization process. */ - protected function clear() + protected function clear(): void { $this->sampleCount = null; parent::clear(); diff --git a/src/Phpml/Helper/Optimizer/StochasticGD.php b/src/Phpml/Helper/Optimizer/StochasticGD.php index 0a622d4..f1b0979 100644 --- a/src/Phpml/Helper/Optimizer/StochasticGD.php +++ b/src/Phpml/Helper/Optimizer/StochasticGD.php @@ -191,7 +191,7 @@ class StochasticGD extends Optimizer $result = ($this->gradientCb)($theta, $sample, $target); - list($error, $gradient, $penalty) = array_pad($result, 3, 0); + [$error, $gradient, $penalty] = array_pad($result, 3, 0); // Update bias $this->theta[0] -= $this->learningRate * $gradient; @@ -249,7 +249,7 @@ class StochasticGD extends Optimizer /** * Clears the optimizer internal vars after the optimization process. */ - protected function clear() + protected function clear(): void { $this->samples = []; $this->targets = []; diff --git a/src/Phpml/Helper/Trainable.php b/src/Phpml/Helper/Trainable.php index 3d011ac..86ffaf1 100644 --- a/src/Phpml/Helper/Trainable.php +++ b/src/Phpml/Helper/Trainable.php @@ -20,7 +20,7 @@ trait Trainable * @param array $samples * @param array $targets */ - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); diff --git a/src/Phpml/Math/LinearAlgebra/EigenvalueDecomposition.php b/src/Phpml/Math/LinearAlgebra/EigenvalueDecomposition.php index b76ddb9..6261d26 100644 --- a/src/Phpml/Math/LinearAlgebra/EigenvalueDecomposition.php +++ b/src/Phpml/Math/LinearAlgebra/EigenvalueDecomposition.php @@ -119,7 +119,7 @@ class EigenvalueDecomposition /** * Symmetric Householder reduction to tridiagonal form. */ - private function tred2() + private function tred2(): void { // This is derived from the Algol procedures tred2 by // Bowdler, Martin, Reinsch, and Wilkinson, Handbook for @@ -236,7 +236,7 @@ class EigenvalueDecomposition * Auto. Comp., Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. */ - private function tql2() + private function tql2(): void { for ($i = 1; $i < $this->n; ++$i) { $this->e[$i - 1] = $this->e[$i]; @@ -343,7 +343,7 @@ class EigenvalueDecomposition * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutines in EISPACK. */ - private function orthes() + private function orthes(): void { $low = 0; $high = $this->n - 1; @@ -428,7 +428,7 @@ class EigenvalueDecomposition * @param int|float $yr * @param int|float $yi */ - private function cdiv($xr, $xi, $yr, $yi) + private function cdiv($xr, $xi, $yr, $yi): void { if (abs($yr) > abs($yi)) { $r = $yi / $yr; @@ -451,7 +451,7 @@ class EigenvalueDecomposition * Vol.ii-Linear Algebra, and the corresponding * Fortran subroutine in EISPACK. */ - private function hqr2() + private function hqr2(): void { // Initialize $nn = $this->n; diff --git a/src/Phpml/Math/Statistic/Covariance.php b/src/Phpml/Math/Statistic/Covariance.php index 2c72e6c..627a8a6 100644 --- a/src/Phpml/Math/Statistic/Covariance.php +++ b/src/Phpml/Math/Statistic/Covariance.php @@ -13,7 +13,7 @@ class Covariance * * @throws InvalidArgumentException */ - public static function fromXYArrays(array $x, array $y, bool $sample = true, float $meanX = null, float $meanY = null) : float + public static function fromXYArrays(array $x, array $y, bool $sample = true, ?float $meanX = null, ?float $meanY = null) : float { if (empty($x) || empty($y)) { throw InvalidArgumentException::arrayCantBeEmpty(); @@ -51,7 +51,7 @@ class Covariance * @throws InvalidArgumentException * @throws \Exception */ - public static function fromDataset(array $data, int $i, int $k, bool $sample = true, float $meanX = null, float $meanY = null) : float + public static function fromDataset(array $data, int $i, int $k, bool $sample = true, ?float $meanX = null, ?float $meanY = null) : float { if (empty($data)) { throw InvalidArgumentException::arrayCantBeEmpty(); @@ -112,7 +112,7 @@ class Covariance * * @param array|null $means */ - public static function covarianceMatrix(array $data, array $means = null) : array + public static function covarianceMatrix(array $data, ?array $means = null) : array { $n = count($data[0]); diff --git a/src/Phpml/Math/Statistic/Mean.php b/src/Phpml/Math/Statistic/Mean.php index 50b3788..eb1baef 100644 --- a/src/Phpml/Math/Statistic/Mean.php +++ b/src/Phpml/Math/Statistic/Mean.php @@ -56,7 +56,7 @@ class Mean /** * @throws InvalidArgumentException */ - private static function checkArrayLength(array $array) + private static function checkArrayLength(array $array): void { if (empty($array)) { throw InvalidArgumentException::arrayCantBeEmpty(); diff --git a/src/Phpml/Metric/ClassificationReport.php b/src/Phpml/Metric/ClassificationReport.php index f4fdaee..ae4c11a 100644 --- a/src/Phpml/Metric/ClassificationReport.php +++ b/src/Phpml/Metric/ClassificationReport.php @@ -76,7 +76,7 @@ class ClassificationReport return $this->average; } - private function computeMetrics(array $truePositive, array $falsePositive, array $falseNegative) + private function computeMetrics(array $truePositive, array $falsePositive, array $falseNegative): void { foreach ($truePositive as $label => $tp) { $this->precision[$label] = $this->computePrecision($tp, $falsePositive[$label]); @@ -85,7 +85,7 @@ class ClassificationReport } } - private function computeAverage() + private function computeAverage(): void { foreach (['precision', 'recall', 'f1score'] as $metric) { $values = array_filter($this->{$metric}); diff --git a/src/Phpml/Metric/ConfusionMatrix.php b/src/Phpml/Metric/ConfusionMatrix.php index 5c7bc0b..0f0b738 100644 --- a/src/Phpml/Metric/ConfusionMatrix.php +++ b/src/Phpml/Metric/ConfusionMatrix.php @@ -6,7 +6,7 @@ namespace Phpml\Metric; class ConfusionMatrix { - public static function compute(array $actualLabels, array $predictedLabels, array $labels = null) : array + public static function compute(array $actualLabels, array $predictedLabels, ?array $labels = null) : array { $labels = $labels ? array_flip($labels) : self::getUniqueLabels($actualLabels); $matrix = self::generateMatrixWithZeros($labels); diff --git a/src/Phpml/ModelManager.php b/src/Phpml/ModelManager.php index 28594be..2fa14f5 100644 --- a/src/Phpml/ModelManager.php +++ b/src/Phpml/ModelManager.php @@ -9,7 +9,7 @@ use Phpml\Exception\SerializeException; class ModelManager { - public function saveToFile(Estimator $estimator, string $filepath) + public function saveToFile(Estimator $estimator, string $filepath): void { if (!is_writable(dirname($filepath))) { throw FileException::cantSaveFile(basename($filepath)); diff --git a/src/Phpml/NeuralNetwork/Layer.php b/src/Phpml/NeuralNetwork/Layer.php index 524bf35..c70bdb3 100644 --- a/src/Phpml/NeuralNetwork/Layer.php +++ b/src/Phpml/NeuralNetwork/Layer.php @@ -17,7 +17,7 @@ class Layer /** * @throws InvalidArgumentException */ - public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ActivationFunction $activationFunction = null) + public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ?ActivationFunction $activationFunction = null) { if (!in_array(Node::class, class_implements($nodeClass))) { throw InvalidArgumentException::invalidLayerNodeClass(); @@ -33,7 +33,7 @@ class Layer * * @return Neuron */ - private function createNode(string $nodeClass, ActivationFunction $activationFunction = null) + private function createNode(string $nodeClass, ?ActivationFunction $activationFunction = null) { if (Neuron::class == $nodeClass) { return new Neuron($activationFunction); @@ -42,7 +42,7 @@ class Layer return new $nodeClass(); } - public function addNode(Node $node) + public function addNode(Node $node): void { $this->nodes[] = $node; } diff --git a/src/Phpml/NeuralNetwork/Network/LayeredNetwork.php b/src/Phpml/NeuralNetwork/Network/LayeredNetwork.php index 1234c41..3baa5ac 100644 --- a/src/Phpml/NeuralNetwork/Network/LayeredNetwork.php +++ b/src/Phpml/NeuralNetwork/Network/LayeredNetwork.php @@ -16,7 +16,7 @@ abstract class LayeredNetwork implements Network */ protected $layers; - public function addLayer(Layer $layer) + public function addLayer(Layer $layer): void { $this->layers[] = $layer; } @@ -29,7 +29,7 @@ abstract class LayeredNetwork implements Network return $this->layers; } - public function removeLayers() + public function removeLayers(): void { unset($this->layers); } diff --git a/src/Phpml/NeuralNetwork/Network/MultilayerPerceptron.php b/src/Phpml/NeuralNetwork/Network/MultilayerPerceptron.php index 530fbef..9ef3f73 100644 --- a/src/Phpml/NeuralNetwork/Network/MultilayerPerceptron.php +++ b/src/Phpml/NeuralNetwork/Network/MultilayerPerceptron.php @@ -58,7 +58,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, /** * @throws InvalidArgumentException */ - public function __construct(int $inputLayerFeatures, array $hiddenLayers, array $classes, int $iterations = 10000, ActivationFunction $activationFunction = null, int $theta = 1) + public function __construct(int $inputLayerFeatures, array $hiddenLayers, array $classes, int $iterations = 10000, ?ActivationFunction $activationFunction = null, int $theta = 1) { if (empty($hiddenLayers)) { throw InvalidArgumentException::invalidLayersNumber(); @@ -78,7 +78,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, $this->initNetwork(); } - private function initNetwork() + private function initNetwork(): void { $this->addInputLayer($this->inputLayerFeatures); $this->addNeuronLayers($this->hiddenLayers, $this->activationFunction); @@ -90,7 +90,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, $this->backpropagation = new Backpropagation($this->theta); } - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->reset(); $this->initNetwork(); @@ -100,7 +100,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, /** * @throws InvalidArgumentException */ - public function partialTrain(array $samples, array $targets, array $classes = []) + public function partialTrain(array $samples, array $targets, array $classes = []): void { if (!empty($classes) && array_values($classes) !== $this->classes) { // We require the list of classes in the constructor. @@ -122,24 +122,24 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, */ abstract protected function predictSample(array $sample); - protected function reset() + protected function reset(): void { $this->removeLayers(); } - private function addInputLayer(int $nodes) + private function addInputLayer(int $nodes): void { $this->addLayer(new Layer($nodes, Input::class)); } - private function addNeuronLayers(array $layers, ActivationFunction $activationFunction = null) + private function addNeuronLayers(array $layers, ?ActivationFunction $activationFunction = null): void { foreach ($layers as $neurons) { $this->addLayer(new Layer($neurons, Neuron::class, $activationFunction)); } } - private function generateSynapses() + private function generateSynapses(): void { $layersNumber = count($this->layers) - 1; for ($i = 0; $i < $layersNumber; ++$i) { @@ -149,7 +149,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, } } - private function addBiasNodes() + private function addBiasNodes(): void { $biasLayers = count($this->layers) - 1; for ($i = 0; $i < $biasLayers; ++$i) { @@ -157,7 +157,7 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, } } - private function generateLayerSynapses(Layer $nextLayer, Layer $currentLayer) + private function generateLayerSynapses(Layer $nextLayer, Layer $currentLayer): void { foreach ($nextLayer->getNodes() as $nextNeuron) { if ($nextNeuron instanceof Neuron) { @@ -166,14 +166,14 @@ abstract class MultilayerPerceptron extends LayeredNetwork implements Estimator, } } - private function generateNeuronSynapses(Layer $currentLayer, Neuron $nextNeuron) + private function generateNeuronSynapses(Layer $currentLayer, Neuron $nextNeuron): void { foreach ($currentLayer->getNodes() as $currentNeuron) { $nextNeuron->addSynapse(new Synapse($currentNeuron)); } } - private function trainSamples(array $samples, array $targets) + private function trainSamples(array $samples, array $targets): void { foreach ($targets as $key => $target) { $this->trainSample($samples[$key], $target); diff --git a/src/Phpml/NeuralNetwork/Node/Input.php b/src/Phpml/NeuralNetwork/Node/Input.php index 569b303..8ff78ea 100644 --- a/src/Phpml/NeuralNetwork/Node/Input.php +++ b/src/Phpml/NeuralNetwork/Node/Input.php @@ -23,7 +23,7 @@ class Input implements Node return $this->input; } - public function setInput(float $input) + public function setInput(float $input): void { $this->input = $input; } diff --git a/src/Phpml/NeuralNetwork/Node/Neuron.php b/src/Phpml/NeuralNetwork/Node/Neuron.php index 520c3b2..096d54f 100644 --- a/src/Phpml/NeuralNetwork/Node/Neuron.php +++ b/src/Phpml/NeuralNetwork/Node/Neuron.php @@ -25,14 +25,14 @@ class Neuron implements Node */ protected $output; - public function __construct(ActivationFunction $activationFunction = null) + public function __construct(?ActivationFunction $activationFunction = null) { $this->activationFunction = $activationFunction ?: new ActivationFunction\Sigmoid(); $this->synapses = []; $this->output = 0; } - public function addSynapse(Synapse $synapse) + public function addSynapse(Synapse $synapse): void { $this->synapses[] = $synapse; } @@ -59,7 +59,7 @@ class Neuron implements Node return $this->output; } - public function reset() + public function reset(): void { $this->output = 0; } diff --git a/src/Phpml/NeuralNetwork/Node/Neuron/Synapse.php b/src/Phpml/NeuralNetwork/Node/Neuron/Synapse.php index adb4b02..0883f4e 100644 --- a/src/Phpml/NeuralNetwork/Node/Neuron/Synapse.php +++ b/src/Phpml/NeuralNetwork/Node/Neuron/Synapse.php @@ -21,7 +21,7 @@ class Synapse /** * @param float|null $weight */ - public function __construct(Node $node, float $weight = null) + public function __construct(Node $node, ?float $weight = null) { $this->node = $node; $this->weight = $weight ?: $this->generateRandomWeight(); @@ -37,7 +37,7 @@ class Synapse return $this->weight * $this->node->getOutput(); } - public function changeWeight(float $delta) + public function changeWeight(float $delta): void { $this->weight += $delta; } diff --git a/src/Phpml/NeuralNetwork/Training/Backpropagation.php b/src/Phpml/NeuralNetwork/Training/Backpropagation.php index b113454..98683ab 100644 --- a/src/Phpml/NeuralNetwork/Training/Backpropagation.php +++ b/src/Phpml/NeuralNetwork/Training/Backpropagation.php @@ -32,7 +32,7 @@ class Backpropagation /** * @param mixed $targetClass */ - public function backpropagate(array $layers, $targetClass) + public function backpropagate(array $layers, $targetClass): void { $layersNumber = count($layers); diff --git a/src/Phpml/Pipeline.php b/src/Phpml/Pipeline.php index a49fb27..a72e634 100644 --- a/src/Phpml/Pipeline.php +++ b/src/Phpml/Pipeline.php @@ -28,12 +28,12 @@ class Pipeline implements Estimator $this->estimator = $estimator; } - public function addTransformer(Transformer $transformer) + public function addTransformer(Transformer $transformer): void { $this->transformers[] = $transformer; } - public function setEstimator(Estimator $estimator) + public function setEstimator(Estimator $estimator): void { $this->estimator = $estimator; } @@ -51,7 +51,7 @@ class Pipeline implements Estimator return $this->estimator; } - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { foreach ($this->transformers as $transformer) { $transformer->fit($samples); @@ -71,7 +71,7 @@ class Pipeline implements Estimator return $this->estimator->predict($samples); } - private function transformSamples(array &$samples) + private function transformSamples(array &$samples): void { foreach ($this->transformers as $transformer) { $transformer->transform($samples); diff --git a/src/Phpml/Preprocessing/Imputer.php b/src/Phpml/Preprocessing/Imputer.php index cc90c46..d2dbfcd 100644 --- a/src/Phpml/Preprocessing/Imputer.php +++ b/src/Phpml/Preprocessing/Imputer.php @@ -8,8 +8,8 @@ use Phpml\Preprocessing\Imputer\Strategy; class Imputer implements Preprocessor { - const AXIS_COLUMN = 0; - const AXIS_ROW = 1; + public const AXIS_COLUMN = 0; + public const AXIS_ROW = 1; /** * @var mixed @@ -43,19 +43,19 @@ class Imputer implements Preprocessor $this->samples = $samples; } - public function fit(array $samples) + public function fit(array $samples): void { $this->samples = $samples; } - public function transform(array &$samples) + public function transform(array &$samples): void { foreach ($samples as &$sample) { $this->preprocessSample($sample); } } - private function preprocessSample(array &$sample) + private function preprocessSample(array &$sample): void { foreach ($sample as $column => &$value) { if ($value === $this->missingValue) { diff --git a/src/Phpml/Preprocessing/Normalizer.php b/src/Phpml/Preprocessing/Normalizer.php index 07777f9..f038345 100644 --- a/src/Phpml/Preprocessing/Normalizer.php +++ b/src/Phpml/Preprocessing/Normalizer.php @@ -10,9 +10,9 @@ use Phpml\Math\Statistic\StandardDeviation; class Normalizer implements Preprocessor { - const NORM_L1 = 1; - const NORM_L2 = 2; - const NORM_STD = 3; + public const NORM_L1 = 1; + public const NORM_L2 = 2; + public const NORM_STD = 3; /** * @var int @@ -46,7 +46,7 @@ class Normalizer implements Preprocessor $this->norm = $norm; } - public function fit(array $samples) + public function fit(array $samples): void { if ($this->fitted) { return; @@ -64,7 +64,7 @@ class Normalizer implements Preprocessor $this->fitted = true; } - public function transform(array &$samples) + public function transform(array &$samples): void { $methods = [ self::NORM_L1 => 'normalizeL1', @@ -80,7 +80,7 @@ class Normalizer implements Preprocessor } } - private function normalizeL1(array &$sample) + private function normalizeL1(array &$sample): void { $norm1 = 0; foreach ($sample as $feature) { @@ -97,7 +97,7 @@ class Normalizer implements Preprocessor } } - private function normalizeL2(array &$sample) + private function normalizeL2(array &$sample): void { $norm2 = 0; foreach ($sample as $feature) { @@ -114,7 +114,7 @@ class Normalizer implements Preprocessor } } - private function normalizeSTD(array &$sample) + private function normalizeSTD(array &$sample): void { foreach ($sample as $i => $val) { if ($this->std[$i] != 0) { diff --git a/src/Phpml/Regression/LeastSquares.php b/src/Phpml/Regression/LeastSquares.php index 28602cd..f8adcb2 100644 --- a/src/Phpml/Regression/LeastSquares.php +++ b/src/Phpml/Regression/LeastSquares.php @@ -30,7 +30,7 @@ class LeastSquares implements Regression */ private $coefficients; - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); @@ -64,7 +64,7 @@ class LeastSquares implements Regression /** * coefficient(b) = (X'X)-1X'Y. */ - private function computeCoefficients() + private function computeCoefficients(): void { $samplesMatrix = $this->getSamplesMatrix(); $targetsMatrix = $this->getTargetsMatrix(); diff --git a/src/Phpml/Regression/SVR.php b/src/Phpml/Regression/SVR.php index 54215e0..e3032ac 100644 --- a/src/Phpml/Regression/SVR.php +++ b/src/Phpml/Regression/SVR.php @@ -15,7 +15,7 @@ class SVR extends SupportVectorMachine implements Regression int $degree = 3, float $epsilon = 0.1, float $cost = 1.0, - float $gamma = null, + ?float $gamma = null, float $coef0 = 0.0, float $tolerance = 0.001, int $cacheSize = 100, diff --git a/src/Phpml/SupportVectorMachine/Kernel.php b/src/Phpml/SupportVectorMachine/Kernel.php index 9918a3f..af76e6d 100644 --- a/src/Phpml/SupportVectorMachine/Kernel.php +++ b/src/Phpml/SupportVectorMachine/Kernel.php @@ -9,20 +9,20 @@ abstract class Kernel /** * u'*v. */ - const LINEAR = 0; + public const LINEAR = 0; /** * (gamma*u'*v + coef0)^degree. */ - const POLYNOMIAL = 1; + public const POLYNOMIAL = 1; /** * exp(-gamma*|u-v|^2). */ - const RBF = 2; + public const RBF = 2; /** * tanh(gamma*u'*v + coef0). */ - const SIGMOID = 3; + public const SIGMOID = 3; } diff --git a/src/Phpml/SupportVectorMachine/SupportVectorMachine.php b/src/Phpml/SupportVectorMachine/SupportVectorMachine.php index 6b6c48d..cbee23d 100644 --- a/src/Phpml/SupportVectorMachine/SupportVectorMachine.php +++ b/src/Phpml/SupportVectorMachine/SupportVectorMachine.php @@ -97,7 +97,7 @@ class SupportVectorMachine float $cost = 1.0, float $nu = 0.5, int $degree = 3, - float $gamma = null, + ?float $gamma = null, float $coef0 = 0.0, float $epsilon = 0.1, float $tolerance = 0.001, @@ -124,7 +124,7 @@ class SupportVectorMachine $this->varPath = $rootPath.'var'.DIRECTORY_SEPARATOR; } - public function setBinPath(string $binPath) + public function setBinPath(string $binPath): void { $this->ensureDirectorySeparator($binPath); $this->verifyBinPath($binPath); @@ -132,7 +132,7 @@ class SupportVectorMachine $this->binPath = $binPath; } - public function setVarPath(string $varPath) + public function setVarPath(string $varPath): void { if (!is_writable($varPath)) { throw InvalidArgumentException::pathNotWritable($varPath); @@ -142,7 +142,7 @@ class SupportVectorMachine $this->varPath = $varPath; } - public function train(array $samples, array $targets) + public function train(array $samples, array $targets): void { $this->samples = array_merge($this->samples, $samples); $this->targets = array_merge($this->targets, $targets); @@ -234,14 +234,14 @@ class SupportVectorMachine ); } - private function ensureDirectorySeparator(string &$path) + private function ensureDirectorySeparator(string &$path): void { if (substr($path, -1) !== DIRECTORY_SEPARATOR) { $path .= DIRECTORY_SEPARATOR; } } - private function verifyBinPath(string $path) + private function verifyBinPath(string $path): void { if (!is_dir($path)) { throw InvalidArgumentException::pathNotFound($path); diff --git a/src/Phpml/SupportVectorMachine/Type.php b/src/Phpml/SupportVectorMachine/Type.php index 1b454a5..1dea9df 100644 --- a/src/Phpml/SupportVectorMachine/Type.php +++ b/src/Phpml/SupportVectorMachine/Type.php @@ -9,25 +9,25 @@ abstract class Type /** * classification. */ - const C_SVC = 0; + public const C_SVC = 0; /** * classification. */ - const NU_SVC = 1; + public const NU_SVC = 1; /** * distribution estimation. */ - const ONE_CLASS_SVM = 2; + public const ONE_CLASS_SVM = 2; /** * regression. */ - const EPSILON_SVR = 3; + public const EPSILON_SVR = 3; /** * regression. */ - const NU_SVR = 4; + public const NU_SVR = 4; } diff --git a/tests/Phpml/Association/AprioriTest.php b/tests/Phpml/Association/AprioriTest.php index c715d6f..3b47483 100644 --- a/tests/Phpml/Association/AprioriTest.php +++ b/tests/Phpml/Association/AprioriTest.php @@ -40,7 +40,7 @@ class AprioriTest extends TestCase [2, 4], ]; - public function testGreek() + public function testGreek(): void { $apriori = new Apriori(0.5, 0.5); $apriori->train($this->sampleGreek, []); @@ -49,14 +49,14 @@ class AprioriTest extends TestCase $this->assertEquals('alpha', $apriori->predict([['alpha', 'epsilon'], ['beta', 'theta']])[1][0][0]); } - public function testPowerSet() + public function testPowerSet(): void { $apriori = new Apriori(); $this->assertCount(8, $this->invoke($apriori, 'powerSet', [['a', 'b', 'c']])); } - public function testApriori() + public function testApriori(): void { $apriori = new Apriori(3 / 7); $apriori->train($this->sampleBasket, []); @@ -73,7 +73,7 @@ class AprioriTest extends TestCase $this->assertTrue($this->invoke($apriori, 'contains', [$L[2], [3, 4]])); } - public function testGetRules() + public function testGetRules(): void { $apriori = new Apriori(0.4, 0.8); $apriori->train($this->sampleChars, []); @@ -81,21 +81,21 @@ class AprioriTest extends TestCase $this->assertCount(19, $apriori->getRules()); } - public function testAntecedents() + public function testAntecedents(): void { $apriori = new Apriori(); $this->assertCount(6, $this->invoke($apriori, 'antecedents', [['a', 'b', 'c']])); } - public function testItems() + public function testItems(): void { $apriori = new Apriori(); $apriori->train($this->sampleGreek, []); $this->assertCount(4, $this->invoke($apriori, 'items', [])); } - public function testFrequent() + public function testFrequent(): void { $apriori = new Apriori(0.51); $apriori->train($this->sampleGreek, []); @@ -104,7 +104,7 @@ class AprioriTest extends TestCase $this->assertCount(2, $this->invoke($apriori, 'frequent', [[['alpha'], ['beta']]])); } - public function testCandidates() + public function testCandidates(): void { $apriori = new Apriori(); $apriori->train($this->sampleGreek, []); @@ -115,7 +115,7 @@ class AprioriTest extends TestCase $this->assertCount(3, $this->invoke($apriori, 'candidates', [[['alpha'], ['beta'], ['theta']]])); } - public function testConfidence() + public function testConfidence(): void { $apriori = new Apriori(); $apriori->train($this->sampleGreek, []); @@ -124,7 +124,7 @@ class AprioriTest extends TestCase $this->assertEquals(1, $this->invoke($apriori, 'confidence', [['alpha', 'beta'], ['alpha']])); } - public function testSupport() + public function testSupport(): void { $apriori = new Apriori(); $apriori->train($this->sampleGreek, []); @@ -133,7 +133,7 @@ class AprioriTest extends TestCase $this->assertEquals(0.5, $this->invoke($apriori, 'support', [['epsilon']])); } - public function testFrequency() + public function testFrequency(): void { $apriori = new Apriori(); $apriori->train($this->sampleGreek, []); @@ -142,7 +142,7 @@ class AprioriTest extends TestCase $this->assertEquals(2, $this->invoke($apriori, 'frequency', [['epsilon']])); } - public function testContains() + public function testContains(): void { $apriori = new Apriori(); @@ -151,7 +151,7 @@ class AprioriTest extends TestCase $this->assertFalse($this->invoke($apriori, 'contains', [[['a'], ['b']], ['c']])); } - public function testSubset() + public function testSubset(): void { $apriori = new Apriori(); @@ -160,7 +160,7 @@ class AprioriTest extends TestCase $this->assertFalse($this->invoke($apriori, 'subset', [['a'], ['a', 'b']])); } - public function testEquals() + public function testEquals(): void { $apriori = new Apriori(); @@ -187,7 +187,7 @@ class AprioriTest extends TestCase return $method->invokeArgs($object, $params); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $classifier = new Apriori(0.5, 0.5); $classifier->train($this->sampleGreek, []); diff --git a/tests/Phpml/Classification/DecisionTree/DecisionTreeLeafTest.php b/tests/Phpml/Classification/DecisionTree/DecisionTreeLeafTest.php index 854e4e5..626ed64 100644 --- a/tests/Phpml/Classification/DecisionTree/DecisionTreeLeafTest.php +++ b/tests/Phpml/Classification/DecisionTree/DecisionTreeLeafTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class DecisionTreeLeafTest extends TestCase { - public function testHTMLOutput() + public function testHTMLOutput(): void { $leaf = new DecisionTreeLeaf(); $leaf->value = 1; diff --git a/tests/Phpml/Classification/DecisionTreeTest.php b/tests/Phpml/Classification/DecisionTreeTest.php index f0ebc04..c7d2d2a 100644 --- a/tests/Phpml/Classification/DecisionTreeTest.php +++ b/tests/Phpml/Classification/DecisionTreeTest.php @@ -35,7 +35,7 @@ class DecisionTreeTest extends TestCase private function getData($input) { $targets = array_column($input, 4); - array_walk($input, function (&$v) { + array_walk($input, function (&$v): void { array_splice($v, 4, 1); }); @@ -44,14 +44,14 @@ class DecisionTreeTest extends TestCase public function testPredictSingleSample() { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $classifier = new DecisionTree(5); $classifier->train($data, $targets); $this->assertEquals('Dont_play', $classifier->predict(['sunny', 78, 72, 'false'])); $this->assertEquals('Play', $classifier->predict(['overcast', 60, 60, 'false'])); $this->assertEquals('Dont_play', $classifier->predict(['rain', 60, 60, 'true'])); - list($data, $targets) = $this->getData($this->extraData); + [$data, $targets] = $this->getData($this->extraData); $classifier->train($data, $targets); $this->assertEquals('Dont_play', $classifier->predict(['scorching', 95, 90, 'true'])); $this->assertEquals('Play', $classifier->predict(['overcast', 60, 60, 'false'])); @@ -59,9 +59,9 @@ class DecisionTreeTest extends TestCase return $classifier; } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $classifier = new DecisionTree(5); $classifier->train($data, $targets); @@ -78,9 +78,9 @@ class DecisionTreeTest extends TestCase $this->assertEquals($predicted, $restoredClassifier->predict($testSamples)); } - public function testTreeDepth() + public function testTreeDepth(): void { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $classifier = new DecisionTree(5); $classifier->train($data, $targets); $this->assertTrue(5 >= $classifier->actualDepth); diff --git a/tests/Phpml/Classification/Ensemble/AdaBoostTest.php b/tests/Phpml/Classification/Ensemble/AdaBoostTest.php index 8b8d0db..2cc8090 100644 --- a/tests/Phpml/Classification/Ensemble/AdaBoostTest.php +++ b/tests/Phpml/Classification/Ensemble/AdaBoostTest.php @@ -42,7 +42,7 @@ class AdaBoostTest extends TestCase return $classifier; } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { // Instantinate new Percetron trained for OR problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; diff --git a/tests/Phpml/Classification/Ensemble/BaggingTest.php b/tests/Phpml/Classification/Ensemble/BaggingTest.php index afc358a..5bca8de 100644 --- a/tests/Phpml/Classification/Ensemble/BaggingTest.php +++ b/tests/Phpml/Classification/Ensemble/BaggingTest.php @@ -36,7 +36,7 @@ class BaggingTest extends TestCase public function testPredictSingleSample() { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $classifier = $this->getClassifier(); // Testing with default options $classifier->train($data, $targets); @@ -44,7 +44,7 @@ class BaggingTest extends TestCase $this->assertEquals('Play', $classifier->predict(['overcast', 60, 60, 'false'])); $this->assertEquals('Dont_play', $classifier->predict(['rain', 60, 60, 'true'])); - list($data, $targets) = $this->getData($this->extraData); + [$data, $targets] = $this->getData($this->extraData); $classifier->train($data, $targets); $this->assertEquals('Dont_play', $classifier->predict(['scorching', 95, 90, 'true'])); $this->assertEquals('Play', $classifier->predict(['overcast', 60, 60, 'false'])); @@ -52,9 +52,9 @@ class BaggingTest extends TestCase return $classifier; } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $classifier = $this->getClassifier(5); $classifier->train($data, $targets); @@ -71,9 +71,9 @@ class BaggingTest extends TestCase $this->assertEquals($predicted, $restoredClassifier->predict($testSamples)); } - public function testBaseClassifiers() + public function testBaseClassifiers(): void { - list($data, $targets) = $this->getData($this->data); + [$data, $targets] = $this->getData($this->data); $baseClassifiers = $this->getAvailableBaseClassifiers(); foreach ($baseClassifiers as $base => $params) { @@ -119,7 +119,7 @@ class BaggingTest extends TestCase } shuffle($populated); $targets = array_column($populated, 4); - array_walk($populated, function (&$v) { + array_walk($populated, function (&$v): void { array_splice($v, 4, 1); }); diff --git a/tests/Phpml/Classification/Ensemble/RandomForestTest.php b/tests/Phpml/Classification/Ensemble/RandomForestTest.php index 3ff51e0..e4ca9e5 100644 --- a/tests/Phpml/Classification/Ensemble/RandomForestTest.php +++ b/tests/Phpml/Classification/Ensemble/RandomForestTest.php @@ -23,7 +23,7 @@ class RandomForestTest extends BaggingTest return [DecisionTree::class => ['depth' => 5]]; } - public function testOtherBaseClassifier() + public function testOtherBaseClassifier(): void { try { $classifier = new RandomForest(); diff --git a/tests/Phpml/Classification/KNearestNeighborsTest.php b/tests/Phpml/Classification/KNearestNeighborsTest.php index aeee5ef..7ef6182 100644 --- a/tests/Phpml/Classification/KNearestNeighborsTest.php +++ b/tests/Phpml/Classification/KNearestNeighborsTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class KNearestNeighborsTest extends TestCase { - public function testPredictSingleSampleWithDefaultK() + public function testPredictSingleSampleWithDefaultK(): void { $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $labels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -30,7 +30,7 @@ class KNearestNeighborsTest extends TestCase $this->assertEquals('a', $classifier->predict([3, 10])); } - public function testPredictArrayOfSamples() + public function testPredictArrayOfSamples(): void { $trainSamples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $trainLabels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -45,7 +45,7 @@ class KNearestNeighborsTest extends TestCase $this->assertEquals($testLabels, $predicted); } - public function testPredictArrayOfSamplesUsingChebyshevDistanceMetric() + public function testPredictArrayOfSamplesUsingChebyshevDistanceMetric(): void { $trainSamples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $trainLabels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -60,7 +60,7 @@ class KNearestNeighborsTest extends TestCase $this->assertEquals($testLabels, $predicted); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $trainSamples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $trainLabels = ['a', 'a', 'a', 'b', 'b', 'b']; diff --git a/tests/Phpml/Classification/Linear/AdalineTest.php b/tests/Phpml/Classification/Linear/AdalineTest.php index 5989462..46f1a34 100644 --- a/tests/Phpml/Classification/Linear/AdalineTest.php +++ b/tests/Phpml/Classification/Linear/AdalineTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class AdalineTest extends TestCase { - public function testPredictSingleSample() + public function testPredictSingleSample(): void { // AND problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; @@ -64,7 +64,7 @@ class AdalineTest extends TestCase $this->assertEquals(1, $classifier->predict([3.0, 9.5])); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { // Instantinate new Percetron trained for OR problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; diff --git a/tests/Phpml/Classification/Linear/DecisionStumpTest.php b/tests/Phpml/Classification/Linear/DecisionStumpTest.php index 678544e..fa522ad 100644 --- a/tests/Phpml/Classification/Linear/DecisionStumpTest.php +++ b/tests/Phpml/Classification/Linear/DecisionStumpTest.php @@ -53,7 +53,7 @@ class DecisionStumpTest extends TestCase return $classifier; } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { // Instantinate new Percetron trained for OR problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; diff --git a/tests/Phpml/Classification/Linear/PerceptronTest.php b/tests/Phpml/Classification/Linear/PerceptronTest.php index c01da33..2721067 100644 --- a/tests/Phpml/Classification/Linear/PerceptronTest.php +++ b/tests/Phpml/Classification/Linear/PerceptronTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class PerceptronTest extends TestCase { - public function testPredictSingleSample() + public function testPredictSingleSample(): void { // AND problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1], [0.6, 0.6]]; @@ -67,7 +67,7 @@ class PerceptronTest extends TestCase $this->assertEquals(1, $classifier->predict([3.0, 9.5])); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { // Instantinate new Percetron trained for OR problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; diff --git a/tests/Phpml/Classification/MLPClassifierTest.php b/tests/Phpml/Classification/MLPClassifierTest.php index 1745bc6..9f9c9a9 100644 --- a/tests/Phpml/Classification/MLPClassifierTest.php +++ b/tests/Phpml/Classification/MLPClassifierTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class MLPClassifierTest extends TestCase { - public function testMLPClassifierLayersInitialization() + public function testMLPClassifierLayersInitialization(): void { $mlp = new MLPClassifier(2, [2], [0, 1]); @@ -32,7 +32,7 @@ class MLPClassifierTest extends TestCase $this->assertContainsOnly(Neuron::class, $layers[2]->getNodes()); } - public function testSynapsesGeneration() + public function testSynapsesGeneration(): void { $mlp = new MLPClassifier(2, [2], [0, 1]); $layers = $mlp->getLayers(); @@ -50,7 +50,7 @@ class MLPClassifierTest extends TestCase } } - public function testBackpropagationLearning() + public function testBackpropagationLearning(): void { // Single layer 2 classes. $network = new MLPClassifier(2, [2], ['a', 'b']); @@ -65,7 +65,7 @@ class MLPClassifierTest extends TestCase $this->assertEquals('b', $network->predict([0, 0])); } - public function testBackpropagationTrainingReset() + public function testBackpropagationTrainingReset(): void { // Single layer 2 classes. $network = new MLPClassifier(2, [2], ['a', 'b'], 1000); @@ -86,7 +86,7 @@ class MLPClassifierTest extends TestCase $this->assertEquals('a', $network->predict([0, 1])); } - public function testBackpropagationPartialTraining() + public function testBackpropagationPartialTraining(): void { // Single layer 2 classes. $network = new MLPClassifier(2, [2], ['a', 'b'], 1000); @@ -109,7 +109,7 @@ class MLPClassifierTest extends TestCase $this->assertEquals('b', $network->predict([0, 0])); } - public function testBackpropagationLearningMultilayer() + public function testBackpropagationLearningMultilayer(): void { // Multi-layer 2 classes. $network = new MLPClassifier(5, [3, 2], ['a', 'b']); @@ -124,7 +124,7 @@ class MLPClassifierTest extends TestCase $this->assertEquals('b', $network->predict([0, 0, 0, 0, 0])); } - public function testBackpropagationLearningMulticlass() + public function testBackpropagationLearningMulticlass(): void { // Multi-layer more than 2 classes. $network = new MLPClassifier(5, [3, 2], ['a', 'b', 4]); @@ -140,7 +140,7 @@ class MLPClassifierTest extends TestCase $this->assertEquals(4, $network->predict([0, 0, 0, 0, 0])); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { // Instantinate new Percetron trained for OR problem $samples = [[0, 0], [1, 0], [0, 1], [1, 1]]; @@ -163,7 +163,7 @@ class MLPClassifierTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidLayersNumber() + public function testThrowExceptionOnInvalidLayersNumber(): void { new MLPClassifier(2, [], [0, 1]); } @@ -171,7 +171,7 @@ class MLPClassifierTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidPartialTrainingClasses() + public function testThrowExceptionOnInvalidPartialTrainingClasses(): void { $classifier = new MLPClassifier(2, [2], [0, 1]); $classifier->partialTrain( @@ -184,7 +184,7 @@ class MLPClassifierTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidClassesNumber() + public function testThrowExceptionOnInvalidClassesNumber(): void { new MLPClassifier(2, [2], [0]); } diff --git a/tests/Phpml/Classification/NaiveBayesTest.php b/tests/Phpml/Classification/NaiveBayesTest.php index 82c69eb..5b14f7e 100644 --- a/tests/Phpml/Classification/NaiveBayesTest.php +++ b/tests/Phpml/Classification/NaiveBayesTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class NaiveBayesTest extends TestCase { - public function testPredictSingleSample() + public function testPredictSingleSample(): void { $samples = [[5, 1, 1], [1, 5, 1], [1, 1, 5]]; $labels = ['a', 'b', 'c']; @@ -23,7 +23,7 @@ class NaiveBayesTest extends TestCase $this->assertEquals('c', $classifier->predict([1, 1, 6])); } - public function testPredictArrayOfSamples() + public function testPredictArrayOfSamples(): void { $trainSamples = [[5, 1, 1], [1, 5, 1], [1, 1, 5]]; $trainLabels = ['a', 'b', 'c']; @@ -47,7 +47,7 @@ class NaiveBayesTest extends TestCase $this->assertEquals($testLabels, $classifier->predict($testSamples)); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $trainSamples = [[5, 1, 1], [1, 5, 1], [1, 1, 5]]; $trainLabels = ['a', 'b', 'c']; diff --git a/tests/Phpml/Classification/SVCTest.php b/tests/Phpml/Classification/SVCTest.php index 1b529d0..f734297 100644 --- a/tests/Phpml/Classification/SVCTest.php +++ b/tests/Phpml/Classification/SVCTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class SVCTest extends TestCase { - public function testPredictSingleSampleWithLinearKernel() + public function testPredictSingleSampleWithLinearKernel(): void { $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $labels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -30,7 +30,7 @@ class SVCTest extends TestCase $this->assertEquals('a', $classifier->predict([3, 10])); } - public function testPredictArrayOfSamplesWithLinearKernel() + public function testPredictArrayOfSamplesWithLinearKernel(): void { $trainSamples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $trainLabels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -45,7 +45,7 @@ class SVCTest extends TestCase $this->assertEquals($testLabels, $predictions); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $trainSamples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $trainLabels = ['a', 'a', 'a', 'b', 'b', 'b']; diff --git a/tests/Phpml/Clustering/DBSCANTest.php b/tests/Phpml/Clustering/DBSCANTest.php index a093b20..d8fb0fe 100644 --- a/tests/Phpml/Clustering/DBSCANTest.php +++ b/tests/Phpml/Clustering/DBSCANTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class DBSCANTest extends TestCase { - public function testDBSCANSamplesClustering() + public function testDBSCANSamplesClustering(): void { $samples = [[1, 1], [8, 7], [1, 2], [7, 8], [2, 1], [8, 9]]; $clustered = [ @@ -32,7 +32,7 @@ class DBSCANTest extends TestCase $this->assertEquals($clustered, $dbscan->cluster($samples)); } - public function testDBSCANSamplesClusteringAssociative() + public function testDBSCANSamplesClusteringAssociative(): void { $samples = ['a' => [1, 1], 'b' => [9, 9], 'c' => [1, 2], 'd' => [9, 8], 'e' => [7, 7], 'f' => [8, 7]]; $clustered = [ diff --git a/tests/Phpml/Clustering/FuzzyCMeansTest.php b/tests/Phpml/Clustering/FuzzyCMeansTest.php index 39f2643..5aed678 100644 --- a/tests/Phpml/Clustering/FuzzyCMeansTest.php +++ b/tests/Phpml/Clustering/FuzzyCMeansTest.php @@ -25,7 +25,7 @@ class FuzzyCMeansTest extends TestCase return $fcm; } - public function testMembershipMatrix() + public function testMembershipMatrix(): void { $fcm = $this->testFCMSamplesClustering(); $clusterCount = 2; diff --git a/tests/Phpml/Clustering/KMeansTest.php b/tests/Phpml/Clustering/KMeansTest.php index 43d41ee..e665c9f 100644 --- a/tests/Phpml/Clustering/KMeansTest.php +++ b/tests/Phpml/Clustering/KMeansTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class KMeansTest extends TestCase { - public function testKMeansSamplesClustering() + public function testKMeansSamplesClustering(): void { $samples = [[1, 1], [8, 7], [1, 2], [7, 8], [2, 1], [8, 9]]; @@ -26,7 +26,7 @@ class KMeansTest extends TestCase $this->assertCount(0, $samples); } - public function testKMeansInitializationMethods() + public function testKMeansInitializationMethods(): void { $samples = [ [180, 155], [186, 159], [119, 185], [141, 147], [157, 158], @@ -53,7 +53,7 @@ class KMeansTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidClusterNumber() + public function testThrowExceptionOnInvalidClusterNumber(): void { new KMeans(0); } diff --git a/tests/Phpml/CrossValidation/RandomSplitTest.php b/tests/Phpml/CrossValidation/RandomSplitTest.php index b2717fd..070e36b 100644 --- a/tests/Phpml/CrossValidation/RandomSplitTest.php +++ b/tests/Phpml/CrossValidation/RandomSplitTest.php @@ -13,7 +13,7 @@ class RandomSplitTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnToSmallTestSize() + public function testThrowExceptionOnToSmallTestSize(): void { new RandomSplit(new ArrayDataset([], []), 0); } @@ -21,12 +21,12 @@ class RandomSplitTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnToBigTestSize() + public function testThrowExceptionOnToBigTestSize(): void { new RandomSplit(new ArrayDataset([], []), 1); } - public function testDatasetRandomSplitWithoutSeed() + public function testDatasetRandomSplitWithoutSeed(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4]], @@ -44,7 +44,7 @@ class RandomSplitTest extends TestCase $this->assertCount(3, $randomSplit2->getTrainSamples()); } - public function testDatasetRandomSplitWithSameSeed() + public function testDatasetRandomSplitWithSameSeed(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4], [5], [6], [7], [8]], @@ -62,7 +62,7 @@ class RandomSplitTest extends TestCase $this->assertEquals($randomSplit1->getTrainSamples(), $randomSplit2->getTrainSamples()); } - public function testDatasetRandomSplitWithDifferentSeed() + public function testDatasetRandomSplitWithDifferentSeed(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4], [5], [6], [7], [8]], @@ -78,7 +78,7 @@ class RandomSplitTest extends TestCase $this->assertNotEquals($randomSplit1->getTrainSamples(), $randomSplit2->getTrainSamples()); } - public function testRandomSplitCorrectSampleAndLabelPosition() + public function testRandomSplitCorrectSampleAndLabelPosition(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4]], diff --git a/tests/Phpml/CrossValidation/StratifiedRandomSplitTest.php b/tests/Phpml/CrossValidation/StratifiedRandomSplitTest.php index 57023d3..e953ca7 100644 --- a/tests/Phpml/CrossValidation/StratifiedRandomSplitTest.php +++ b/tests/Phpml/CrossValidation/StratifiedRandomSplitTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class StratifiedRandomSplitTest extends TestCase { - public function testDatasetStratifiedRandomSplitWithEvenDistribution() + public function testDatasetStratifiedRandomSplitWithEvenDistribution(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4], [5], [6], [7], [8]], @@ -28,7 +28,7 @@ class StratifiedRandomSplitTest extends TestCase $this->assertEquals(1, $this->countSamplesByTarget($split->getTestLabels(), 'b')); } - public function testDatasetStratifiedRandomSplitWithEvenDistributionAndNumericTargets() + public function testDatasetStratifiedRandomSplitWithEvenDistributionAndNumericTargets(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4], [5], [6], [7], [8]], diff --git a/tests/Phpml/Dataset/ArrayDatasetTest.php b/tests/Phpml/Dataset/ArrayDatasetTest.php index 0b13b51..41e037b 100644 --- a/tests/Phpml/Dataset/ArrayDatasetTest.php +++ b/tests/Phpml/Dataset/ArrayDatasetTest.php @@ -12,12 +12,12 @@ class ArrayDatasetTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArgumentsSize() + public function testThrowExceptionOnInvalidArgumentsSize(): void { new ArrayDataset([0, 1], [0]); } - public function testArrayDataset() + public function testArrayDataset(): void { $dataset = new ArrayDataset( $samples = [[1], [2], [3], [4]], diff --git a/tests/Phpml/Dataset/CsvDatasetTest.php b/tests/Phpml/Dataset/CsvDatasetTest.php index a3a377e..f5cc851 100644 --- a/tests/Phpml/Dataset/CsvDatasetTest.php +++ b/tests/Phpml/Dataset/CsvDatasetTest.php @@ -12,12 +12,12 @@ class CsvDatasetTest extends TestCase /** * @expectedException \Phpml\Exception\FileException */ - public function testThrowExceptionOnMissingFile() + public function testThrowExceptionOnMissingFile(): void { new CsvDataset('missingFile', 3); } - public function testSampleCsvDatasetWithHeaderRow() + public function testSampleCsvDatasetWithHeaderRow(): void { $filePath = dirname(__FILE__).'/Resources/dataset.csv'; @@ -27,7 +27,7 @@ class CsvDatasetTest extends TestCase $this->assertCount(10, $dataset->getTargets()); } - public function testSampleCsvDatasetWithoutHeaderRow() + public function testSampleCsvDatasetWithoutHeaderRow(): void { $filePath = dirname(__FILE__).'/Resources/dataset.csv'; @@ -37,7 +37,7 @@ class CsvDatasetTest extends TestCase $this->assertCount(11, $dataset->getTargets()); } - public function testLongCsvDataset() + public function testLongCsvDataset(): void { $filePath = dirname(__FILE__).'/Resources/longdataset.csv'; diff --git a/tests/Phpml/Dataset/Demo/GlassDatasetTest.php b/tests/Phpml/Dataset/Demo/GlassDatasetTest.php index 5e3f94c..8feef45 100644 --- a/tests/Phpml/Dataset/Demo/GlassDatasetTest.php +++ b/tests/Phpml/Dataset/Demo/GlassDatasetTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class GlassDatasetTest extends TestCase { - public function testLoadingWineDataset() + public function testLoadingWineDataset(): void { $glass = new GlassDataset(); diff --git a/tests/Phpml/Dataset/Demo/IrisDatasetTest.php b/tests/Phpml/Dataset/Demo/IrisDatasetTest.php index 18ad647..faa48c6 100644 --- a/tests/Phpml/Dataset/Demo/IrisDatasetTest.php +++ b/tests/Phpml/Dataset/Demo/IrisDatasetTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class IrisDatasetTest extends TestCase { - public function testLoadingIrisDataset() + public function testLoadingIrisDataset(): void { $iris = new IrisDataset(); diff --git a/tests/Phpml/Dataset/Demo/WineDatasetTest.php b/tests/Phpml/Dataset/Demo/WineDatasetTest.php index a79ed8c..e0324b4 100644 --- a/tests/Phpml/Dataset/Demo/WineDatasetTest.php +++ b/tests/Phpml/Dataset/Demo/WineDatasetTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class WineDatasetTest extends TestCase { - public function testLoadingWineDataset() + public function testLoadingWineDataset(): void { $wine = new WineDataset(); diff --git a/tests/Phpml/Dataset/FilesDatasetTest.php b/tests/Phpml/Dataset/FilesDatasetTest.php index d12477f..0592d06 100644 --- a/tests/Phpml/Dataset/FilesDatasetTest.php +++ b/tests/Phpml/Dataset/FilesDatasetTest.php @@ -12,12 +12,12 @@ class FilesDatasetTest extends TestCase /** * @expectedException \Phpml\Exception\DatasetException */ - public function testThrowExceptionOnMissingRootFolder() + public function testThrowExceptionOnMissingRootFolder(): void { new FilesDataset('some/not/existed/path'); } - public function testLoadFilesDatasetWithBBCData() + public function testLoadFilesDatasetWithBBCData(): void { $rootPath = dirname(__FILE__).'/Resources/bbc'; diff --git a/tests/Phpml/DimensionReduction/KernelPCATest.php b/tests/Phpml/DimensionReduction/KernelPCATest.php index e586fc8..66b4622 100644 --- a/tests/Phpml/DimensionReduction/KernelPCATest.php +++ b/tests/Phpml/DimensionReduction/KernelPCATest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class KernelPCATest extends TestCase { - public function testKernelPCA() + public function testKernelPCA(): void { // Acceptable error $epsilon = 0.001; @@ -37,7 +37,7 @@ class KernelPCATest extends TestCase // Due to the fact that the sign of values can be flipped // during the calculation of eigenValues, we have to compare // absolute value of the values - array_map(function ($val1, $val2) use ($epsilon) { + array_map(function ($val1, $val2) use ($epsilon): void { $this->assertEquals(abs($val1), abs($val2), '', $epsilon); }, $transformed, $reducedData); diff --git a/tests/Phpml/DimensionReduction/LDATest.php b/tests/Phpml/DimensionReduction/LDATest.php index 4498ea5..19124a0 100644 --- a/tests/Phpml/DimensionReduction/LDATest.php +++ b/tests/Phpml/DimensionReduction/LDATest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class LDATest extends TestCase { - public function testLDA() + public function testLDA(): void { // Acceptable error $epsilon = 0.001; @@ -43,7 +43,7 @@ class LDATest extends TestCase $control = array_merge($control, array_slice($transformed, 0, 3)); $control = array_merge($control, array_slice($transformed, -3)); - $check = function ($row1, $row2) use ($epsilon) { + $check = function ($row1, $row2) use ($epsilon): void { // Due to the fact that the sign of values can be flipped // during the calculation of eigenValues, we have to compare // absolute value of the values diff --git a/tests/Phpml/DimensionReduction/PCATest.php b/tests/Phpml/DimensionReduction/PCATest.php index c26782a..0a60004 100644 --- a/tests/Phpml/DimensionReduction/PCATest.php +++ b/tests/Phpml/DimensionReduction/PCATest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class PCATest extends TestCase { - public function testPCA() + public function testPCA(): void { // Acceptable error $epsilon = 0.001; @@ -39,7 +39,7 @@ class PCATest extends TestCase // Due to the fact that the sign of values can be flipped // during the calculation of eigenValues, we have to compare // absolute value of the values - array_map(function ($val1, $val2) use ($epsilon) { + array_map(function ($val1, $val2) use ($epsilon): void { $this->assertEquals(abs($val1), abs($val2), '', $epsilon); }, $transformed, $reducedData); @@ -49,7 +49,7 @@ class PCATest extends TestCase $newRow = [[$transformed[$i]]]; $newRow2 = $pca->transform($row); - array_map(function ($val1, $val2) use ($epsilon) { + array_map(function ($val1, $val2) use ($epsilon): void { $this->assertEquals(abs($val1), abs($val2), '', $epsilon); }, $newRow, $newRow2); } diff --git a/tests/Phpml/FeatureExtraction/StopWordsTest.php b/tests/Phpml/FeatureExtraction/StopWordsTest.php index 4979860..4b715ef 100644 --- a/tests/Phpml/FeatureExtraction/StopWordsTest.php +++ b/tests/Phpml/FeatureExtraction/StopWordsTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class StopWordsTest extends TestCase { - public function testCustomStopWords() + public function testCustomStopWords(): void { $stopWords = new StopWords(['lorem', 'ipsum', 'dolor']); @@ -25,12 +25,12 @@ class StopWordsTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidLanguage() + public function testThrowExceptionOnInvalidLanguage(): void { StopWords::factory('Lorem'); } - public function testEnglishStopWords() + public function testEnglishStopWords(): void { $stopWords = StopWords::factory('English'); @@ -38,7 +38,7 @@ class StopWordsTest extends TestCase $this->assertFalse($stopWords->isStopWord('strategy')); } - public function testPolishStopWords() + public function testPolishStopWords(): void { $stopWords = StopWords::factory('Polish'); @@ -46,7 +46,7 @@ class StopWordsTest extends TestCase $this->assertFalse($stopWords->isStopWord('transhumanizm')); } - public function testFrenchStopWords() + public function testFrenchStopWords(): void { $stopWords = StopWords::factory('French'); diff --git a/tests/Phpml/FeatureExtraction/TfIdfTransformerTest.php b/tests/Phpml/FeatureExtraction/TfIdfTransformerTest.php index 90aa107..0e1adbc 100644 --- a/tests/Phpml/FeatureExtraction/TfIdfTransformerTest.php +++ b/tests/Phpml/FeatureExtraction/TfIdfTransformerTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class TfIdfTransformerTest extends TestCase { - public function testTfIdfTransformation() + public function testTfIdfTransformation(): void { // https://en.wikipedia.org/wiki/Tf-idf diff --git a/tests/Phpml/FeatureExtraction/TokenCountVectorizerTest.php b/tests/Phpml/FeatureExtraction/TokenCountVectorizerTest.php index a25d5a5..3419a29 100644 --- a/tests/Phpml/FeatureExtraction/TokenCountVectorizerTest.php +++ b/tests/Phpml/FeatureExtraction/TokenCountVectorizerTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class TokenCountVectorizerTest extends TestCase { - public function testTransformationWithWhitespaceTokenizer() + public function testTransformationWithWhitespaceTokenizer(): void { $samples = [ 'Lorem ipsum dolor sit amet dolor', @@ -47,7 +47,7 @@ class TokenCountVectorizerTest extends TestCase $this->assertSame($tokensCounts, $samples); } - public function testTransformationWithMinimumDocumentTokenCountFrequency() + public function testTransformationWithMinimumDocumentTokenCountFrequency(): void { // word at least in half samples $samples = [ @@ -100,7 +100,7 @@ class TokenCountVectorizerTest extends TestCase $this->assertSame($tokensCounts, $samples); } - public function testTransformationWithStopWords() + public function testTransformationWithStopWords(): void { $samples = [ 'Lorem ipsum dolor sit amet dolor', diff --git a/tests/Phpml/Math/ComparisonTest.php b/tests/Phpml/Math/ComparisonTest.php index 8fff3cb..d31b1ae 100644 --- a/tests/Phpml/Math/ComparisonTest.php +++ b/tests/Phpml/Math/ComparisonTest.php @@ -15,7 +15,7 @@ class ComparisonTest extends TestCase * * @dataProvider provideData */ - public function testResult($a, $b, string $operator, bool $expected) + public function testResult($a, $b, string $operator, bool $expected): void { $result = Comparison::compare($a, $b, $operator); @@ -26,7 +26,7 @@ class ComparisonTest extends TestCase * @expectedException \Phpml\Exception\InvalidArgumentException * @expectedExceptionMessage Invalid operator "~=" provided */ - public function testThrowExceptionWhenOperatorIsInvalid() + public function testThrowExceptionWhenOperatorIsInvalid(): void { Comparison::compare(1, 1, '~='); } diff --git a/tests/Phpml/Math/Distance/ChebyshevTest.php b/tests/Phpml/Math/Distance/ChebyshevTest.php index 8806c74..893c000 100644 --- a/tests/Phpml/Math/Distance/ChebyshevTest.php +++ b/tests/Phpml/Math/Distance/ChebyshevTest.php @@ -14,7 +14,7 @@ class ChebyshevTest extends TestCase */ private $distanceMetric; - public function setUp() + public function setUp(): void { $this->distanceMetric = new Chebyshev(); } @@ -22,7 +22,7 @@ class ChebyshevTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArguments() + public function testThrowExceptionOnInvalidArguments(): void { $a = [0, 1, 2]; $b = [0, 2]; @@ -30,7 +30,7 @@ class ChebyshevTest extends TestCase $this->distanceMetric->distance($a, $b); } - public function testCalculateDistanceForOneDimension() + public function testCalculateDistanceForOneDimension(): void { $a = [4]; $b = [2]; @@ -41,7 +41,7 @@ class ChebyshevTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForTwoDimensions() + public function testCalculateDistanceForTwoDimensions(): void { $a = [4, 6]; $b = [2, 5]; @@ -52,7 +52,7 @@ class ChebyshevTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForThreeDimensions() + public function testCalculateDistanceForThreeDimensions(): void { $a = [6, 10, 3]; $b = [2, 5, 5]; diff --git a/tests/Phpml/Math/Distance/EuclideanTest.php b/tests/Phpml/Math/Distance/EuclideanTest.php index 38cb6b7..03bf7f3 100644 --- a/tests/Phpml/Math/Distance/EuclideanTest.php +++ b/tests/Phpml/Math/Distance/EuclideanTest.php @@ -14,7 +14,7 @@ class EuclideanTest extends TestCase */ private $distanceMetric; - public function setUp() + public function setUp(): void { $this->distanceMetric = new Euclidean(); } @@ -22,7 +22,7 @@ class EuclideanTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArguments() + public function testThrowExceptionOnInvalidArguments(): void { $a = [0, 1, 2]; $b = [0, 2]; @@ -30,7 +30,7 @@ class EuclideanTest extends TestCase $this->distanceMetric->distance($a, $b); } - public function testCalculateDistanceForOneDimension() + public function testCalculateDistanceForOneDimension(): void { $a = [4]; $b = [2]; @@ -41,7 +41,7 @@ class EuclideanTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForTwoDimensions() + public function testCalculateDistanceForTwoDimensions(): void { $a = [4, 6]; $b = [2, 5]; @@ -52,7 +52,7 @@ class EuclideanTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForThreeDimensions() + public function testCalculateDistanceForThreeDimensions(): void { $a = [6, 10, 3]; $b = [2, 5, 5]; diff --git a/tests/Phpml/Math/Distance/ManhattanTest.php b/tests/Phpml/Math/Distance/ManhattanTest.php index 0e22a15..9c20edd 100644 --- a/tests/Phpml/Math/Distance/ManhattanTest.php +++ b/tests/Phpml/Math/Distance/ManhattanTest.php @@ -14,7 +14,7 @@ class ManhattanTest extends TestCase */ private $distanceMetric; - public function setUp() + public function setUp(): void { $this->distanceMetric = new Manhattan(); } @@ -22,7 +22,7 @@ class ManhattanTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArguments() + public function testThrowExceptionOnInvalidArguments(): void { $a = [0, 1, 2]; $b = [0, 2]; @@ -30,7 +30,7 @@ class ManhattanTest extends TestCase $this->distanceMetric->distance($a, $b); } - public function testCalculateDistanceForOneDimension() + public function testCalculateDistanceForOneDimension(): void { $a = [4]; $b = [2]; @@ -41,7 +41,7 @@ class ManhattanTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForTwoDimensions() + public function testCalculateDistanceForTwoDimensions(): void { $a = [4, 6]; $b = [2, 5]; @@ -52,7 +52,7 @@ class ManhattanTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForThreeDimensions() + public function testCalculateDistanceForThreeDimensions(): void { $a = [6, 10, 3]; $b = [2, 5, 5]; diff --git a/tests/Phpml/Math/Distance/MinkowskiTest.php b/tests/Phpml/Math/Distance/MinkowskiTest.php index d8931d0..81ecd97 100644 --- a/tests/Phpml/Math/Distance/MinkowskiTest.php +++ b/tests/Phpml/Math/Distance/MinkowskiTest.php @@ -14,7 +14,7 @@ class MinkowskiTest extends TestCase */ private $distanceMetric; - public function setUp() + public function setUp(): void { $this->distanceMetric = new Minkowski(); } @@ -22,7 +22,7 @@ class MinkowskiTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArguments() + public function testThrowExceptionOnInvalidArguments(): void { $a = [0, 1, 2]; $b = [0, 2]; @@ -30,7 +30,7 @@ class MinkowskiTest extends TestCase $this->distanceMetric->distance($a, $b); } - public function testCalculateDistanceForOneDimension() + public function testCalculateDistanceForOneDimension(): void { $a = [4]; $b = [2]; @@ -41,7 +41,7 @@ class MinkowskiTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance); } - public function testCalculateDistanceForTwoDimensions() + public function testCalculateDistanceForTwoDimensions(): void { $a = [4, 6]; $b = [2, 5]; @@ -52,7 +52,7 @@ class MinkowskiTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance, '', $delta = 0.001); } - public function testCalculateDistanceForThreeDimensions() + public function testCalculateDistanceForThreeDimensions(): void { $a = [6, 10, 3]; $b = [2, 5, 5]; @@ -63,7 +63,7 @@ class MinkowskiTest extends TestCase $this->assertEquals($expectedDistance, $actualDistance, '', $delta = 0.001); } - public function testCalculateDistanceForThreeDimensionsWithDifferentLambda() + public function testCalculateDistanceForThreeDimensionsWithDifferentLambda(): void { $distanceMetric = new Minkowski($lambda = 5); diff --git a/tests/Phpml/Math/Kernel/RBFTest.php b/tests/Phpml/Math/Kernel/RBFTest.php index 8076827..3ed7017 100644 --- a/tests/Phpml/Math/Kernel/RBFTest.php +++ b/tests/Phpml/Math/Kernel/RBFTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class RBFTest extends TestCase { - public function testComputeRBFKernelFunction() + public function testComputeRBFKernelFunction(): void { $rbf = new RBF($gamma = 0.001); diff --git a/tests/Phpml/Math/LinearAlgebra/EigenDecompositionTest.php b/tests/Phpml/Math/LinearAlgebra/EigenDecompositionTest.php index 1db2c66..688874c 100644 --- a/tests/Phpml/Math/LinearAlgebra/EigenDecompositionTest.php +++ b/tests/Phpml/Math/LinearAlgebra/EigenDecompositionTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class EigenDecompositionTest extends TestCase { - public function testSymmetricMatrixEigenPairs() + public function testSymmetricMatrixEigenPairs(): void { // Acceptable error $epsilon = 0.001; diff --git a/tests/Phpml/Math/MatrixTest.php b/tests/Phpml/Math/MatrixTest.php index 0285b61..cd9fff2 100644 --- a/tests/Phpml/Math/MatrixTest.php +++ b/tests/Phpml/Math/MatrixTest.php @@ -12,12 +12,12 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidMatrixSupplied() + public function testThrowExceptionOnInvalidMatrixSupplied(): void { new Matrix([[1, 2], [3]]); } - public function testCreateMatrixFromFlatArray() + public function testCreateMatrixFromFlatArray(): void { $flatArray = [1, 2, 3, 4]; $matrix = Matrix::fromFlatArray($flatArray); @@ -32,7 +32,7 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\MatrixException */ - public function testThrowExceptionOnInvalidColumnNumber() + public function testThrowExceptionOnInvalidColumnNumber(): void { $matrix = new Matrix([[1, 2, 3], [4, 5, 6]]); $matrix->getColumnValues(4); @@ -41,13 +41,13 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\MatrixException */ - public function testThrowExceptionOnGetDeterminantIfArrayIsNotSquare() + public function testThrowExceptionOnGetDeterminantIfArrayIsNotSquare(): void { $matrix = new Matrix([[1, 2, 3], [4, 5, 6]]); $matrix->getDeterminant(); } - public function testGetMatrixDeterminant() + public function testGetMatrixDeterminant(): void { //http://matrix.reshish.com/determinant.php $matrix = new Matrix([ @@ -68,7 +68,7 @@ class MatrixTest extends TestCase $this->assertEquals(1116.5035, $matrix->getDeterminant(), '', $delta = 0.0001); } - public function testMatrixTranspose() + public function testMatrixTranspose(): void { $matrix = new Matrix([ [3, 3, 3], @@ -88,7 +88,7 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnMultiplyWhenInconsistentMatrixSupplied() + public function testThrowExceptionOnMultiplyWhenInconsistentMatrixSupplied(): void { $matrix1 = new Matrix([[1, 2, 3], [4, 5, 6]]); $matrix2 = new Matrix([[3, 2, 1], [6, 5, 4]]); @@ -96,7 +96,7 @@ class MatrixTest extends TestCase $matrix1->multiply($matrix2); } - public function testMatrixMultiplyByMatrix() + public function testMatrixMultiplyByMatrix(): void { $matrix1 = new Matrix([ [1, 2, 3], @@ -117,7 +117,7 @@ class MatrixTest extends TestCase $this->assertEquals($product, $matrix1->multiply($matrix2)->toArray()); } - public function testDivideByScalar() + public function testDivideByScalar(): void { $matrix = new Matrix([ [4, 6, 8], @@ -135,7 +135,7 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\MatrixException */ - public function testThrowExceptionWhenInverseIfArrayIsNotSquare() + public function testThrowExceptionWhenInverseIfArrayIsNotSquare(): void { $matrix = new Matrix([[1, 2, 3], [4, 5, 6]]); $matrix->inverse(); @@ -144,7 +144,7 @@ class MatrixTest extends TestCase /** * @expectedException \Phpml\Exception\MatrixException */ - public function testThrowExceptionWhenInverseIfMatrixIsSingular() + public function testThrowExceptionWhenInverseIfMatrixIsSingular(): void { $matrix = new Matrix([ [0, 0, 0], @@ -155,7 +155,7 @@ class MatrixTest extends TestCase $matrix->inverse(); } - public function testInverseMatrix() + public function testInverseMatrix(): void { //http://ncalculators.com/matrix/inverse-matrix.htm $matrix = new Matrix([ @@ -173,7 +173,7 @@ class MatrixTest extends TestCase $this->assertEquals($inverseMatrix, $matrix->inverse()->toArray(), '', $delta = 0.0001); } - public function testCrossOutMatrix() + public function testCrossOutMatrix(): void { $matrix = new Matrix([ [3, 4, 2], @@ -189,14 +189,14 @@ class MatrixTest extends TestCase $this->assertEquals($crossOuted, $matrix->crossOut(1, 1)->toArray()); } - public function testToScalar() + public function testToScalar(): void { $matrix = new Matrix([[1, 2, 3], [3, 2, 3]]); $this->assertEquals($matrix->toScalar(), 1); } - public function testMultiplyByScalar() + public function testMultiplyByScalar(): void { $matrix = new Matrix([ [4, 6, 8], @@ -211,7 +211,7 @@ class MatrixTest extends TestCase $this->assertEquals($result, $matrix->multiplyByScalar(-2)->toArray()); } - public function testAdd() + public function testAdd(): void { $array1 = [1, 1, 1]; $array2 = [2, 2, 2]; @@ -223,7 +223,7 @@ class MatrixTest extends TestCase $this->assertEquals($result, $m1->add($m2)->toArray()[0]); } - public function testSubtract() + public function testSubtract(): void { $array1 = [1, 1, 1]; $array2 = [2, 2, 2]; @@ -235,7 +235,7 @@ class MatrixTest extends TestCase $this->assertEquals($result, $m1->subtract($m2)->toArray()[0]); } - public function testTransposeArray() + public function testTransposeArray(): void { $array = [ [1, 1, 1], @@ -250,7 +250,7 @@ class MatrixTest extends TestCase $this->assertEquals($transposed, Matrix::transposeArray($array)); } - public function testDot() + public function testDot(): void { $vect1 = [2, 2, 2]; $vect2 = [3, 3, 3]; diff --git a/tests/Phpml/Math/ProductTest.php b/tests/Phpml/Math/ProductTest.php index 50ced9e..9c3a4b4 100644 --- a/tests/Phpml/Math/ProductTest.php +++ b/tests/Phpml/Math/ProductTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class ProductTest extends TestCase { - public function testScalarProduct() + public function testScalarProduct(): void { $this->assertEquals(10, Product::scalar([2, 3], [-1, 4])); $this->assertEquals(-0.1, Product::scalar([1, 4, 1], [-2, 0.5, -0.1])); diff --git a/tests/Phpml/Math/SetTest.php b/tests/Phpml/Math/SetTest.php index 101763c..a572a42 100644 --- a/tests/Phpml/Math/SetTest.php +++ b/tests/Phpml/Math/SetTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class SetTest extends TestCase { - public function testUnion() + public function testUnion(): void { $union = Set::union(new Set([3, 1]), new Set([3, 2, 2])); @@ -18,7 +18,7 @@ class SetTest extends TestCase $this->assertEquals(3, $union->cardinality()); } - public function testIntersection() + public function testIntersection(): void { $intersection = Set::intersection(new Set(['C', 'A']), new Set(['B', 'C'])); @@ -27,7 +27,7 @@ class SetTest extends TestCase $this->assertEquals(1, $intersection->cardinality()); } - public function testDifference() + public function testDifference(): void { $difference = Set::difference(new Set(['C', 'A', 'B']), new Set(['A'])); @@ -36,7 +36,7 @@ class SetTest extends TestCase $this->assertEquals(2, $difference->cardinality()); } - public function testPower() + public function testPower(): void { $power = Set::power(new Set(['A', 'B'])); @@ -45,7 +45,7 @@ class SetTest extends TestCase $this->assertCount(4, $power); } - public function testCartesian() + public function testCartesian(): void { $cartesian = Set::cartesian(new Set(['A']), new Set([1, 2])); @@ -54,7 +54,7 @@ class SetTest extends TestCase $this->assertCount(2, $cartesian); } - public function testContains() + public function testContains(): void { $set = new Set(['B', 'A', 2, 1]); @@ -65,21 +65,21 @@ class SetTest extends TestCase $this->assertFalse($set->containsAll(['A', 'B', 'C'])); } - public function testRemove() + public function testRemove(): void { $set = new Set(['B', 'A', 2, 1]); $this->assertEquals((new Set([1, 2, 2, 2, 'B']))->toArray(), $set->remove('A')->toArray()); } - public function testAdd() + public function testAdd(): void { $set = new Set(['B', 'A', 2, 1]); $set->addAll(['foo', 'bar']); $this->assertEquals(6, $set->cardinality()); } - public function testEmpty() + public function testEmpty(): void { $set = new Set([1, 2]); $set->removeAll([2, 1]); @@ -87,7 +87,7 @@ class SetTest extends TestCase $this->assertTrue($set->isEmpty()); } - public function testToArray() + public function testToArray(): void { $set = new Set([1, 2, 2, 3, 'A', false, '', 1.1, -1, -10, 'B']); diff --git a/tests/Phpml/Math/Statistic/CorrelationTest.php b/tests/Phpml/Math/Statistic/CorrelationTest.php index dd01b8b..7fd2cec 100644 --- a/tests/Phpml/Math/Statistic/CorrelationTest.php +++ b/tests/Phpml/Math/Statistic/CorrelationTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class CorrelationTest extends TestCase { - public function testPearsonCorrelation() + public function testPearsonCorrelation(): void { //http://www.stat.wmich.edu/s216/book/node126.html $delta = 0.001; @@ -32,7 +32,7 @@ class CorrelationTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArgumentsForPearsonCorrelation() + public function testThrowExceptionOnInvalidArgumentsForPearsonCorrelation(): void { Correlation::pearson([1, 2, 4], [3, 5]); } diff --git a/tests/Phpml/Math/Statistic/CovarianceTest.php b/tests/Phpml/Math/Statistic/CovarianceTest.php index d2abe7b..3a8c9d3 100644 --- a/tests/Phpml/Math/Statistic/CovarianceTest.php +++ b/tests/Phpml/Math/Statistic/CovarianceTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class CovarianceTest extends TestCase { - public function testSimpleCovariance() + public function testSimpleCovariance(): void { // Acceptable error $epsilon = 0.001; diff --git a/tests/Phpml/Math/Statistic/GaussianTest.php b/tests/Phpml/Math/Statistic/GaussianTest.php index a0c9700..8030f85 100644 --- a/tests/Phpml/Math/Statistic/GaussianTest.php +++ b/tests/Phpml/Math/Statistic/GaussianTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class GaussianTest extends TestCase { - public function testPdf() + public function testPdf(): void { $std = 1.0; $mean = 0.0; diff --git a/tests/Phpml/Math/Statistic/MeanTest.php b/tests/Phpml/Math/Statistic/MeanTest.php index 8f6a8fe..86553e0 100644 --- a/tests/Phpml/Math/Statistic/MeanTest.php +++ b/tests/Phpml/Math/Statistic/MeanTest.php @@ -12,12 +12,12 @@ class MeanTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testArithmeticThrowExceptionOnEmptyArray() + public function testArithmeticThrowExceptionOnEmptyArray(): void { Mean::arithmetic([]); } - public function testArithmeticMean() + public function testArithmeticMean(): void { $delta = 0.01; $this->assertEquals(3.5, Mean::arithmetic([2, 5]), '', $delta); @@ -28,19 +28,19 @@ class MeanTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testMedianThrowExceptionOnEmptyArray() + public function testMedianThrowExceptionOnEmptyArray(): void { Mean::median([]); } - public function testMedianOnOddLengthArray() + public function testMedianOnOddLengthArray(): void { $numbers = [5, 2, 6, 1, 3]; $this->assertEquals(3, Mean::median($numbers)); } - public function testMedianOnEvenLengthArray() + public function testMedianOnEvenLengthArray(): void { $numbers = [5, 2, 6, 1, 3, 4]; @@ -50,12 +50,12 @@ class MeanTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testModeThrowExceptionOnEmptyArray() + public function testModeThrowExceptionOnEmptyArray(): void { Mean::mode([]); } - public function testModeOnArray() + public function testModeOnArray(): void { $numbers = [5, 2, 6, 1, 3, 4, 6, 6, 5]; diff --git a/tests/Phpml/Math/Statistic/StandardDeviationTest.php b/tests/Phpml/Math/Statistic/StandardDeviationTest.php index 35850c4..ead67b5 100644 --- a/tests/Phpml/Math/Statistic/StandardDeviationTest.php +++ b/tests/Phpml/Math/Statistic/StandardDeviationTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class StandardDeviationTest extends TestCase { - public function testStandardDeviationOfPopulationSample() + public function testStandardDeviationOfPopulationSample(): void { //https://pl.wikipedia.org/wiki/Odchylenie_standardowe $delta = 0.001; @@ -28,7 +28,7 @@ class StandardDeviationTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnEmptyArrayIfNotSample() + public function testThrowExceptionOnEmptyArrayIfNotSample(): void { StandardDeviation::population([], false); } @@ -36,7 +36,7 @@ class StandardDeviationTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnToSmallArray() + public function testThrowExceptionOnToSmallArray(): void { StandardDeviation::population([1]); } diff --git a/tests/Phpml/Metric/AccuracyTest.php b/tests/Phpml/Metric/AccuracyTest.php index 02876e0..885893d 100644 --- a/tests/Phpml/Metric/AccuracyTest.php +++ b/tests/Phpml/Metric/AccuracyTest.php @@ -16,7 +16,7 @@ class AccuracyTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidArguments() + public function testThrowExceptionOnInvalidArguments(): void { $actualLabels = ['a', 'b', 'a', 'b']; $predictedLabels = ['a', 'a']; @@ -24,7 +24,7 @@ class AccuracyTest extends TestCase Accuracy::score($actualLabels, $predictedLabels); } - public function testCalculateNormalizedScore() + public function testCalculateNormalizedScore(): void { $actualLabels = ['a', 'b', 'a', 'b']; $predictedLabels = ['a', 'a', 'b', 'b']; @@ -32,7 +32,7 @@ class AccuracyTest extends TestCase $this->assertEquals(0.5, Accuracy::score($actualLabels, $predictedLabels)); } - public function testCalculateNotNormalizedScore() + public function testCalculateNotNormalizedScore(): void { $actualLabels = ['a', 'b', 'a', 'b']; $predictedLabels = ['a', 'b', 'b', 'b']; @@ -40,7 +40,7 @@ class AccuracyTest extends TestCase $this->assertEquals(3, Accuracy::score($actualLabels, $predictedLabels, false)); } - public function testAccuracyOnDemoDataset() + public function testAccuracyOnDemoDataset(): void { $dataset = new RandomSplit(new IrisDataset(), 0.5, 123); diff --git a/tests/Phpml/Metric/ClassificationReportTest.php b/tests/Phpml/Metric/ClassificationReportTest.php index 7b142cf..b7ff02d 100644 --- a/tests/Phpml/Metric/ClassificationReportTest.php +++ b/tests/Phpml/Metric/ClassificationReportTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class ClassificationReportTest extends TestCase { - public function testClassificationReportGenerateWithStringLabels() + public function testClassificationReportGenerateWithStringLabels(): void { $labels = ['cat', 'ant', 'bird', 'bird', 'bird']; $predicted = ['cat', 'cat', 'bird', 'bird', 'ant']; @@ -29,7 +29,7 @@ class ClassificationReportTest extends TestCase $this->assertEquals($average, $report->getAverage(), '', 0.01); } - public function testClassificationReportGenerateWithNumericLabels() + public function testClassificationReportGenerateWithNumericLabels(): void { $labels = [0, 1, 2, 2, 2]; $predicted = [0, 0, 2, 2, 1]; @@ -49,7 +49,7 @@ class ClassificationReportTest extends TestCase $this->assertEquals($average, $report->getAverage(), '', 0.01); } - public function testPreventDivideByZeroWhenTruePositiveAndFalsePositiveSumEqualsZero() + public function testPreventDivideByZeroWhenTruePositiveAndFalsePositiveSumEqualsZero(): void { $labels = [1, 2]; $predicted = [2, 2]; @@ -59,7 +59,7 @@ class ClassificationReportTest extends TestCase $this->assertEquals([1 => 0.0, 2 => 0.5], $report->getPrecision(), '', 0.01); } - public function testPreventDivideByZeroWhenTruePositiveAndFalseNegativeSumEqualsZero() + public function testPreventDivideByZeroWhenTruePositiveAndFalseNegativeSumEqualsZero(): void { $labels = [2, 2, 1]; $predicted = [2, 2, 3]; @@ -69,7 +69,7 @@ class ClassificationReportTest extends TestCase $this->assertEquals([1 => 0.0, 2 => 1, 3 => 0], $report->getPrecision(), '', 0.01); } - public function testPreventDividedByZeroWhenPredictedLabelsAllNotMatch() + public function testPreventDividedByZeroWhenPredictedLabelsAllNotMatch(): void { $labels = [1, 2, 3, 4, 5]; $predicted = [2, 3, 4, 5, 6]; diff --git a/tests/Phpml/Metric/ConfusionMatrixTest.php b/tests/Phpml/Metric/ConfusionMatrixTest.php index 1fa3130..f958bdf 100644 --- a/tests/Phpml/Metric/ConfusionMatrixTest.php +++ b/tests/Phpml/Metric/ConfusionMatrixTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class ConfusionMatrixTest extends TestCase { - public function testComputeConfusionMatrixOnNumericLabels() + public function testComputeConfusionMatrixOnNumericLabels(): void { $actualLabels = [2, 0, 2, 2, 0, 1]; $predictedLabels = [0, 0, 2, 2, 0, 2]; @@ -23,7 +23,7 @@ class ConfusionMatrixTest extends TestCase $this->assertEquals($confusionMatrix, ConfusionMatrix::compute($actualLabels, $predictedLabels)); } - public function testComputeConfusionMatrixOnStringLabels() + public function testComputeConfusionMatrixOnStringLabels(): void { $actualLabels = ['cat', 'ant', 'cat', 'cat', 'ant', 'bird']; $predictedLabels = ['ant', 'ant', 'cat', 'cat', 'ant', 'cat']; @@ -37,7 +37,7 @@ class ConfusionMatrixTest extends TestCase $this->assertEquals($confusionMatrix, ConfusionMatrix::compute($actualLabels, $predictedLabels)); } - public function testComputeConfusionMatrixOnLabelsWithSubset() + public function testComputeConfusionMatrixOnLabelsWithSubset(): void { $actualLabels = ['cat', 'ant', 'cat', 'cat', 'ant', 'bird']; $predictedLabels = ['ant', 'ant', 'cat', 'cat', 'ant', 'cat']; diff --git a/tests/Phpml/ModelManagerTest.php b/tests/Phpml/ModelManagerTest.php index 400b6d1..e44a32a 100644 --- a/tests/Phpml/ModelManagerTest.php +++ b/tests/Phpml/ModelManagerTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class ModelManagerTest extends TestCase { - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $filename = uniqid(); $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$filename; @@ -26,7 +26,7 @@ class ModelManagerTest extends TestCase /** * @expectedException \Phpml\Exception\FileException */ - public function testRestoreWrongFile() + public function testRestoreWrongFile(): void { $filepath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'unexisting'; $modelManager = new ModelManager(); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/BinaryStepTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/BinaryStepTest.php index a62b1c9..95e95cb 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/BinaryStepTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/BinaryStepTest.php @@ -12,7 +12,7 @@ class BinaryStepTest extends TestCase /** * @dataProvider binaryStepProvider */ - public function testBinaryStepActivationFunction($expected, $value) + public function testBinaryStepActivationFunction($expected, $value): void { $binaryStep = new BinaryStep(); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/GaussianTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/GaussianTest.php index 19b6cca..f7af7c0 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/GaussianTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/GaussianTest.php @@ -12,7 +12,7 @@ class GaussianTest extends TestCase /** * @dataProvider gaussianProvider */ - public function testGaussianActivationFunction($expected, $value) + public function testGaussianActivationFunction($expected, $value): void { $gaussian = new Gaussian(); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/HyperboliTangentTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/HyperboliTangentTest.php index b27dfa0..95f437f 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/HyperboliTangentTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/HyperboliTangentTest.php @@ -12,7 +12,7 @@ class HyperboliTangentTest extends TestCase /** * @dataProvider tanhProvider */ - public function testHyperbolicTangentActivationFunction($beta, $expected, $value) + public function testHyperbolicTangentActivationFunction($beta, $expected, $value): void { $tanh = new HyperbolicTangent($beta); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/PReLUTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/PReLUTest.php index 5e14ce8..873520e 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/PReLUTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/PReLUTest.php @@ -12,7 +12,7 @@ class PReLUTest extends TestCase /** * @dataProvider preluProvider */ - public function testPReLUActivationFunction($beta, $expected, $value) + public function testPReLUActivationFunction($beta, $expected, $value): void { $prelu = new PReLU($beta); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/SigmoidTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/SigmoidTest.php index 6894006..096a376 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/SigmoidTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/SigmoidTest.php @@ -12,7 +12,7 @@ class SigmoidTest extends TestCase /** * @dataProvider sigmoidProvider */ - public function testSigmoidActivationFunction($beta, $expected, $value) + public function testSigmoidActivationFunction($beta, $expected, $value): void { $sigmoid = new Sigmoid($beta); diff --git a/tests/Phpml/NeuralNetwork/ActivationFunction/ThresholdedReLUTest.php b/tests/Phpml/NeuralNetwork/ActivationFunction/ThresholdedReLUTest.php index 571a197..1800d7b 100644 --- a/tests/Phpml/NeuralNetwork/ActivationFunction/ThresholdedReLUTest.php +++ b/tests/Phpml/NeuralNetwork/ActivationFunction/ThresholdedReLUTest.php @@ -12,7 +12,7 @@ class ThresholdedReLUTest extends TestCase /** * @dataProvider thresholdProvider */ - public function testThresholdedReLUActivationFunction($theta, $expected, $value) + public function testThresholdedReLUActivationFunction($theta, $expected, $value): void { $thresholdedReLU = new ThresholdedReLU($theta); diff --git a/tests/Phpml/NeuralNetwork/LayerTest.php b/tests/Phpml/NeuralNetwork/LayerTest.php index 4105b6f..284b1eb 100644 --- a/tests/Phpml/NeuralNetwork/LayerTest.php +++ b/tests/Phpml/NeuralNetwork/LayerTest.php @@ -11,14 +11,14 @@ use PHPUnit\Framework\TestCase; class LayerTest extends TestCase { - public function testLayerInitialization() + public function testLayerInitialization(): void { $layer = new Layer(); $this->assertEquals([], $layer->getNodes()); } - public function testLayerInitializationWithDefaultNodesType() + public function testLayerInitializationWithDefaultNodesType(): void { $layer = new Layer($number = 5); @@ -28,7 +28,7 @@ class LayerTest extends TestCase } } - public function testLayerInitializationWithExplicitNodesType() + public function testLayerInitializationWithExplicitNodesType(): void { $layer = new Layer($number = 5, $class = Bias::class); @@ -41,12 +41,12 @@ class LayerTest extends TestCase /** * @expectedException \Phpml\Exception\InvalidArgumentException */ - public function testThrowExceptionOnInvalidNodeClass() + public function testThrowExceptionOnInvalidNodeClass(): void { new Layer(1, \stdClass::class); } - public function testAddNodesToLayer() + public function testAddNodesToLayer(): void { $layer = new Layer(); $layer->addNode($node1 = new Neuron()); diff --git a/tests/Phpml/NeuralNetwork/Network/LayeredNetworkTest.php b/tests/Phpml/NeuralNetwork/Network/LayeredNetworkTest.php index 8b3f0e0..48bee66 100644 --- a/tests/Phpml/NeuralNetwork/Network/LayeredNetworkTest.php +++ b/tests/Phpml/NeuralNetwork/Network/LayeredNetworkTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class LayeredNetworkTest extends TestCase { - public function testLayersSettersAndGetters() + public function testLayersSettersAndGetters(): void { $network = $this->getLayeredNetworkMock(); @@ -21,7 +21,7 @@ class LayeredNetworkTest extends TestCase $this->assertEquals([$layer1, $layer2], $network->getLayers()); } - public function testGetLastLayerAsOutputLayer() + public function testGetLastLayerAsOutputLayer(): void { $network = $this->getLayeredNetworkMock(); $network->addLayer($layer1 = new Layer()); @@ -32,7 +32,7 @@ class LayeredNetworkTest extends TestCase $this->assertEquals($layer2, $network->getOutputLayer()); } - public function testSetInputAndGetOutput() + public function testSetInputAndGetOutput(): void { $network = $this->getLayeredNetworkMock(); $network->addLayer(new Layer(2, Input::class)); diff --git a/tests/Phpml/NeuralNetwork/Node/BiasTest.php b/tests/Phpml/NeuralNetwork/Node/BiasTest.php index 8f01d52..ee311f5 100644 --- a/tests/Phpml/NeuralNetwork/Node/BiasTest.php +++ b/tests/Phpml/NeuralNetwork/Node/BiasTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class BiasTest extends TestCase { - public function testBiasOutput() + public function testBiasOutput(): void { $bias = new Bias(); diff --git a/tests/Phpml/NeuralNetwork/Node/InputTest.php b/tests/Phpml/NeuralNetwork/Node/InputTest.php index 31d86c9..2d3be71 100644 --- a/tests/Phpml/NeuralNetwork/Node/InputTest.php +++ b/tests/Phpml/NeuralNetwork/Node/InputTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class InputTest extends TestCase { - public function testInputInitialization() + public function testInputInitialization(): void { $input = new Input(); $this->assertEquals(0.0, $input->getOutput()); @@ -18,7 +18,7 @@ class InputTest extends TestCase $this->assertEquals($value, $input->getOutput()); } - public function testSetInput() + public function testSetInput(): void { $input = new Input(); $input->setInput($value = 6.9); diff --git a/tests/Phpml/NeuralNetwork/Node/Neuron/SynapseTest.php b/tests/Phpml/NeuralNetwork/Node/Neuron/SynapseTest.php index 126d70d..02d6dfa 100644 --- a/tests/Phpml/NeuralNetwork/Node/Neuron/SynapseTest.php +++ b/tests/Phpml/NeuralNetwork/Node/Neuron/SynapseTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class SynapseTest extends TestCase { - public function testSynapseInitialization() + public function testSynapseInitialization(): void { $node = $this->getNodeMock($nodeOutput = 0.5); @@ -25,7 +25,7 @@ class SynapseTest extends TestCase $this->assertInternalType('float', $synapse->getWeight()); } - public function testSynapseWeightChange() + public function testSynapseWeightChange(): void { $node = $this->getNodeMock(); $synapse = new Synapse($node, $weight = 0.75); diff --git a/tests/Phpml/NeuralNetwork/Node/NeuronTest.php b/tests/Phpml/NeuralNetwork/Node/NeuronTest.php index a7bc6fe..89f1ca1 100644 --- a/tests/Phpml/NeuralNetwork/Node/NeuronTest.php +++ b/tests/Phpml/NeuralNetwork/Node/NeuronTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class NeuronTest extends TestCase { - public function testNeuronInitialization() + public function testNeuronInitialization(): void { $neuron = new Neuron(); @@ -19,7 +19,7 @@ class NeuronTest extends TestCase $this->assertEquals(0.5, $neuron->getOutput()); } - public function testNeuronActivationFunction() + public function testNeuronActivationFunction(): void { $activationFunction = $this->getMockBuilder(BinaryStep::class)->getMock(); $activationFunction->method('compute')->with(0)->willReturn($output = 0.69); @@ -29,7 +29,7 @@ class NeuronTest extends TestCase $this->assertEquals($output, $neuron->getOutput()); } - public function testNeuronWithSynapse() + public function testNeuronWithSynapse(): void { $neuron = new Neuron(); $neuron->addSynapse($synapse = $this->getSynapseMock()); @@ -38,7 +38,7 @@ class NeuronTest extends TestCase $this->assertEquals(0.88, $neuron->getOutput(), '', 0.01); } - public function testNeuronRefresh() + public function testNeuronRefresh(): void { $neuron = new Neuron(); $neuron->getOutput(); diff --git a/tests/Phpml/PipelineTest.php b/tests/Phpml/PipelineTest.php index 7fc3545..fc06e56 100644 --- a/tests/Phpml/PipelineTest.php +++ b/tests/Phpml/PipelineTest.php @@ -17,7 +17,7 @@ use PHPUnit\Framework\TestCase; class PipelineTest extends TestCase { - public function testPipelineConstruction() + public function testPipelineConstruction(): void { $transformers = [ new TfIdfTransformer(), @@ -30,7 +30,7 @@ class PipelineTest extends TestCase $this->assertEquals($estimator, $pipeline->getEstimator()); } - public function testPipelineEstimatorSetter() + public function testPipelineEstimatorSetter(): void { $pipeline = new Pipeline([new TfIdfTransformer()], new SVC()); @@ -40,7 +40,7 @@ class PipelineTest extends TestCase $this->assertEquals($estimator, $pipeline->getEstimator()); } - public function testPipelineWorkflow() + public function testPipelineWorkflow(): void { $transformers = [ new Imputer(null, new MostFrequentStrategy()), @@ -68,7 +68,7 @@ class PipelineTest extends TestCase $this->assertEquals(4, $predicted[0]); } - public function testPipelineTransformers() + public function testPipelineTransformers(): void { $transformers = [ new TokenCountVectorizer(new WordTokenizer()), diff --git a/tests/Phpml/Preprocessing/ImputerTest.php b/tests/Phpml/Preprocessing/ImputerTest.php index 2f5c31b..658b454 100644 --- a/tests/Phpml/Preprocessing/ImputerTest.php +++ b/tests/Phpml/Preprocessing/ImputerTest.php @@ -12,7 +12,7 @@ use PHPUnit\Framework\TestCase; class ImputerTest extends TestCase { - public function testComplementsMissingValuesWithMeanStrategyOnColumnAxis() + public function testComplementsMissingValuesWithMeanStrategyOnColumnAxis(): void { $data = [ [1, null, 3, 4], @@ -34,7 +34,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data, '', $delta = 0.01); } - public function testComplementsMissingValuesWithMeanStrategyOnRowAxis() + public function testComplementsMissingValuesWithMeanStrategyOnRowAxis(): void { $data = [ [1, null, 3, 4], @@ -56,7 +56,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data, '', $delta = 0.01); } - public function testComplementsMissingValuesWithMediaStrategyOnColumnAxis() + public function testComplementsMissingValuesWithMediaStrategyOnColumnAxis(): void { $data = [ [1, null, 3, 4], @@ -78,7 +78,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data, '', $delta = 0.01); } - public function testComplementsMissingValuesWithMediaStrategyOnRowAxis() + public function testComplementsMissingValuesWithMediaStrategyOnRowAxis(): void { $data = [ [1, null, 3, 4], @@ -100,7 +100,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data, '', $delta = 0.01); } - public function testComplementsMissingValuesWithMostFrequentStrategyOnColumnAxis() + public function testComplementsMissingValuesWithMostFrequentStrategyOnColumnAxis(): void { $data = [ [1, null, 3, 4], @@ -124,7 +124,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data); } - public function testComplementsMissingValuesWithMostFrequentStrategyOnRowAxis() + public function testComplementsMissingValuesWithMostFrequentStrategyOnRowAxis(): void { $data = [ [1, null, 3, 4, 3], @@ -148,7 +148,7 @@ class ImputerTest extends TestCase $this->assertEquals($imputeData, $data); } - public function testImputerWorksOnFitSamples() + public function testImputerWorksOnFitSamples(): void { $trainData = [ [1, 3, 4], diff --git a/tests/Phpml/Preprocessing/NormalizerTest.php b/tests/Phpml/Preprocessing/NormalizerTest.php index 542eef5..22ed1bd 100644 --- a/tests/Phpml/Preprocessing/NormalizerTest.php +++ b/tests/Phpml/Preprocessing/NormalizerTest.php @@ -12,12 +12,12 @@ class NormalizerTest extends TestCase /** * @expectedException \Phpml\Exception\NormalizerException */ - public function testThrowExceptionOnInvalidNorm() + public function testThrowExceptionOnInvalidNorm(): void { new Normalizer(99); } - public function testNormalizeSamplesWithL2Norm() + public function testNormalizeSamplesWithL2Norm(): void { $samples = [ [1, -1, 2], @@ -37,7 +37,7 @@ class NormalizerTest extends TestCase $this->assertEquals($normalized, $samples, '', $delta = 0.01); } - public function testNormalizeSamplesWithL1Norm() + public function testNormalizeSamplesWithL1Norm(): void { $samples = [ [1, -1, 2], @@ -57,7 +57,7 @@ class NormalizerTest extends TestCase $this->assertEquals($normalized, $samples, '', $delta = 0.01); } - public function testFitNotChangeNormalizerBehavior() + public function testFitNotChangeNormalizerBehavior(): void { $samples = [ [1, -1, 2], @@ -81,7 +81,7 @@ class NormalizerTest extends TestCase $this->assertEquals($normalized, $samples, '', $delta = 0.01); } - public function testL1NormWithZeroSumCondition() + public function testL1NormWithZeroSumCondition(): void { $samples = [ [0, 0, 0], @@ -101,7 +101,7 @@ class NormalizerTest extends TestCase $this->assertEquals($normalized, $samples, '', $delta = 0.01); } - public function testStandardNorm() + public function testStandardNorm(): void { // Generate 10 random vectors of length 3 $samples = []; diff --git a/tests/Phpml/Regression/LeastSquaresTest.php b/tests/Phpml/Regression/LeastSquaresTest.php index ac457a9..7d835a2 100644 --- a/tests/Phpml/Regression/LeastSquaresTest.php +++ b/tests/Phpml/Regression/LeastSquaresTest.php @@ -10,7 +10,7 @@ use PHPUnit\Framework\TestCase; class LeastSquaresTest extends TestCase { - public function testPredictSingleFeatureSamples() + public function testPredictSingleFeatureSamples(): void { $delta = 0.01; @@ -37,7 +37,7 @@ class LeastSquaresTest extends TestCase $this->assertEquals(278.66, $regression->predict([153260]), '', $delta); } - public function testPredictSingleFeatureSamplesWithMatrixTargets() + public function testPredictSingleFeatureSamplesWithMatrixTargets(): void { $delta = 0.01; @@ -51,7 +51,7 @@ class LeastSquaresTest extends TestCase $this->assertEquals(4.06, $regression->predict([64]), '', $delta); } - public function testPredictMultiFeaturesSamples() + public function testPredictMultiFeaturesSamples(): void { $delta = 0.01; @@ -68,7 +68,7 @@ class LeastSquaresTest extends TestCase $this->assertEquals(5711.40, $regression->predict([60000, 2000]), '', $delta); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { //https://www.easycalculation.com/analytical/learn-least-square-regression.php $samples = [[60], [61], [62], [63], [65]]; diff --git a/tests/Phpml/Regression/SVRTest.php b/tests/Phpml/Regression/SVRTest.php index 4ea19a3..3cd0ee5 100644 --- a/tests/Phpml/Regression/SVRTest.php +++ b/tests/Phpml/Regression/SVRTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class SVRTest extends TestCase { - public function testPredictSingleFeatureSamples() + public function testPredictSingleFeatureSamples(): void { $delta = 0.01; @@ -24,7 +24,7 @@ class SVRTest extends TestCase $this->assertEquals(4.03, $regression->predict([64]), '', $delta); } - public function testPredictMultiFeaturesSamples() + public function testPredictMultiFeaturesSamples(): void { $delta = 0.01; @@ -37,7 +37,7 @@ class SVRTest extends TestCase $this->assertEquals([4109.82, 4112.28], $regression->predict([[60000, 1996], [60000, 2000]]), '', $delta); } - public function testSaveAndRestore() + public function testSaveAndRestore(): void { $samples = [[60], [61], [62], [63], [65]]; $targets = [3.1, 3.6, 3.8, 4, 4.1]; diff --git a/tests/Phpml/SupportVectorMachine/DataTransformerTest.php b/tests/Phpml/SupportVectorMachine/DataTransformerTest.php index 9aa1558..b1f8522 100644 --- a/tests/Phpml/SupportVectorMachine/DataTransformerTest.php +++ b/tests/Phpml/SupportVectorMachine/DataTransformerTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class DataTransformerTest extends TestCase { - public function testTransformDatasetToTrainingSet() + public function testTransformDatasetToTrainingSet(): void { $samples = [[1, 1], [2, 1], [3, 2], [4, 5]]; $labels = ['a', 'a', 'b', 'b']; @@ -24,7 +24,7 @@ class DataTransformerTest extends TestCase $this->assertEquals($trainingSet, DataTransformer::trainingSet($samples, $labels)); } - public function testTransformSamplesToTestSet() + public function testTransformSamplesToTestSet(): void { $samples = [[1, 1], [2, 1], [3, 2], [4, 5]]; diff --git a/tests/Phpml/SupportVectorMachine/SupportVectorMachineTest.php b/tests/Phpml/SupportVectorMachine/SupportVectorMachineTest.php index 4cc6d57..ebbf99f 100644 --- a/tests/Phpml/SupportVectorMachine/SupportVectorMachineTest.php +++ b/tests/Phpml/SupportVectorMachine/SupportVectorMachineTest.php @@ -11,7 +11,7 @@ use PHPUnit\Framework\TestCase; class SupportVectorMachineTest extends TestCase { - public function testTrainCSVCModelWithLinearKernel() + public function testTrainCSVCModelWithLinearKernel(): void { $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $labels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -35,7 +35,7 @@ SV $this->assertEquals($model, $svm->getModel()); } - public function testPredictSampleWithLinearKernel() + public function testPredictSampleWithLinearKernel(): void { $samples = [[1, 3], [1, 4], [2, 4], [3, 1], [4, 1], [4, 2]]; $labels = ['a', 'a', 'a', 'b', 'b', 'b']; @@ -54,7 +54,7 @@ SV $this->assertEquals('b', $predictions[2]); } - public function testPredictSampleFromMultipleClassWithRbfKernel() + public function testPredictSampleFromMultipleClassWithRbfKernel(): void { $samples = [ [1, 3], [1, 4], [1, 4], @@ -85,7 +85,7 @@ SV * @expectedException \Phpml\Exception\InvalidArgumentException * @expectedExceptionMessage is not writable */ - public function testThrowExceptionWhenVarPathIsNotWritable() + public function testThrowExceptionWhenVarPathIsNotWritable(): void { $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF); $svm->setVarPath('var-path'); @@ -95,7 +95,7 @@ SV * @expectedException \Phpml\Exception\InvalidArgumentException * @expectedExceptionMessage does not exist */ - public function testThrowExceptionWhenBinPathDoesNotExist() + public function testThrowExceptionWhenBinPathDoesNotExist(): void { $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF); $svm->setBinPath('bin-path'); @@ -105,7 +105,7 @@ SV * @expectedException \Phpml\Exception\InvalidArgumentException * @expectedExceptionMessage not found */ - public function testThrowExceptionWhenFileIsNotFoundInBinPath() + public function testThrowExceptionWhenFileIsNotFoundInBinPath(): void { $svm = new SupportVectorMachine(Type::C_SVC, Kernel::RBF); $svm->setBinPath('var'); diff --git a/tests/Phpml/Tokenization/WhitespaceTokenizerTest.php b/tests/Phpml/Tokenization/WhitespaceTokenizerTest.php index 97fa833..f9d7c73 100644 --- a/tests/Phpml/Tokenization/WhitespaceTokenizerTest.php +++ b/tests/Phpml/Tokenization/WhitespaceTokenizerTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class WhitespaceTokenizerTest extends TestCase { - public function testTokenizationOnAscii() + public function testTokenizationOnAscii(): void { $tokenizer = new WhitespaceTokenizer(); @@ -24,7 +24,7 @@ class WhitespaceTokenizerTest extends TestCase $this->assertEquals($tokens, $tokenizer->tokenize($text)); } - public function testTokenizationOnUtf8() + public function testTokenizationOnUtf8(): void { $tokenizer = new WhitespaceTokenizer(); diff --git a/tests/Phpml/Tokenization/WordTokenizerTest.php b/tests/Phpml/Tokenization/WordTokenizerTest.php index 09db222..607c327 100644 --- a/tests/Phpml/Tokenization/WordTokenizerTest.php +++ b/tests/Phpml/Tokenization/WordTokenizerTest.php @@ -9,7 +9,7 @@ use PHPUnit\Framework\TestCase; class WordTokenizerTest extends TestCase { - public function testTokenizationOnAscii() + public function testTokenizationOnAscii(): void { $tokenizer = new WordTokenizer(); @@ -24,7 +24,7 @@ class WordTokenizerTest extends TestCase $this->assertEquals($tokens, $tokenizer->tokenize($text)); } - public function testTokenizationOnUtf8() + public function testTokenizationOnUtf8(): void { $tokenizer = new WordTokenizer();