-
Notifications
You must be signed in to change notification settings - Fork 4
/
utils.py
54 lines (40 loc) · 1.18 KB
/
utils.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
''' ---------------------------------
Utility Functions
Simple utility functions, placed in here to make the main code easier to read
--------------------------------- '''
# Initialises a dictionary with the same keys as d but with zero-vector values
def init_dict_like(d):
return {k: np.zeros_like(v) for k, v in d.iteritems()}
# Normalises a vector
def normalise(vec):
return vec / np.sum(vec)
# Generates a one-hot-vector of length len, with the ith element 1
def one_hot_vec(len, i):
vec = np.zeros((len, 1))
vec[i] = 1
return vec
# TODO: possibly replace with hard sigmoid (faster)
def sigmoid(x, D):
if not D:
return 1 / (1 + np.exp(- x))
else:
s = sigmoid(x, False)
return s - (s ** 2)
def tanh(x, D):
if not D:
return np.tanh(x)
else:
return 1.0 - (np.tanh(x) ** 2)
# Initialises the LSTM weight matrices
def init_lstm_weights(X_DIM, Y_DIM, zeroed):
def layer():
if zeroed:
return np.zeros((X_DIM, Y_DIM))
else:
return np.random.random((X_DIM, Y_DIM)) * 0.01
return {
'i': layer(),
'f': layer(),
'o': layer(),
'g': layer()
}