-
Notifications
You must be signed in to change notification settings - Fork 1
/
Prosjektoppgave1barealpha.py
248 lines (211 loc) · 8.04 KB
/
Prosjektoppgave1barealpha.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from scipy.stats import gamma
import time
from numba import njit
@njit
def learning_rule(s1,s2,Ap,Am,taup,taum,t,i,binsize):
'''
5.8 in article (typo in article, should be negative exponent for e)
s1,s2 : binary values for the different time bins for neuron 1 and 2 respectively
t : numpy array with the measured time points
Ap,Am,taup,taum : learning rule parameters
'''
l = i - np.int(np.ceil(10*taup / binsize))
return s2[i-1]*np.sum(s1[max([l,0]):i]*Ap*np.exp((t[max([l,0]):i]-max(t))/taup)) - s1[i-1]*np.sum(s2[max([l,0]):i]*Am*np.exp((t[max([l,0]):i]-max(t))/taum))
def logit(x):
return np.log(x/(1-x))
def inverse_logit(x):
return np.exp(x)/(1+np.exp(x))
def generative(Ap,Am,taup,taum,b1,b2,w0,std,seconds,binsize):
'''time and binsize measured in seconds'''
iterations = np.int(seconds/binsize)
t,W,s1,s2 = np.zeros(iterations),np.zeros(iterations),np.zeros(iterations),np.zeros(iterations)
W[0] = w0 #Initial value for weights
s1[0] = np.random.binomial(1,inverse_logit(b1)) #5.4 in article, generate spike/not for neuron 1
for i in range(1,iterations):
s2[i] = np.random.binomial(1,inverse_logit(W[i-1]*s1[i-1]+b2)) #5.5 in article, spike/not neuron 2
lr = learning_rule(s1,s2,Ap,Am,taup,taum,t,i,binsize)
W[i] = W[i-1] + lr + np.random.normal(0,std) #updating weights, as in 5.8 in article
s1[i] = np.random.binomial(1,inverse_logit(b1)) #5.4
t[i] = binsize*i #list with times (start time of current bin)
return(s1,s2,t,W)
def plot_gen_weight(t,W):
plt.figure()
plt.title('Weight trajectory')
plt.plot(t,W)
plt.xlabel('Time')
plt.ylabel('Weight')
#plt.legend()
plt.show()
def infer_b1(s1):
return logit(np.sum(s1)/len(s1)) #5.23
def normalize(vp): #normalisere vekter
return vp/np.sum(vp)
def perplexity_func(vp_normalized,P):
h = -np.sum(vp_normalized*np.log(vp_normalized))
return np.exp(h)/P
def resampling(vp_normalized,wp,P):
wp_new = np.copy(wp)
indexes = np.linspace(0,P-1,P)
resampling_indexes = np.random.choice(indexes,P,p=vp_normalized)
for i in range(P):
wp_new[i] = np.copy(wp[resampling_indexes.astype(int)[i]])
return wp_new
def likelihood_step(s1,s2,w,b2): #p(s2 given s1,w,theta)
return inverse_logit(w*s1 + b2)**(s2) * (1-inverse_logit(w*s1 + b2))**(1-s2)
def parameter_priors(shapes,rates):
return np.array([(np.random.gamma(shapes[i],1/rates[i])) for i in range(len(shapes))])
def proposal_step(shapes,theta):
return np.random.gamma(shapes,theta/shapes)
def adjust_variance(theta, U,it,shapes):
means = theta[-U:].mean(0)
var_new = 0
while (var_new == 0):
var_new = theta[-U:].var(0)*(2.4**2)
U += 50
if U > it:
return shapes, np.random.gamma(shapes,theta[-1]/shapes)
new_shapes = means**2 / var_new
proposal = np.random.gamma(new_shapes,theta[-1]/new_shapes)
return new_shapes,proposal
def ratio(prob_old,prob_next,shapes_prior,rates_prior,shapes,theta_next,theta_prior):
spike_prob_ratio = prob_next / prob_old
prior_ratio = gamma.pdf(theta_next,a=shapes_prior,scale=1/rates_prior)/\
gamma.pdf(theta_prior,a=shapes_prior,scale=1/rates_prior)
proposal_ratio = gamma.pdf(theta_prior,a=shapes,scale=theta_next/shapes)/\
gamma.pdf(theta_next,a=shapes,scale=theta_prior/shapes)
return spike_prob_ratio * prior_ratio * proposal_ratio
def scaled2_spike_prob(old,new):
print(old,new)
return np.exp(old - min(old,new)),np.exp(new - min(old,new))
def infer_b2_w0(s1,s2,tol):
'''
Fisher scoring algorithm
'''
beta = [0,0]
x = np.array([np.ones(len(s1)-1),s1[:-1]])
i = 0
score = np.array([np.inf,np.inf])
while(i < 1000 and any(abs(i) > tol for i in score)):
eta = np.matmul(beta,x) #linear predictor
mu = inverse_logit(eta)
score = np.matmul(x,s2[1:] - mu)
hessian_u = mu * (1-mu)
hessian = np.matmul(x*hessian_u,np.transpose(x))
delta = np.matmul(np.linalg.inv(hessian),score)
beta = beta + delta
i += 1
return beta
def particle_filter(w0,b2,theta,s1,s2,std,P,binsize,seconds,tau):
'''
Particle filtering, (doesnt quite work yet, smth with weights vp)
Possible to speed it up?
How to initiate w0 and vp?
'''
timesteps = np.int(seconds/binsize)
t = np.zeros(timesteps)
wp = np.full((P,timesteps),np.float(w0))
vp = np.ones(P)
log_posterior = 0
for i in range(1,timesteps):
v_normalized = normalize(vp)
perplexity = perplexity_func(v_normalized,P)
if perplexity < 0.66:
wp = resampling(v_normalized,wp,P)
vp = np.full(P,1/P)
v_normalized = normalize(vp)
lr = learning_rule(s1,s2,theta,theta*1.05,tau,tau,t,i,binsize)
ls = likelihood_step(s1[i-1],s2[i],wp[:,i-1],b2)
vp = ls*v_normalized
#print(vp)
#vpfull.append(vp)
wp[:,i] = wp[:,i-1] + lr + np.random.normal(0,std,size = P)
log_posterior += np.log(np.sum(vp)/P)
t[i] = i*binsize
return log_posterior,wp
def MHsampler2(w0,b2est,shapes_prior,rates_prior,s1,s2,std,P,binsize,seconds,U,it,tau):
'''
Monte Carlo sampling with particle filtering, algoritme 3
'''
theta_prior = 0.002
theta = np.zeros(it)
theta[0] = np.copy(theta_prior)
shapes = np.copy(shapes_prior)
old_log_post = particle_filter(w0,b2est,theta_prior,s1,s2,std,P,binsize,seconds,tau)[0]
for i in tqdm(range(1,it)):
if (i % U == 0):
theta_change = np.copy(theta[:i])
shapes, theta_next = adjust_variance(theta_change,U,it,shapes)
else:
theta_next = proposal_step(shapes,theta_prior)
new_log_post = particle_filter(w0,b2est,theta_next,s1,s2,std,P,binsize,seconds,tau)[0]
print('old:', theta_prior)
print('new:', theta_next)
prob_old,prob_next = scaled2_spike_prob(old_log_post,new_log_post)
r = ratio(prob_old,prob_next,shapes_prior,rates_prior,shapes,theta_next,theta_prior)
print('r:',r)
choice = np.int(np.random.choice([1,0], 1, p=[min(1,r),1-min(1,r)]))
theta_choice = [np.copy(theta_prior),np.copy(theta_next)][choice == 1]
print('choice:',theta_choice)
theta[i] = theta_choice
theta_prior = np.copy(theta_choice)
old_log_post = [np.copy(old_log_post),np.copy(new_log_post)][choice == 1]
return theta
'''
PARAMETERS AND RUNNING OF ALGORITHM :
'''
std = 0.0001
w0 = 1.0
b1 = -2
b2 = -2
Ap = 0.005
Am = Ap*1.05
tau = 20.0e-3
seconds = 120.0
binsize = 1/200.0
P = 500
U = 100
it = 100
shapes_prior = 4
rates_prior = 50
fast_tau = 0.02
s1,s2,t,W = generative(Ap,Am,tau,tau,b1,b2,w0,std,seconds,binsize)
b1est = infer_b1(s1)
w0est = infer_b2_w0(s1[:2000],s2[:2000],1e-10)[1]
b2est = infer_b2_w0(s1,s2,1e-10)[0]
Alist = MHsampler2(w0est,b2est,shapes_prior,rates_prior,s1,s2,std,P,binsize,seconds,U,it,fast_tau)
np.save('s1_1',s1)
np.save('s2_1',s2)
np.save('t_1',t)
np.save('w0est_1',w0est)
np.save('b1est_1',b1est)
np.save('b2est_1',b2est)
np.save('Alist',Alist)
plt.figure()
plt.title('A')
plt.xlabel('Iterations')
plt.ylabel('Ap')
plt.plot(np.linspace(1,it,it),Alist,'ro')
plt.savefig('Aen')
"""
particle_trajectories = []
real_trajectories = []
Aps = [0.003,0.0035,0.004,0.0045,0.005,0.0055,0.006,0.0065,0.007]
loglikes = []
for i in tqdm(range(5)):
s1temp,s2temp,t,wtemp = generative(Ap,Am, tau,tau , b1, b2, w0, std, seconds, binsize)
b1est = infer_b1(s1temp)
w0est= infer_b2_w0(s1temp[:2000],s2temp[:2000],1e-10)[1]
b2est = infer_b2_w0(s1temp,s2temp,1e-10)[0]
loglikes_temp = []
particle_traj_temp = []
real_trajectories.append(wtemp)
for j in range(len(Aps)):
ll, tr = particle_filter(w0est, b2est, Aps[j], s1temp, s2temp, std, 200, binsize, seconds, tau)
loglikes_temp.append(ll)
particle_traj_temp.append(tr)
loglikes.append(loglikes_temp)
particle_trajectories.append(particle_traj_temp)
"""