Completed
Push — develop ( 50fbcd...100205 )
by Arkadiusz
02:36
created

NaiveBayes   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 64
Duplicated Lines 20.31 %

Coupling/Cohesion

Components 1
Dependencies 0

Importance

Changes 7
Bugs 0 Features 1
Metric Value
wmc 8
c 7
b 0
f 1
lcom 1
cbo 0
dl 13
loc 64
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A train() 0 5 1
A predict() 13 13 3
A predictSample() 0 17 4

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
3
declare (strict_types = 1);
4
5
namespace Phpml\Classifier;
6
7
class NaiveBayes implements Classifier
8
{
9
    /**
10
     * @var array
11
     */
12
    private $samples;
13
14
    /**
15
     * @var array
16
     */
17
    private $labels;
18
19
    /**
20
     * @param array $samples
21
     * @param array $labels
22
     */
23
    public function train(array $samples, array $labels)
24
    {
25
        $this->samples = $samples;
26
        $this->labels = $labels;
27
    }
28
29
    /**
30
     * @param array $samples
31
     *
32
     * @return mixed
33
     */
34 View Code Duplication
    public function predict(array $samples)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
35
    {
36
        if (!is_array($samples[0])) {
37
            $predicted = $this->predictSample($samples);
38
        } else {
39
            $predicted = [];
40
            foreach ($samples as $index => $sample) {
41
                $predicted[$index] = $this->predictSample($sample);
42
            }
43
        }
44
45
        return $predicted;
46
    }
47
48
    /**
49
     * @param array $sample
50
     *
51
     * @return mixed
52
     */
53
    private function predictSample(array $sample)
54
    {
55
        $predictions = [];
56
        foreach ($this->labels as $index => $label) {
57
            $predictions[$label] = 0;
58
            foreach ($sample as $token => $count) {
59
                if (array_key_exists($token, $this->samples[$index])) {
60
                    $predictions[$label] += $count * $this->samples[$index][$token];
61
                }
62
            }
63
        }
64
65
        arsort($predictions, SORT_NUMERIC);
66
        reset($predictions);
67
68
        return key($predictions);
69
    }
70
}
71