-
Notifications
You must be signed in to change notification settings - Fork 1
/
model.py
172 lines (134 loc) · 5.46 KB
/
model.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
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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# -----------------------------------------------------------------------------
# Gated working memory with an echo state network
# Copyright (c) 2018 Nicolas P. Rougier
#
# Distributed under the terms of the BSD License.
# -----------------------------------------------------------------------------
import tqdm
import numpy as np
def generate_model(shape, sparsity=0.25, radius=1.0, scaling=0.25,
leak=1.0, noise=0.0, seed=0):
"""
Generate a reservoir according to parameters
shape: tuple
shape of the reservoir as (a,b,c) where:
a: number of input
b: number of reservoir units
d: number of output
sparsity: float
Connectivity sparsity inside the reservoir
(percentage of non null connexions)
radius: float
Spectral radius
scaling: float
scaling of the reservoir input and feedback as (i,f)
i: Input scaling
f: Feedback scaling
leak: float
Neuron leak
noise: float
Noise level inside the reservoir
seed: int
Seed for the random generator
"""
# Get a random generator
rng = np.random
if seed is not None:
rng = np.random.mtrand.RandomState(seed)
if isinstance(scaling, (int,float)):
scaling = { "in": 1,
"fb": scaling
}
else:
scaling = { "in": scaling[0],
"fb": scaling[1],
}
# Reservoir building
W_in = rng.uniform(-1.0, 1.0, (shape[1], shape[0]))
W_in *= scaling["in"]
W_rc = rng.uniform(-0.5, 0.5, (shape[1], shape[1]))
W_rc[rng.uniform(0.0, 1.0, W_rc.shape) > sparsity] = 0.0
W_rc *= radius / np.max(np.abs(np.linalg.eigvals(W_rc)))
W_fb = rng.uniform(-1.0, 1.0, (shape[1], shape[2]))
W_fb *= scaling["fb"]
# W_fb *= rng.uniform(0.0, 1.0, (shape[1], shape[2])) < 0.25
if isinstance(noise, (int,float)):
noise = { "input": noise,
"internal": noise,
"output": noise }
else:
noise = { "input": noise[0],
"internal": noise[1],
"output": noise[2] }
return { "shape" : shape,
"sparsity" : sparsity,
"scaling" : scaling,
"leak" : leak,
"noise" : noise,
"W_in" : W_in,
"W_rc" : W_rc,
"W_fb" : W_fb,
"W_out" : None }
def train_model(model, data, seed=None):
""" Train the model using provided data and seed (noise). """
# Get a random generator
rng = np.random
if seed is not None:
rng = np.random.mtrand.RandomState(seed)
inputs, outputs = data["input"], data["output"]
internals = np.zeros((len(data), model["shape"][1]))
leak = model["leak"]
shape_in = inputs[0].shape
shape_rc = internals[0].shape
shape_out = outputs[0].shape
# Gathering internal states over all samples
for i in tqdm.trange(1, len(data)):
noise_in = model["noise"]["input"] * rng.uniform(-1, 1, shape_in)
noise_rc = model["noise"]["internal"] * rng.uniform(-1, 1, shape_rc)
noise_out = model["noise"]["output"] * rng.uniform(-1, 1, shape_out)
z = (np.dot(model["W_rc"], internals[i-1]) +
np.dot(model["W_in"], inputs[i] + noise_in) +
np.dot(model["W_fb"], outputs[i-1] + noise_out))
internals[i] = np.tanh(z) + noise_rc
internals[i] = (1-leak)*internals[i-1] + leak*internals[i]
# Computing W_out over a subset of reservoir units
W_out = np.dot(np.linalg.pinv(internals), outputs).T
error = np.sqrt(np.mean((np.dot(internals, W_out.T) - outputs)**2))
model["W_out"] = W_out
model["last_state"] = inputs[-1], internals[-1], outputs[-1]
return error
def test_model(model, data, seed=None):
""" Test the model using provided data and seed (noise). """
# Get a random generator
rng = np.random
if seed is not None:
rng = np.random.mtrand.RandomState(seed)
# Shortened version
# W_ = model["W_rc"] + model["scaling"] * (model["W_out"]*model["W_fb"])
last_input, last_internal, last_output = model["last_state"]
inputs = np.vstack([last_input, data["input"]])
internals = np.vstack([last_internal,
np.zeros((len(data), model["shape"][1]))])
outputs = np.vstack([last_output, data["output"]])
leak = model["leak"]
shape_in = inputs[0].shape
shape_rc = internals[0].shape
shape_out = outputs[0].shape
for i in tqdm.trange(1,len(data)+1):
noise_in = model["noise"]["input"] * rng.uniform(-1, 1, shape_in)
noise_rc = model["noise"]["internal"] * rng.uniform(-1, 1, shape_rc)
noise_out = model["noise"]["output"] * rng.uniform(-1, 1, shape_out)
# Regular version
z = ( np.dot(model["W_rc"], internals[i-1]) +
np.dot(model["W_in"], inputs[i] + noise_in) +
np.dot(model["W_fb"], outputs[i-1] + noise_out) )
# Shortened version
# z = np.dot(W_, internals[i-1]) + np.dot(model["W_in"], inputs[i])
internals[i] = np.tanh(z) + noise_rc
internals[i] = (1-leak)*internals[i-1] + leak*internals[i]
outputs[i] = np.dot(model["W_out"], internals[i])
model["state"] = internals[1:].T
model["input"] = inputs[1:]
model["output"] = outputs[1:]
error = np.sqrt(np.mean((model["output"] - data["output"])**2))
return error