-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathobjlearner.py
More file actions
401 lines (353 loc) · 15.8 KB
/
Copy pathobjlearner.py
File metadata and controls
401 lines (353 loc) · 15.8 KB
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
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
"""Implements decorators for objective functions used in calibrations.
This module defines the three decorator classes:
* ObjectiveCounter - counts the number of objective function calls.
* ObjectiveSaver - saves the input-output pairs fo the objective function calls.
* ObjectiveLearner - provides machine learning (linear regression) and sensitivity analysis.
"""
import numpy as np
import pandas as pd
from sklearn import linear_model
from sklearn.svm import SVR
#import SALib
from SALib.analyze import sobol,morris,delta,fast,rbd_fast
from SALib.sample import saltelli,morris,latin,fast_sampler
class ObjectiveCounter(object):
"""Counts the number of objective function calls.
This class is to used a decorator of the objective function in calibrations and
is used to count the number of function calls.
Attributes:
count (int): The number of objective function calls.
"""
count = 0
_objective_function = None
def __init__(self, objective_function):
"""Initialize the ObjectiveCounter.
Args:
objective_function (function): The objective function.
"""
self._objective_function = objective_function
def __call__(self, theta):
"""ObjectiveCounter call that wraps of the objective function.
Args:
theta (numpy.ndarray): The parameter vector to be evaluated by the
objective function.
"""
objective = self._objective_function(theta)
self.count += 1
return objective
class ObjectiveSaver(ObjectiveCounter):
"""Saves the input-output pairs fo the objective function calls.
This class is to used a decorator of the objective function in calibrations and
is used to save the input and outputs of calls to the objective function.
Attributes:
count (int): The number of objective function calls.
objective_theta (pandas.DataFrame): The objective function values and the input
parameter vectors.
"""
_objective_theta = None
def __init__(self, objective_function):
"""Initialize the ObjectiveSaver.
Args:
objective_function (function): The objective function.
"""
self._objective_function = objective_function
self._objective_theta = list()
def __call__(self, theta):
"""ObjectiveSaver call that wraps of the objective function.
Args:
theta (numpy.ndarray): The parameter vector to be evaluated by the
objective function.
"""
objective = self._objective_function(theta)
dpd = dict({'objective': objective, })
for k,val in enumerate(theta):
dpd[k] = val
self._objective_theta.append(dpd)
self.count += 1
return objective
def write_csv(self, prefix='objective_data'):
"""Write the objective function and parameter vector DataFrame values to a csv file.
"""
objective_theta = self.objective_theta
objective_theta.to_csv(prefix+".csv", compression='zip')
return
def write_npy(self, prefix='objective_data'):
"""Write the objective function and parameter vector DataFrame values to a NumPy npy file.
"""
objective_theta = self.objective_theta
np.save(prefix, objective_theta.values, allow_pickle=False)
return
@property
def objective_theta(self):
"""pandas.DataFrame: objective function and parameter vector values.
"""
return pd.DataFrame(self._objective_theta)
class ObjectiveLearner(ObjectiveSaver):
"""Provides machine learning (linear regression) and sensitivity analysis.
This class is used as a decorator of the objective function in calibrations and
is used to save the input and outputs of calls to the objective function while
providing functions to run machine learning (linear regression) and
sensitivity analyses of the objective function.
Attributes:
count (int): The number of objective function calls.
objective_theta (pandas.DataFrame): The objective function values and the input
parameter vectors.
"""
#def __init__(self, objective_function):
# super(ObjectiveSaver, self).__init__(objective_function)
#def __call__(self, theta):
# return super(ObjectiveSaver, self).__call__(theta)
def __init__(self, objective_function):
"""Initialize the ObjectiveLearner.
Args:
objective_function (function): The objective function.
"""
self._objective_function = objective_function
self._objective_theta = list()
def __call__(self, theta):
"""ObjectiveLearner call that wraps of the objective function.
Args:
theta (numpy.ndarray): The parameter vector to be evaluated by the
objective function.
"""
objective = self._objective_function(theta)
dpd = dict({'objective': objective, })
for k,val in enumerate(theta):
dpd[k] = val
self._objective_theta.append(dpd)
self.count += 1
return objective
def best_data(self, n_points=100, cost=True):
"""Gets the set of highest objective and parameter data.
"""
# Load the dataset -- panda DataFrame
objective_theta = self.objective_theta
# Sort
objective_theta.sort_values(by=['objective'], inplace=True)
# Split into X and Y
# X is set of theta vectors
idx_X = objective_theta.columns[1:]
X = objective_theta[idx_X]
# y is the objective
y = objective_theta['objective'].to_numpy()
if cost:
X_best = X[:n_points]
y_best = y[:n_points]
else:
X_best = X[-n_points:]
y_best = y[-n_points:]
return X_best.to_numpy(), y_best
def split_data(self):
"""Splits the objective and paramter data into training and test sets.
"""
# Load the dataset -- panda DataFrame
objective_theta = self.objective_theta
# Shuffle -- https://stackoverflow.com/questions/29576430/shuffle-dataframe-rows
objective_theta = objective_theta.sample(frac=1).reset_index(drop=True)
# Split into X and Y
# X is set of theta vectors
idx_X = objective_theta.columns[1:]
X = objective_theta[idx_X]
# y is the objective
y = objective_theta['objective'].to_numpy()
n_y = len(y)
# Split into training/testing sets
tenp = int(n_y*0.10)
X_train = X[:-tenp]
X_test = X[-tenp:]
y_train = y[:-tenp]
y_test = y[-tenp:]
return X_train, X_test, y_train, y_test
def _linear_regression(self, model, *args, **kwargs):
"""Runs linear regression of the objective function against the parameters.
This function estimates the coefficients and the explained variance
score for a linear least squares fit of the objective function vs. the
input parameters using the given regression model class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
X_train, X_test, y_train, y_test = self.split_data()
# Initialize the model
regr = model(*args, **kwargs)
# Train the model
regr.fit(X_train, y_train)
# Score the predictions -- score function is the explained variance score.
ev_score = regr.score(X_test, y_test)
return regr.coef_, ev_score
def least_squares(self, *args, **kwargs):
"""Least squares linear regression of the objective function against the parameters.
This function estimates the coefficients and the explained variance
score for a linear least squares fit of the objective function vs. the
input parameters using the LinearRegression class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
return self._linear_regression(linear_model.LinearRegression, *args, **kwargs)
def ridge(self, *args, **kwargs):
"""Ridge regression of the objective function against the parameters.
This function estimates the coefficients and the explained variance
score for a Ridge regression fit of the objective function vs. the
input parameters using the Ridge class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
return self._linear_regression(linear_model.Ridge, *args, **kwargs)
def lasso(self, *args, **kwargs):
"""Lasso regression of the objective function against the parameters.
This function estimates the coefficients and the explained variance
score for a Lasso regression fit of the objective function vs. the
input parameters using the Lasso class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
return self._linear_regression(linear_model.Lasso, *args, **kwargs)
def linear_svr(self, *args, **kwargs):
"""Linear Support Vector Regression (SVR) of the objective function against the parameters.
This function estimates the coefficients and the explained variance
score for a SVR fit of the objective function vs. the
input parameters using the SVR class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
if 'gamma' not in kwargs.keys():
kwargs['gamma'] = 'auto'
kwargs['kernel'] = 'linear'
return self._linear_regression(SVR, *args, **kwargs)
def harmonic_local_optimum_sensitivity(self, cost=True):
"""Sensitivity measure around the optimum of the objective function from regression.
This function estimates the coefficients and the explained variance
score for a linear least squares fit of the objective function vs. the
input parameters using the LinearRegression class from scikit-learn.
Returns:
tuple(numpy.ndarray, float): coefficients, explained_variance_score.
"""
X_best, y_best = self.best_data(n_points=int(0.10*self.count), cost=cost)
if cost:
X_diff = X_best - X_best[0]
#print(X_best[-1])
y_diff = y_best - y_best.min()
else:
X_diff = X_best - X_best[-1]
#print(X_best[-1])
y_diff = y_best - y_best.max()
#print(y_diff)
X_sq = X_diff**2
X_sq = X_sq/X_sq.max()
#print(X_sq)
# Initialize the model -- Let's use Lasso with large alpha
regr = linear_model.Lasso(alpha=0.25, fit_intercept=False)
#regr = linear_model.LinearRegression()
# Train the model
regr.fit(X_sq, y_diff)
coef = np.abs(regr.coef_)
coef/coef.sum()
fmask = coef < 0.001
coef[fmask] = 0.
return coef/coef.sum()
def _sensitivity_prep(self):
# Load the dataset -- pandas DataFrame
objective_theta = self.objective_theta
#objective_theta.sort_values(by=['objective'], inplace=True)
objective_theta.sample(frac=1).reset_index(drop=True)
# Split into X and Y
# X is set of theta vectors
idx_X = objective_theta.columns[1:]
X = objective_theta[idx_X].to_numpy()
# y is the objective
y = objective_theta['objective'].to_numpy()
n_X = len(X[0])
names = list()
bounds = list()
for i in range(n_X):
X_i = X[:,i]
X_i_max = X_i.max()
X_i_min = X_i.min()
names.append(i)
bound = list([X_i_min, X_i_max])
bounds.append(bound)
problem = dict({'num_vars': n_X, 'names': names, 'bounds': bounds})
return X, y, problem
def _closest_points(self, problem, X, y, samples):
n_samples = len(samples)
X_s = np.zeros((n_samples,problem['num_vars']))
y_s = np.zeros(n_samples)
for i,theta in enumerate(samples):
dists = np.linalg.norm(X - theta, axis=1)
idx = np.argmin(dists)
#print(theta, X[idx], dists[idx])
X_s[i] = X[idx]
y_s[i] = y[idx]
return X_s, y_s
def sobol(self):
"""Sobol sensitivity of the objective function.
This function estimates the Sobol sensitivity indicies of the
objective function with changes in the parameters using SALib:
https://salib.readthedocs.io/en/latest/api.html#sobol-sensitivity-analysis
Returns:
dict: sensitivity indices of parameters; dict has keys 'S1',
'S1_conf', 'ST', and 'ST_conf'
"""
X, y, problem = self._sensitivity_prep()
n_sample = 2000
param_values = saltelli.sample(problem, n_sample)
X_s, y_s = self._closest_points(problem, X, y, param_values)
Si = sobol.analyze(problem, y_s)
return Si
def morris(self):
"""Morris Method sensitivity of the objective function.
This function estimates the sensitivity with the Morris Method of the
objective function with changes in the parameters using SALib:
https://salib.readthedocs.io/en/latest/api.html#method-of-morris
Returns:
dict: sensitivity values of parameters; dict has keys 'mu',
'mu_star', 'sigma', and 'mu_star_conf'
"""
X, y, problem = self._sensitivity_prep()
n_sample = 2000
param_values = morris.sample(problem, n_sample)
X_s, y_s = self._closest_points(problem, X, y, param_values)
Si = morris.analyze(problem, X_s, y_s)
return Si
def delta(self):
"""Morris Method sensitivity of the objective function.
This function estimates the sensitivity with the Morris Method of the
objective function with changes in the parameters using SALib:
https://salib.readthedocs.io/en/latest/api.html#delta-moment-independent-measure
Returns:
dict: sensitivity values of parameters; dict has keys 'delta',
'delta_conf', 'S1', and 'S1_conf'
"""
X, y, problem = self._sensitivity_prep()
n_sample = 2000
param_values = latin.sample(problem, n_sample)
X_s, y_s = self._closest_points(problem, X, y, param_values)
Si = delta.analyze(problem, X_s, y_s)
return Si
def fast(self):
"""FAST sensitivity analysis of the objective function.
This function estimates the sensitivity with the FAST method of the
objective function with changes in the parameters using SALib:
https://salib.readthedocs.io/en/latest/api.html#fast-fourier-amplitude-sensitivity-test
Returns:
dict: sensitivity values of parameters; dict has keys 'S1' and 'ST'
"""
X, y, problem = self._sensitivity_prep()
n_sample = 2000
param_values = fast_sampler.sample(problem, n_sample)
X_s, y_s = self._closest_points(problem, X, y, param_values)
Si = fast.analyze(problem, y_s)
return Si
def rbd_fast(self):
"""RBD-FAST sensitivity analysis of the objective function.
This function estimates the sensitivity with the RBD-FAST method of the
objective function with changes in the parameters using SALib:
https://salib.readthedocs.io/en/latest/api.html#rbd-fast-random-balance-designs-fourier-amplitude-sensitivity-test
Returns:
dict: sensitivity values of parameters; dict has keys 'S1'
"""
X, y, problem = self._sensitivity_prep()
n_sample = 2000
param_values = latin.sample(problem, n_sample)
X_s, y_s = self._closest_points(problem, X, y, param_values)
Si = rbd_fast.analyze(problem, X_s, y_s)
return Si