-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRB-parallel-MCMC.py
292 lines (227 loc) · 8.08 KB
/
RB-parallel-MCMC.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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 22 21:10:35 2019
@author: Tobias Schwedes
!/usr/bin/env python3
Script to implement Bayesian logistic regression using using Rao-Blackwellised
parallel MCMC.
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import norm
from Data import DataLoad
from Seed import SeedGen
class RB_BayesianLogReg:
def __init__(
self,
N,
StepSize,
PowerOfTwo,
x0,
InitMean,
InitCov,
Case,
alpha=100.0,
Stream="iid",
):
"""
Implements the Bayesian Logistic Regression based on the
Data sets in ./Data/ by using Rao-Blackwellised
parallel MCMC.
Inputs:
-------
N - int
number of proposals per iteration
StepSize - float
step size for proposed jump in mean
PowerOfTwo - int
Defines size S of seed by S=2**PowerOfTwo-1
x0 - array_like
d-dimensional array; starting value
InitMean - array_like
d-dimensional initial proposal mean
InitCov - array_like
dxd-dimensional initial proposal covariance
Case - string
determines the data used
alpha - float
1./alpha scales prior covariance
Stream - string
either 'cud' or 'iid'; defining what seed is used
"""
#############
# Load Data #
#############
Data = DataLoad(Case)
d = Data.GetDimension()
XX = Data.GetDesignMatrix()
t = Data.GetResponses()
##################################
# Choose stream for Markoc Chain #
##################################
xs = SeedGen(d + 1, PowerOfTwo, Stream)
##################
# Initialisation #
##################
# List of samples to be collected
self.xVals = list()
self.xVals.append(x0)
# Iteration number
NumOfIter = int(int((2**PowerOfTwo - 1) / (d + 1)) * (d + 1) / N)
print("Total number of Iterations = ", NumOfIter)
# Set up acceptance rate array
self.AcceptVals = list()
# Initialise
xI = self.xVals[0]
I = 0
# Weighted Sum and Covariance Arrays
self.WeightedSum = np.zeros((NumOfIter, d))
self.WeightedCov = np.zeros((NumOfIter, d, d))
# Approximate Posterior Mean and Covariance as initial estimates
self.ApprPostMean = InitMean
self.ApprPostCov = InitCov
# Cholesky decomposition of initial Approximate Posterior Covariance
CholApprPostCov = np.linalg.cholesky(self.ApprPostCov)
InvApprPostCov = np.linalg.inv(self.ApprPostCov)
####################
# Start Simulation #
####################
for n in range(NumOfIter):
######################
# Generate proposals #
######################
# Load stream of points in [0,1]^(d+1)
U = xs[n * N : (n + 1) * N, :]
# Sample new proposed States according to multivariate Gaussian
y = self.ApprPostMean + np.dot(
norm.ppf(U[:, :d], loc=np.zeros(d), scale=StepSize), CholApprPostCov
)
# Add current state xI to proposals
Proposals = np.insert(y, 0, xI, axis=0)
########################################################
# Compute probability ratios = weights of RB-estimator #
########################################################
# Compute Log-posterior probabilities
LogPriors = -0.5 * np.dot(
np.dot(Proposals, np.identity(d) / alpha), (Proposals).T
).diagonal(0)
fs = np.dot(XX, Proposals.T)
LogLikelihoods = np.dot(t, fs) - np.sum(np.log(1.0 + np.exp(fs)), axis=0)
LogPosteriors = LogPriors + LogLikelihoods
# Compute Log of transition probabilities
LogK_ni = -0.5 * np.dot(
np.dot(Proposals - self.ApprPostMean, InvApprPostCov / (StepSize**2)),
(Proposals - self.ApprPostMean).T,
).diagonal(0)
LogKs = np.sum(LogK_ni) - LogK_ni # from any state to all others
# Compute weights
LogPstates = LogPosteriors + LogKs
Sorted_LogPstates = np.sort(LogPstates)
LogPstates = LogPstates - (
Sorted_LogPstates[-1]
+ np.log(
1 + np.sum(np.exp(Sorted_LogPstates[:-1] - Sorted_LogPstates[-1]))
)
)
Pstates = np.exp(LogPstates)
########################
# Compute RB-estimates #
########################
# Compute weighted sum as posterior mean estimate
WeightedStates = np.tile(Pstates, (d, 1)) * Proposals.T
self.WeightedSum[n, :] = np.sum(WeightedStates, axis=1).copy()
##################################
# Sample according to RB-weights #
##################################
# Sample N new states
PstatesSum = np.cumsum(Pstates)
Is = np.searchsorted(PstatesSum, U[:, d:].flatten())
xValsNew = Proposals[Is]
self.xVals.append(xValsNew.copy())
# Compute approximate acceptance rate
AcceptValsNew = 1.0 - Pstates[Is]
self.AcceptVals.append(AcceptValsNew)
# Update current state
I = Is[-1]
xI = Proposals[I, :]
def GetSamples(self, BurnIn=0):
"""
Compute samples from posterior
Inputs:
------
BurnIn - int
Burn-In period
Outputs:
-------
Samples - array_like
(Number of samples) x d-dimensional arrayof Samples
"""
Samples = np.concatenate(self.xVals[1:], axis=0)[BurnIn:, :]
return Samples
def GetAcceptRate(self, BurnIn=0):
"""
Compute acceptance rate
Inputs:
------
BurnIn - int
Burn-In period
Outputs:
-------
AcceptRate - float
average acceptance rate
"""
AcceptVals = np.concatenate(self.AcceptVals)[BurnIn:]
AcceptRate = np.mean(AcceptVals)
return AcceptRate
def GetIS_MeanEstimate(self, N, BurnIn=0):
"""
Compute RB estimate
Outputs:
-------
WeightedMean - array_like
d-dimensional array
"""
WeightedMean = np.mean(self.WeightedSum[int(BurnIn / N) :, :], axis=0)
return WeightedMean
def GetIS_FunMeanEstimate(self, N, BurnIn=0):
"""
Compute RB estimate
Outputs:
-------
WeightedMean - array_like
d-dimensional array
"""
WeightedMean = np.mean(self.WeightedFunSum[int(BurnIn / N) :, :], axis=0)
return WeightedMean
def GetIS_CovEstimate(self, N, BurnIn=0):
"""
Compute RB covariance estimate
Outputs:
-------
WeightedCov - d-dimensional array
"""
WeightedCov = np.mean(self.WeightedCov[int(BurnIn / N) :, :, :], axis=0)
return WeightedCov
def GetMarginalHistogram(self, Index=0, BarNum=100, BurnIn=0):
"""
Plot histogram of marginal distribution for posterior
Inputs:
------
Index - int
index of dimension for marginal distribution
BurnIn - int
Burn-In period
Outputs:
-------
Plot
"""
Fig = plt.figure()
SubPlot = Fig.add_subplot(111)
SubPlot.hist(
self.GetSamples(BurnIn)[:, Index],
BarNum,
label="PDF Histogram",
density=True,
)
return Fig