-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
135 lines (117 loc) · 2.02 KB
/
util.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
package deep
import "math"
// Mean of xx
func Mean(xx []float64) float64 {
var sum float64
for _, x := range xx {
sum += x
}
return sum / float64(len(xx))
}
// Variance of xx
func Variance(xx []float64) float64 {
if len(xx) == 1 {
return 0.0
}
m := Mean(xx)
var variance float64
for _, x := range xx {
variance += math.Pow((x - m), 2)
}
return variance / float64(len(xx)-1)
}
// StandardDeviation of xx
func StandardDeviation(xx []float64) float64 {
return math.Sqrt(Variance(xx))
}
// Standardize (z-score) shifts distribution to μ=0 σ=1
func Standardize(xx []float64) {
m := Mean(xx)
s := StandardDeviation(xx)
if s == 0 {
s = 1
}
for i, x := range xx {
xx[i] = (x - m) / s
}
}
// Normalize scales to (0,1)
func Normalize(xx []float64) {
min, max := Min(xx), Max(xx)
for i, x := range xx {
xx[i] = (x - min) / (max - min)
}
}
// Min is the smallest element
func Min(xx []float64) float64 {
min := xx[0]
for _, x := range xx {
if x < min {
min = x
}
}
return min
}
// Max is the largest element
func Max(xx []float64) float64 {
max := xx[0]
for _, x := range xx {
if x > max {
max = x
}
}
return max
}
// ArgMax is the index of the largest element
func ArgMax(xx []float64) int {
max, idx := xx[0], 0
for i, x := range xx {
if x > max {
max, idx = xx[i], i
}
}
return idx
}
// Sgn is signum
func Sgn(x float64) float64 {
switch {
case x < 0:
return -1.0
case x > 0:
return 1.0
}
return 0
}
// Sum is sum
func Sum(xx []float64) (sum float64) {
for _, x := range xx {
sum += x
}
return
}
// Softmax is the softmax function
func Softmax(xx []float64) []float64 {
out := make([]float64, len(xx))
var sum float64
max := Max(xx)
for i, x := range xx {
out[i] = math.Exp(x - max)
sum += out[i]
}
for i := range out {
out[i] /= sum
}
return out
}
// Round to nearest integer
func Round(x float64) float64 {
return math.Floor(x + .5)
}
// Dot product
func Dot(xx, yy []float64) float64 {
var p float64
for i := range xx {
p += xx[i] * yy[i]
}
return p
}