-
Notifications
You must be signed in to change notification settings - Fork 2
/
model_validator.py
executable file
·324 lines (294 loc) · 10.4 KB
/
model_validator.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
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 02 18:20:40 2015
@author: Konstantin
"""
from scipy import optimize
import numpy as np
import configparser, os, csv
from fabric.api import env, execute, task, get
import cuisine
import pandas
import operator
import pickle
import scipy.stats as stats
#class Parameter:
# def __init__(self, value):
# self.value = value
# def set_val(self, value):
# self.value = value
# def __call__(self):
# return self.value
#
#def fit(function, parameters, y, x=None):
# def f(params):
# i = 0
# for p in parameters:
# p.set_val(params[i])
# i += 1
# return y - function(x)
# if x is None: x = np.arange(y.shape[0])
# p = [param() for param in parameters]
# optimize.leastsq(f, p)
#
#mu = Parameter(7)
#sigma = Parameter(3)
#height = Parameter(5)
#landa = Parameter(2)
#
#def gaussian(x):
# return height() * np.exp(-((x-mu())/sigma())**2)
#def exponential(x):
# return landa * np.exp(-(landa * x))
#
#def weibull(x, c):
# return c / 2 * abs(x)**(c-1) * np.exp(-abs(x)**c)
#
#def norm(x):
# return np.exp(-x**2/2)/np.sqrt(2*np.pi)
#
#def lognorm(x):
# return 1 / (s*x*np.sqrt(2*np.pi)) * np.exp(-1/2*(np.log(x)/s)**2)
# pylint: disable=E1101
@task
def upload_file(remote_location, local_location, sudo=False):
"""
Fabric task to upload a file to a VM.
"""
cuisine.file_upload(remote_location,
local_location, sudo=sudo)
cuisine.file_ensure(remote_location)
@task
def collect_data_files(vm_list):
i = 1
for vm in vm_list:
get('/root/response_time.csv.'+vm,
'response_time_'+str(i)+'.csv')
i += 1
def expectation(data, dist=stats.dweibull):
"""
Computes the expected value of a sample.
"""
return dist(*dist.fit(data)).mean()
def sum_sq(x, x_bar):
"""
Returns the sum of squared difference between
x and x_bar.
"""
return (x - x_bar)**2
def log_num(x, x_bar):
return np.log(x / x_bar) + ((x - x_bar)/x_bar)
def log_den(x, x_bar):
return np.log(x / x_bar)
def calculate_prediction_data():
data = pickle.load(open('valid_predictions', 'r'))
Y_bar = np.mean(data['measured'].copy())
y_var = np.apply_along_axis(log_den,
0,
data['measured'],
Y_bar)
y_var2 = np.apply_along_axis(sum_sq,
0,
data['measured'],
Y_bar)
y_var = y_var.cumsum()[-1]
y_var2 = y_var2.cumsum()[-1]
R_squared_list = []
regres_list = []
i = 0
for el in data.columns:
if i == 3:
# break
print y_var2
# Y_bar_z = np.mean(data[el].copy())
regres_var = np.apply_along_axis(sum_sq,
0,
data[el],
Y_bar)
regres_var = regres_var.cumsum()[-1]
regres_list.append(regres_var)
R_squared = y_var2/regres_var
if R_squared > 1.0:
R_squared = (1.0 / R_squared)
print "======%s" % R_squared
R_squared_list.append(R_squared)
elif i == 4:
# break
print y_var2
# Y_bar_z = np.mean(data[el].copy())
regres_var = np.apply_along_axis(sum_sq,
0,
data[el],
Y_bar)
regres_var = regres_var.cumsum()[-1]
regres_list.append(regres_var)
R_squared = y_var2/regres_var
if R_squared > 1.0:
R_squared = (1.0 / R_squared)
print "======%s" % R_squared
R_squared_list.append(R_squared)
else:
print y_var
# Y_bar_z = np.mean(data[el].copy())
regres_var = np.apply_along_axis(log_num,
0,
data[el],
Y_bar)
regres_var = regres_var.cumsum()[-1]
regres_list.append(regres_var)
R_squared = 1 - abs(y_var/regres_var)
print "======%s" % R_squared
R_squared_list.append(R_squared)
i += 1
print R_squared_list
print regres_list
print y_var
R_squared_list = np.array(R_squared_list, dtype='float64')
# R_squared_list = pandas.DataFrame(R_squared_list)
print data
data.loc[len(data)] = R_squared_list
# data = np.hstack((data,R_squared_list))
pickle.dump(data, open('valid_predictions2', 'w'))
np.savetxt('valid_predictions2.csv', data,
fmt='%.4f', delimiter=';')
with open('valid_predictions2.csv', 'ab') as f:
writer = csv.writer(f, delimiter=';')
writer.writerow(R_squared_list)
writer.writerow(data.columns)
def write_prediction_data(data, ratings):
n = len(data)
print n
rates = sorted(ratings.keys())
for el in rates:
preds = get_predictions(ratings, el, n)
data = np.vstack((data, preds))
data = data.transpose()
data = pandas.DataFrame(data=data, dtype='float64')
np.savetxt('valid_predictions.csv', data,
fmt='%.4f', delimiter=';')
names = ['measured']
[names.append(el) for el in rates]
print names
data.columns = names
pickle.dump(data, open('valid_predictions', 'w'))
# np.savetxt('predictions.csv', arr, fmt='%.4f', delimiter=';')
def read_data_from_files():
"""
Get number of failure rates from failure rates file.
"""
f_rates = []
with open('f_rates.csv', 'rb') as f:
reader = csv.reader(f, delimiter=';', quotechar='|')
f_rates = [row[0] for row in reader]
return f_rates
def fit_model(data, model_name, ratings):
n = len(data)
if model_name == 'expon':
params = convert_string_to_tuple(ratings['expon'][0][0])
print params
std_func = stats.expon.rvs(size=n,
loc=params[0],
scale=params[1])
elif model_name == 'dweibull':
params = convert_string_to_tuple(ratings['dweibull'][0][0])
print params
std_func = stats.dweibull.rvs(params[0],
loc=params[1],
scale=params[2],
size=n)
elif model_name == 'norm':
params = convert_string_to_tuple(ratings['norm'][0][0])
print params
std_func = stats.norm.rvs(loc=params[0],
scale=params[1],
size=n)
elif model_name == 'lognorm':
params = convert_string_to_tuple(ratings['lognorm'][0][0])
print params
std_func = stats.lognorm.rvs(params[0],
loc=params[1],
scale=params[2],
size=n)
std_func.sort()
test_vals = stats.ks_2samp(data, std_func)
result = [test for test in test_vals]
result.append(params)
result.append(std_func)
return result
def convert_string_to_tuple(ratings_string):
"""
Helper method to convert a Python string to a tuple.
"""
result_tuple = ratings_string.split(', ')
result_tuple[0] = result_tuple[0].lstrip('(')
result_tuple[-1] = result_tuple[-1].rstrip(')')
result_tuple = tuple([float(el) for el in result_tuple])
return result_tuple
def rank_models(ratings):
sorted_by_stat = sorted(ratings.items(),
key=operator.itemgetter(1))
return [element[0] for element in sorted_by_stat]
def get_models():
with open('fitted_models.csv', 'rb') as f:
reader = csv.reader(f, delimiter=';')
data = {}
for row in reader:
data.update({row[0]: [row[1:]]})
# data = [row for row in reader]
return data
def write_results(ranking, ratings):
with open('validated_models.csv', 'wb') as f:
writer = csv.writer(f, delimiter=';')
for dist in ranking:
writer.writerow([dist, ratings[dist][2],
ratings[dist][0], ratings[dist][1]
])
def get_predictions(ratings, model_name, size):
"""
Computes predicted random values depending on type
and parameters of the distribution.
"""
if(model_name == 'expon'):
preds = stats.expon.rvs(ratings['expon'][2][0],
ratings['expon'][2][1],
size=size)
elif(model_name == 'dweibull'):
preds = stats.dweibull.rvs(ratings['dweibull'][2][0],
ratings['dweibull'][2][1],
ratings['dweibull'][2][2],
size=size)
elif(model_name == 'norm'):
preds = stats.norm.rvs(ratings['norm'][2][0],
ratings['norm'][2][1],
size=size)
elif(model_name == 'lognorm'):
preds = stats.lognorm.rvs(ratings['lognorm'][2][0],
ratings['lognorm'][2][1],
ratings['lognorm'][2][2],
size=size)
preds = np.apply_along_axis(abs, 0, preds)
preds = np.apply_along_axis(sorted, 0, preds)
return preds
def fit_models():
"""
Gets fitted models and checks them via KS-test. Computes
R-squared as goodness of fit measurements.
"""
#if __name__ == "__main__":
f_rates = read_data_from_files()
f_rates = sorted(f_rates)
print f_rates
data = np.array(f_rates, dtype='float64')
data = data/1500
n = len(data)
data.sort()
ratings = get_models()
[ratings.update({key : fit_model(data, key, ratings)})
for key
in ratings.keys()]
ranking = rank_models(ratings)
write_results(ranking, ratings)
write_prediction_data(data, ratings)
calculate_prediction_data()
if __name__ == "__main__":
fit_models()