-
-
Notifications
You must be signed in to change notification settings - Fork 189
/
Copy pathL2Normalizer.php
82 lines (71 loc) · 1.59 KB
/
L2Normalizer.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<?php
namespace Rubix\ML\Transformers;
use Rubix\ML\DataType;
use function array_walk;
use function sqrt;
/**
* L2 Normalizer
*
* Transform each sample vector in the sample matrix such that each feature is divided by
* the L2 norm (or *magnitude*) of that vector. The resulting sample will have continuous
* features between 0 and 1.
*
* @category Machine Learning
* @package Rubix/ML
* @author Andrew DalPino
*/
class L2Normalizer implements Transformer
{
/**
* Return the data types that this transformer is compatible with.
*
* @internal
*
* @return list<DataType>
*/
public function compatibility() : array
{
return [
DataType::continuous(),
];
}
/**
* Transform the dataset in place.
*
* @param array<mixed[]> $samples
*/
public function transform(array &$samples) : void
{
array_walk($samples, [$this, 'normalize']);
}
/**
* Normalize a sample by its L2 norm.
*
* @param list<int|float> $sample
*/
protected function normalize(array &$sample) : void
{
$norm = 0.0;
foreach ($sample as $value) {
$norm += $value ** 2;
}
if ($norm === 0.0) {
return;
}
$norm = sqrt($norm);
foreach ($sample as &$value) {
$value /= $norm;
}
}
/**
* Return the string representation of the object.
*
* @internal
*
* @return string
*/
public function __toString() : string
{
return 'L2 Normalizer';
}
}