-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathnormalize.go
146 lines (113 loc) · 2.3 KB
/
normalize.go
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package optimus
import (
"errors"
"github.com/montanaflynn/stats"
)
var (
ErrDegenerateVector = errors.New("all elements in the vector the same")
)
type Normalizer interface {
Normalize(x float64) float64
NormalizeBatch(x []float64)
Denormalize(x float64) float64
IsDegenerated() bool
}
type nilNormalizer struct{}
func (*nilNormalizer) Normalize(x float64) float64 {
return x
}
func (*nilNormalizer) NormalizeBatch(x []float64) {
}
func (*nilNormalizer) Denormalize(x float64) float64 {
return x
}
func (*nilNormalizer) IsDegenerated() bool {
return false
}
type meanNormalizer struct {
mean float64
scale float64
}
func newMeanNormalizer(values []float64) (Normalizer, error) {
min, err := stats.Min(values)
if err != nil {
return nil, err
}
max, err := stats.Max(values)
if err != nil {
return nil, err
}
scale := max - min
if scale == 0.0 {
return nil, ErrDegenerateVector
}
mean, err := stats.Mean(values)
if err != nil {
return nil, err
}
m := &meanNormalizer{
mean: mean,
scale: scale,
}
return m, nil
}
func (m *meanNormalizer) Normalize(x float64) float64 {
return (x - m.mean) / m.scale
}
func (m *meanNormalizer) NormalizeBatch(x []float64) {
for i, v := range x {
x[i] = m.Normalize(v)
}
}
func (m *meanNormalizer) IsDegenerated() bool {
return m.scale == 0.0
}
func (m *meanNormalizer) Denormalize(x float64) float64 {
return x*m.scale + m.mean
}
// Normalizer rescales the range of features to scale the range in [0, 1].
type normalizer struct {
min float64
max float64
scale float64
}
func newNormalizer(vec ...float64) (Normalizer, error) {
m := &normalizer{}
if len(vec) > 0 {
min, err := stats.Min(vec)
if err != nil {
return nil, err
}
max, err := stats.Max(vec)
if err != nil {
return nil, err
}
m.min = min
m.max = max
m.scale = max - min
}
return m, nil
}
func (m *normalizer) Add(x float64) {
if x < m.min {
m.min = x
}
if x > m.max {
m.max = x
}
m.scale = m.max - m.min
}
func (m *normalizer) IsDegenerated() bool {
return m.scale == 0.0
}
func (m *normalizer) Normalize(x float64) float64 {
return (x - m.min) / m.scale
}
func (m *normalizer) NormalizeBatch(x []float64) {
for i, v := range x {
x[i] = m.Normalize(v)
}
}
func (m *normalizer) Denormalize(x float64) float64 {
return x*m.scale + m.min
}