-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.py
63 lines (50 loc) · 1.52 KB
/
functions.py
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
import numpy as np
def sigmoid(x):
return 1/(1+np.exp(-x))
def relu(x):
x[np.where(x<0)] = 0
return x
def linear(x):
return x
def softmax(x):
'''Compute the softmax in a numerically stable way.'''
x = x - np.max(x)
x_exp = np.exp(x)
sum_exp = np.sum(x_exp, axis=1).reshape(x.shape[0], -1)
return x_exp/sum_exp
def softmax_grad(x):
'''
it's better to combine the cross entropy with softmax to calculate the gradient
'''
pass
def relu_grad(x):
grad = np.where(x < 0, 0, 1)
return grad
def sigmoid_grad(x):
return sigmoid(x)*(1-sigmoid(x))
def linear_grad(x):
return 1
def cross_entropy(y, y_true, reduce="mean"):
if reduce=="mean":
return np.sum(-y_true*np.log(y+1e-12))/y.shape[0]
else:
return np.sum(-y_true*np.log(y+1e-12))
def cross_entropy_grad(y, y_true):
'''
it's better to combine the cross entropy with softmax to calculate the gradient
'''
pass
def binary_cross_entropy_grad(y, y_true):
'''
y.shape = y_true.shape: [m, 1] 1 is the output dim, m is the nsmaples
'''
return -(y_true*(1/(y+1e-12)) + (1-y_true)*1/(1-y+1e-12))
def binary_cross_entropy(y, y_true, reduce="mean"):
'''
y.shape = y_true.shape: [m, 1] 1 is the output dim, m is the nsmaples
L = -(yilogy+(1-y)log(1-y))
'''
if reduce=="mean":
return np.mean(-(y_true*np.log(y+1e-12) + (1-y_true)*np.log(1-y+1e-12)))
else:
return np.sum(-(y_true*np.log(y+1e-12) + (1-y_true)*np.log(1-y+1e-12)))