-
Notifications
You must be signed in to change notification settings - Fork 1
/
ensemble.py
337 lines (300 loc) · 10.6 KB
/
ensemble.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
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
# -*- coding: utf-8 -*-
##########################################
#Renato Stoffalette Joao
#
##########################################
__author__ = "Renato Stoffalette Joao(renatosjoao@gmail.com)"
__version__ = "$Revision: 0.1 $"
__date__ = "$Date: 2014// $"
__copyright__ = "Copyright (c) 2013 Renato SJ"
__license__ = "Python"
import _mypath
import os.path
import classifier as clf
import feature as ft
import xplutil
import numpy as np
import trioswindow as triosw
import pylab
import matplotlib.pyplot as plt
import subprocess
import shlex
from scipy import misc
class Ensemble:
def __init__(self, xpl_data, win, n_features, n_iterations, error_list, mae_list, dirpath):
self.xpl_data = xpl_data
self.win = win
self.n_features = n_features
self.n_iterations = n_iterations
self.error_list = error_list
self.mae_list = mae_list
self.dirpath = dirpath
def train(xpl_data, n_features, n_iterations, dirpath):
Xdata = xpl_data.data
win = xpl_data.windata
# copies frequency data as original frequencies are used towards the end to estimate training error
w0 = xpl_data.freq0.copy()
w1 = xpl_data.freq1.copy()
error_list = []
mae_list = []
GVector = []
DEC = np.zeros(w0.shape)
total = float(np.sum([w0, w1]))
w0_train = w0/total
w1_train = w1/total
file = open(dirpath+"MAE_training.txt", "w")
for i in range(n_iterations):
indices, feature_list, _ = ft.cmim(Xdata, w0, w1, n_features)
indices = np.sort(indices)
triosw.to_window_file(indices, xpl_data.winshape, dirpath+"window_"+str(i)+".win")
triosw.to_image_file(indices,xpl_data.winshape, dirpath+"window_"+str(i)+".png", scale=8)
total = float(np.sum([w0, w1]))
w0 = w0/total
w1 = w1/total
w0, w1, updated_decision, cls_error = clf.apply_feature_selection(Xdata, indices, w0, w1)
unique_array, unique_index = clf._apply_projection(Xdata, indices)
xplutil.write_minterm_file(dirpath+"mtm"+str(i),indices, xpl_data.winshape, unique_array,updated_decision[unique_index])
#str_to_file = "Classification error for iteration " + str(i) +" = "+ str(cls_error) +".\n"
#file.write(str_to_file)
error_list.append(cls_error)
bt = clf.beta_factor(cls_error)
gam = np.log(1/bt)
GVector = np.append(GVector,gam)
#DEC represents the Decision Table. Each column represents the decision for an iteration
DEC = np.column_stack((DEC,updated_decision))
aux_dec = DEC
aux_dec = np.delete(aux_dec,0, axis=1)
hypothesis = clf.adaboost_decision(aux_dec, GVector)
MAE_t = clf.mae_from_distribution(hypothesis,w0_train, w1_train)
mae_list = np.append(mae_list,MAE_t)
str_to_file = str(i) +", "+ str(MAE_t) +"\n"
file.write(str_to_file)
#Must delete the first column because it contains only Zeros as it was initialized with np.zeros()
DEC = np.delete(DEC,0, axis=1)
hypothesis = clf.adaboost_decision(DEC, GVector)
#MAE = clf.mae_from_distribution(hypothesis,w0_train, w1_train)
#str_to_file = "Final MAE = "+str(MAE)
#file.write(str(MAE))
file.close()
plot_MAE(np.array(range(n_iterations)), np.array(mae_list), dirpath)
return Ensemble(xpl_data, win, n_features, n_iterations, error_list, mae_list,dirpath)
def write_min_empirical_error(filename, value):
f = open(filename, "w")
f.write(str(value))
f.close()
return 0
def min_empirical_error(xpldata):
"""
Given the data originally from a XPL file the minimal empirical error
is a value threshold for overfitting reference.
Parameters
----------
xpldata : ExampleData(data, freq0, freq1, winshape, windata, filename)
Same as xplutil returns.
Returns
-------
err : double
The error value.
"""
w0, w1 = clf.normalize_table(xpldata.freq0, xpldata.freq1)
err = clf.error(w0,w1)
return err
def mae(imageset_list):
"""
Given the list of observed and the ideal images data we calculate the
mae as an improvement threshold.
Parameters
----------
imageset_list: list
A list containing the imageset to be used for mae calculation.
i.e.
[('./dataset-map/map1bin.pnm', './dataset-map/map1bin.ide.pnm', './dataset-map/map1bin.pnm'),
('./dataset-map/map2bin.pnm', './dataset-map/map2bin.ide.pnm', './dataset-map/map2bin.pnm'),
('./dataset-map/map3bin.pnm', './dataset-map/map3bin.ide.pnm', './dataset-map/map3bin.pnm')]
Returns
-------
value : double
"""
sum_nonzero = 0.0
total_pix = 0.0
for row in imageset_list:
ideal = misc.imread(row[1])
observed = misc.imread(row[0])
subset = np.absolute(ideal - observed)
nonzero = np.count_nonzero(subset)
sum_nonzero += nonzero
total_pix += subset.size
value = sum_nonzero/total_pix
return value
def plot_MAE(xaxis, yaxis, dir):
""" This is a function to plot the MAE per iteration graph.
Parameters
----------
xaxis : array-like of shape = [n, 1]
Iterations
yaxis : array-like of shape = [n, 1]
MAEs
"""
fig = plt.figure()
plt.title('MAE per iteration')
plt.xlabel('Iteration (t)')
plt.ylabel('MAE')
plt.grid(True)
plt.plot(xaxis, yaxis)
fig.savefig(dir +'MAE_trainning.png', dpi=fig.dpi)
def predict(self, Xdata):
return 0 #( TO BE IMPLEMENTED)
def build_xpl(imgset, win, output):
"""
Writes a xpl file to disk according to the parameters
Parameters
----------
imgset : string
The image set path for creating the XPL file.
win : string
The path to the win file used to create the XPL file.
output : string
The path to the output XPL file.
Returns:
--------
: bolean value
True if the processing is sucessful
"""
#trios_build_xpl must not be hardcoded !!!
cmd = "trios_build_xpl %s %s %s" %(imgset, win, output)
cmd = shlex.split(cmd)
process = subprocess.call(cmd)
if process == 0:
return True
else:
raise Exception('Build XPL operation failed')
def trios_build(win, imgset, fname):
"""
Runs the training process for the Image Operator using the imageset passed in the parameters.
"""
cmd = "trios_build single BB %s %s %s" %(win, imgset, fname)
cmd = shlex.split(cmd)
process = subprocess.call(cmd)
if process == 0:
return True
else:
raise Exception('Build operator failed')
def trios_build_mtm(win, imgset, fname):
"""
Creates a MTM file using the imageset and window given as arguments.
"""
cmd = "trios_build_mtm %s %s %s" %(win, imgset, fname)
cmd = shlex.split(cmd)
process = subprocess.call(cmd)
if process == 0:
return True
else:
raise Exception('Creating mtm operation failed')
def build_operators(dirpath, n_iterations):
for i in range(n_iterations):
window = dirpath+"window_"+str(i)+".win"
mtm = dirpath+"mtm"+str(i)
output = dirpath+"mtm"+str(i)+"-op"
build_operator(window, mtm, output)
return 0
def build_operator(win, mtm, output):
"""
Runs the build operator process using the mimtermfile passed in the parameters.
Parameters
----------
win : string
The path to the win file used to create the image operator.
mtm : string
The path to the mimterm file used to create the image operator.
output : string
The path to the output image operator.
"""
#trios_build_operator must not be hardcoded !!!
cmd = "trios_build_operator %s %s %s" %(win, mtm, output)
cmd = shlex.split(cmd)
process = subprocess.call(cmd)
if process == 0:
return True
else:
raise Exception('Build operator failed')
def build_operator_combination(imgset, op_to_combine, op_dir, fname):
#op_to_combine i.e 1,2,3 or 2,3,4 or 3,4,5
operators_list = []
outputfname = fname
for i in op_to_combine:
operators_list.append("mtm"+str(i)+"-op")
p = build_2level(imgset, operators_list, op_dir, outputfname)
if p == True:
return True
else:
raise Exception('Build operator failed')
def build_2level(imgset, operators, op_dir, fname):
"""
This function builds the 2-level operator by running trios_build tool
with the flag 'combine'.
Parameters
----------
imgset : string
The image set path for training the 2-level operator.
operators : string[]
List of operators that will be combined to create the 2-level operator.
op_dir : string
The directory path related to where the operators are located.
fname : string
The 2-level image operator path after combining the first level operators.
Returns:
--------
: bolean value
True if the processing is sucessful
"""
ops = " ".join(op_dir+o for o in operators)
#trios_build must not be hardcoded !!!
cmd = "trios_build combine %s %s %s" %(ops, imgset, fname)
cmd = shlex.split(cmd)
process = subprocess.call(cmd)
if process == 0:
return True
else:
raise Exception('Building Image Operator failed')
def apply_operator(operator_path, img_path, result_path, mask=''):
"""
Apply a trained operator on an image.
Parameters
----------
operator_path : string
The operator path.
img_path : string
The image path on which the operator will be applied.
result_path : string
The image result path after applying the operator.
mask: string
The mask image path. Optional.
Returns:
--------
0 if the processing is sucessful.
"""
#trios_apply must not be hardcoded !!!
cmd = "trios_apply %s %s %s %s"%(operator_path, img_path, result_path, mask)
cmd = shlex.split(cmd)
res = subprocess.call(cmd)
if res != 0:
raise Exception('Applying Image Operator Failed')
return res
def trios_test(operator_path, imgset_path, output):
"""
Calculates the image operator MAE over a image set
operator_path : string
The operator path.
imgset_path : string
The imageset path on which the operator will be applied.
"""
f = open(output, "w")
f2 = open("/dev/null", "w")
cmd = "trios_test %s %s" %(operator_path,imgset_path)
cmd = shlex.split(cmd)
res = subprocess.call(cmd,stdout=f, stderr=f2)
if res != 0:
raise Exception('Operation Failed')
f.close()
f2.close()
return res