File size: 9,590 Bytes
2fc2c1f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
#!/usr/local/bin/python3

# avenir-python: Machine Learning
# Author: Pranab Ghosh
# 
# Licensed under the Apache License, Version 2.0 (the "License"); you
# may not use this file except in compliance with the License. You may
# obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0 
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied. See the License for the specific language governing
# permissions and limitations under the License.

# Package imports
import os
import sys
import matplotlib.pyplot as plt
import numpy as np
import sklearn as sk
from sklearn.neighbors import KDTree
import matplotlib
import random
import jprops
from random import randint
import statistics
sys.path.append(os.path.abspath("../lib"))
from util import *
from mlutil import *
from tnn import *
from stats import *

"""
neural model calibration
"""
class ModelCalibration(object):
	def __init__(self):
		pass
		
	@staticmethod
	def findModelCalibration(model):
		"""
		pmodel calibration
		"""
		FeedForwardNetwork.prepValidate(model)
		FeedForwardNetwork.validateModel(model)
		
		yPred = model.yPred.flatten()
		yActual = model.validOutData.flatten()
		nsamp = len(yActual)
		
		#print(yPred.shape)
		#print(yActual.shape)
		
		nBins = model.config.getIntConfig("calibrate.num.bins")[0]
		prThreshhold = model.config.getFloatConfig("calibrate.pred.prob.thresh")[0]
		
		minConf = yPred.min()
		maxConf = yPred.max()
		bsize = (maxConf - minConf) / nBins
		#print("minConf {:.3f}  maxConf {:.3f}  bsize {:.3f}".format(minConf, maxConf, bsize))
		blist = list(map(lambda i : None, range(nBins)))
		
		#binning
		for yp, ya in zip(yPred, yActual):
			indx = int((yp - minConf) / bsize)
			if indx == nBins:
				indx = nBins - 1
			#print("yp {:.3f}  indx {}".format(yp, indx))
			pair = (yp, ya)
			plist  = blist[indx]
			if plist is None:
				plist = list()
				blist[indx] = plist 
			plist.append(pair)
		 
		x = list()
		y = list()
		yideal = list()
		ece = 0
		mce = 0
		
		# per bin confidence and accuracy
		b = 0
		for plist in blist:
			if plist is not None:
				#confidence
				ypl = list(map(lambda p : p[0], plist))
				ypm = statistics.mean(ypl)
				x.append(ypm)
			
				#accuracy
				ypcount = 0
				for p in plist:
					yp = 1 if p[0] > prThreshhold else 0
					if (yp == 1 and p[1] == 1):
						ypcount += 1
				 
				acc = ypcount / len(plist)
				y.append(acc)
				yideal.append(ypm)
			
				ce = abs(ypm - acc)
				ece += len(plist) * ce
				if ce > mce:
					mce = ce
			else:
				ypm = minConf + (b + 0.5) * bsize
				x.append(ypm)
				yideal.append(ypm)
				y.append(0)
			b += 1
				
		#calibration plot	
		drawPairPlot(x, y, yideal, "confidence", "accuracy", "actual", "ideal")
		
		print("confidence\taccuracy")
		for z in zip(x,y):
			print("{:.3f}\t{:.3f}".format(z[0], z[1]))
		
		
		#expected calibration error
		ece /= nsamp
		print("expected calibration error\t{:.3f}".format(ece))
		print("maximum calibration error\t{:.3f}".format(mce))
	
	
	@staticmethod
	def findModelCalibrationLocal(model):
		"""
		pmodel calibration based k nearest neghbors
		"""
		FeedForwardNetwork.prepValidate(model)
		FeedForwardNetwork.validateModel(model)
		
		yPred = model.yPred.flatten()
		yActual = model.validOutData.flatten()
		nsamp = len(yActual)
		
		neighborCnt =  model.config.getIntConfig("calibrate.num.nearest.neighbors")[0]
		prThreshhold = model.config.getFloatConfig("calibrate.pred.prob.thresh")[0]
		fData = model.validFeatData.numpy()
		tree = KDTree(fData, leaf_size=4)
		
		dist, ind = tree.query(fData, k=neighborCnt)
		calibs = list()
		#all data
		for si, ni in enumerate(ind):
			conf = 0
			ypcount = 0
			#all neighbors
			for i in ni:
				conf += yPred[i]
				yp = 1 if yPred[i] > prThreshhold else 0
				if (yp == 1 and yActual[i] == 1):
					ypcount += 1
			conf /= neighborCnt
			acc = ypcount / neighborCnt
			calib = (si, conf, acc)
			calibs.append(calib)
			
		#descending sort by difference between confidence and accuracy
		calibs = sorted(calibs, key=lambda c : abs(c[1] - c[2]), reverse=True)
		print("local calibration")
		print("conf\taccu\trecord")
		for i in range(19):
			si, conf, acc = calibs[i]
			rec = toStrFromList(fData[si], 3)
			print("{:.3f}\t{:.3f}\t{}".format(conf, acc, rec))

	@staticmethod
	def findModelSharpness(model):
		"""
		pmodel calibration
		"""
		FeedForwardNetwork.prepValidate(model)
		FeedForwardNetwork.validateModel(model)
		
		yPred = model.yPred.flatten()
		yActual = model.validOutData.flatten()
		nsamp = len(yActual)
		
		#print(yPred.shape)
		#print(yActual.shape)
		
		nBins = model.config.getIntConfig("calibrate.num.bins")[0]
		prThreshhold = model.config.getFloatConfig("calibrate.pred.prob.thresh")[0]
		
		minConf = yPred.min()
		maxConf = yPred.max()
		bsize = (maxConf - minConf) / nBins
		#print("minConf {:.3f}  maxConf {:.3f}  bsize {:.3f}".format(minConf, maxConf, bsize))
		blist = list(map(lambda i : None, range(nBins)))
		
		#binning
		for yp, ya in zip(yPred, yActual):
			indx = int((yp - minConf) / bsize)
			if indx == nBins:
				indx = nBins - 1
			#print("yp {:.3f}  indx {}".format(yp, indx))
			pair = (yp, ya)
			plist  = blist[indx]
			if plist is None:
				plist = list()
				blist[indx] = plist 
			plist.append(pair)
		 
		y = list()
		ypgcount = 0
		# per bin confidence and accuracy
		for plist in blist:
			#ypl = list(map(lambda p : p[0], plist))
			#ypm = statistics.mean(ypl)
			#x.append(ypm)
			
			ypcount = 0
			for p in plist:
				yp = 1 if p[0] > prThreshhold else 0
				if (yp == 1 and p[1] == 1):
					ypcount += 1
					ypgcount += 1
				 
			acc = ypcount / len(plist)
			y.append(acc)
		
		print("{} {}".format(ypgcount, nsamp))	
		accg = ypgcount / nsamp
		accgl = [accg] * nBins
		x = list(range(nBins))	
		drawPairPlot(x, y, accgl, "discretized confidence", "accuracy", "local", "global")
		
		contrast = list(map(lambda acc : abs(acc - accg), y))
		contrast = statistics.mean(contrast)
		print("contrast {:.3f}".format(contrast))

"""
neural model robustness
"""
class ModelRobustness(object):
	def __init__(self):
		pass
		
	def localPerformance(self, model, fpath, nsamp, neighborCnt):
		"""
		local performnance sampling
		"""
		
		#load data
		fData, oData = FeedForwardNetwork.prepData(model, fpath)
		#print(type(fData))
		#print(type(oData))
		#print(fData.shape)
		dsize = fData.shape[0]
		ncol = fData.shape[1]
		
		#kdd 
		tree = KDTree(fData, leaf_size=4)		

		scores = list()
		indices = list()
		for _ in range(nsamp):
			indx = randomInt(0, dsize - 1)
			indices.append(indx)
			frow = fData[indx]
			frow = np.reshape(frow, (1, ncol))
			dist, ind = tree.query(frow, k=neighborCnt)
			
			ind = ind[0]
			vfData = fData[ind]	
			voData = oData[ind]	
			
			#print(type(vfData))
			#print(vfData.shape)
			#print(type(voData))
			#print(voData.shape)
			
			model.setValidationData((vfData, voData), False)
			score = FeedForwardNetwork.validateModel(model)
			scores.append(score)
		
		#performance distribution
		m, s = basicStat(scores)
		print("model performance:   mean {:.3f}\tstd dev {:.3f}".format(m,s))	
		drawHist(scores, "model accuracy", "accuracy", "frequency")
		
		#worst performance 
		lscores = sorted(zip(indices, scores), key=lambda s : s[1])
		print(lscores[:5])
		
		lines = getFileLines(fpath, None)
		print("worst performing features regions")
		for i,s in lscores[:5]:
			print("score {:.3f}\t{}".format(s, lines[i]))
			

"""
conformal prediction for regression
"""
class ConformalRegressionPrediction(object):
	def __init__(self):
		self.calibration = dict()
		
	def calibrate(self, ypair, confBound):
		""" n
		calibration for conformal prediction
		"""
		cscores = list()
		ymax = None
		ymin = None
		for yp, ya  in ypair:
			cscore = abs(yp - ya)
			cscores.append(cscore)
			if ymax is None:
				ymax = ya
				ymin = ya
			else:
				ymax = ya if ya > ymax else ymax
				ymin = ya if ya < ymin else ymin
		
		cscores.sort()
		drawHist(cscores, "conformal score distribution", "conformal score",  "frequency", 20)
		cbi = int(confBound * len(cscores))
		scoreConfBound = cscores[cbi]
		self.calibration["scoreConfBound"] = scoreConfBound
		self.calibration["ymin"] = ymin
		self.calibration["ymax"] = ymax
		print(self.calibration)
	
	def saveCalib(self, fPath):
		"""
		saves scoformal score calibration
		"""
		saveObject(self.calibration, fPath)
		
	def restoreCalib(self, fPath):
		"""
		saves scoformal score calibration
		"""
		self.calibration = restoreObject(fPath)
		print(self.calibration)
	
	def getPredRange(self, yp, nstep=100):
		"""
		get prediction range and related data
		"""
		ymin = self.calibration["ymin"]
		ymax = self.calibration["ymax"]
		step = (ymax - ymin) / nstep
		scoreConfBound = self.calibration["scoreConfBound"]
		
		rmin = None
		rmax = None
		rcount = 0
		#print(ymin, ymax, step)
		for ya in np.arange(ymin, ymax, step):
			cscore = abs(yp - ya)
			if cscore < scoreConfBound:
				if rmin is None:
					#lower bound
					rmin = ya
					rmax = ya
				else:
					#keep updating upper bound
					rmax = ya if ya > rmax else rmax
					rcount += 1
			else:
				if rmax is not None	and rcount > 0:
					#past upper bound
					break
		
		res = dict()
		res["predRangeMin"] = rmin
		res["predRangeMax"] = rmax
		accepted = yp >= rmin and yp <= rmax
		res["status"] = "accepted" if accepted else "rejected"
		conf = 1.0 - (rmax - rmin) / (ymax - ymin)
		res["confidence"] = conf
		
		return res