-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathloss.go
80 lines (61 loc) · 1.35 KB
/
loss.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
package whale
import "github.com/hidetatz/whale/tensor"
type LossCalculator interface {
Calculate(pred, actual *Variable) (*Variable, error)
}
type MSE struct{}
func NewMSE() *MSE {
return &MSE{}
}
func (m *MSE) Calculate(pred, actual *Variable) (*Variable, error) {
diff, err := Sub(pred, actual)
if err != nil {
return nil, err
}
squ, err := Pow(diff, NewVar(tensor.Scalar(2)))
if err != nil {
return nil, err
}
sm, err := Sum(squ, false)
if err != nil {
return nil, err
}
return Div(sm, NewVar(tensor.Scalar(float32(diff.Size()))))
}
type SoftmaxCrossEntropy struct{}
func NewSoftmaxCrossEntropy() *SoftmaxCrossEntropy {
return &SoftmaxCrossEntropy{}
}
func (s *SoftmaxCrossEntropy) Calculate(x, t *Variable) (*Variable, error) {
n := x.data.Shape[0]
a, err := NewSoftMax().Activate(x)
if err != nil {
return nil, err
}
p, err := Clip(a, 1e-15, 1.0)
if err != nil {
return nil, err
}
logp, err := Log(p)
if err != nil {
return nil, err
}
ar := tensor.Arange(0, float32(n), 1).Reshape(n)
tlogp, err := Index(logp, NewVar(ar), t)
if err != nil {
return nil, err
}
sum, err := Sum(tlogp, false)
if err != nil {
return nil, err
}
m, err := Mul(NewVar(tensor.Scalar(-1)), sum)
if err != nil {
return nil, err
}
d, err := Div(m, NewVar(tensor.Scalar(float32(n))))
if err != nil {
return nil, err
}
return d, nil
}