-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlearner.py
2342 lines (1936 loc) · 99.6 KB
/
learner.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
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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
__all__ = ['BaseLearner', 'ELM', 'CELM', 'CMLP']
__version__ = '3.1'
__author__ = 'Jannick Stranghöner'
import warnings
from abc import ABC, abstractmethod
import copy
import types
from time import time
from pynput.keyboard import Key, Listener
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
import sklearn.utils
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import grad
from torch.autograd.functional import jacobian, hessian
from torch.optim.lr_scheduler import StepLR
from cvxopt import matrix, solvers
from constraints import *
import utils
warnings.filterwarnings("ignore")
torch._C._debug_only_display_vmap_fallback_warnings(True)
# cvxopt solver config
solvers.options['show_progress'] = False
solvers.options['max_iters'] = int(1e9)
solvers.options['abstol'] = 1e-7
solvers.options['reltol'] = 1e-6
solvers.options['feastol'] = 1e-7
class BaseLearner(ABC):
def __init__(self, inp_dim, out_dim):
self.inp_dim = inp_dim
self.out_dim = out_dim
# normalization parameters
self._inp_offset = None
self._inp_scale = None
self._inp_range = None
self._out_offset = None
self._out_scale = None
self._out_range = None
super(BaseLearner, self).__init__()
def normalize(self, x=None, y=None, overwrite=False):
if x is not None:
if self._inp_offset is None or overwrite:
self._inp_range = np.array([np.amin(x, axis=0), np.amax(x, axis=0)])
self._inp_offset = np.array([np.mean(x, axis=0)]).T
self._inp_scale = np.array([np.std(x, axis=0)]).T
x = (x.T - self._inp_offset) / self._inp_scale
x = x.T
if y is not None:
if self._out_offset is None or overwrite:
self._out_range = np.array([np.amin(y, axis=0), np.amax(y, axis=0)])
self._out_offset = np.array([np.mean(y, axis=0)]).T
self._out_scale = np.array([np.std(y, axis=0)]).T
y = (y.T - self._out_offset) / self._out_scale
y = y.T
# I hate this
if x is None and y is not None:
return y
if x is not None and y is None:
return x
if x is not None and y is not None:
return x, y
def denormalize(self, x=None, y=None):
if x is not None and self._inp_offset is None:
raise ValueError('No known input range for denormalization, normalize first')
if y is not None and self._out_offset is None:
raise ValueError('No known output range for denormalization, normalize first')
if x is not None:
x = x.T * self._inp_scale + self._inp_offset
x = x.T
if y is not None:
y = y.T * self._out_scale + self._out_offset
y = y.T
if x is None and y is not None:
return y
if x is not None and y is None:
return x
if x is not None and y is not None:
return x, y
@abstractmethod
def init(self):
pass
@abstractmethod
def train(self):
pass
@abstractmethod
def apply(self):
pass
class ELM(BaseLearner):
def __init__(self,
inp_dim,
out_dim,
use_bias=True,
hid_dim=100,
bip=False, # batch intrinsic plasticity
reg=1e-6,
mu=0.3,
batch_size=10000,
normalize=False):
if not isinstance(inp_dim, int) or inp_dim < 1:
raise ValueError("'inp_dim' must be of type int and greater than 0")
if not isinstance(out_dim, int) or out_dim < 1:
raise ValueError("'out_dim' must be of type int and greater than 0")
if not isinstance(bip, bool):
raise ValueError("'bip' must be of type bool")
if not isinstance(reg, (float, int)) or reg <= 0:
raise ValueError("'reg' must be of type float and greater than 0")
if not isinstance(mu, (float, int)):
raise ValueError("'mu' must be of type float")
if not isinstance(normalize, bool):
raise ValueError("'normalize' must be of type bool")
BaseLearner.__init__(self, inp_dim, out_dim)
self.hid_dim = hid_dim # number of nodes in the hidden layer
self.reg = reg # regularization parameter for ridge regression
self.bip = bip # flag for using Batch Intrinsic Plasticity (bip)
self.mu = mu # desired mean activity parameter for bip
self.batch_size = batch_size # batchwise
self._normalize = normalize
self._use_bias = use_bias
self._initialized = False
# weights from input layer to hidden layer
self.input_weights = 2 * np.random.uniform(size=(self.hid_dim, self.inp_dim)) - np.ones((self.hid_dim, self.inp_dim))
# weights from hidden layer to output layer
if self._use_bias:
self.out_weights = 2 * np.random.uniform(size=(self.hid_dim + 1, self.out_dim)) - np.ones(
(self.hid_dim + 1, self.out_dim))
else:
self.out_weights = 2 * np.random.uniform(size=(self.hid_dim, self.out_dim)) - np.ones((self.hid_dim, self.out_dim))
# slope and bias parameters of activation functions
self.a = np.ones(self.hid_dim)
self.b = 2 * np.random.uniform(size=self.hid_dim) - np.ones(self.hid_dim)
def init(self, x):
"""Initialize batch intrinsic plasticity. Must be called before .train(...) and .apply(...)!"""
if x is not None and not isinstance(x, np.ndarray):
raise ValueError("'x' must either be None or a numpy array")
if self.bip:
if x is None:
raise ValueError("Can only apply Batch Intrinic Plasticity when 'x' was passed")
self.__bip(x)
self._initialized = True
def train(self, x, y):
"""Calculate least-squares output weights for x and y."""
if not isinstance(x, np.ndarray):
raise ValueError("'x' must be a numpy array")
if not isinstance(y, np.ndarray):
raise ValueError("'y' must be a numpy array")
if not self._initialized:
raise ValueError("Model is not initialized")
if x.ndim == 1:
x = np.reshape(x, (x.shape[0], 1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0], 1))
num_samples = np.size(x, 0)
if self._normalize:
x = self.normalize(x, overwrite=True)
if num_samples < self.batch_size:
hs = self.__calc_hidden_state(x)
if self._use_bias:
hs = np.column_stack([hs, np.ones([hs.shape[0], 1])])
if self._use_bias:
g = np.linalg.inv(np.dot(hs.T, hs) + self.reg * np.identity(self.hid_dim + 1))
else:
g = np.linalg.inv(np.dot(hs.T, hs) + self.reg * np.identity(self.hid_dim))
self.out_weights = np.dot(g, np.dot(hs.T, y))
else:
if self._use_bias:
hth = np.zeros((self.hid_dim + 1, self.hid_dim + 1))
hty = np.zeros((self.hid_dim + 1, self.out_dim))
else:
hth = np.zeros((self.hid_dim, self.hid_dim))
hty = np.zeros((self.hid_dim, self.out_dim))
num_batches = num_samples // self.batch_size
rest = num_samples % self.batch_size
for n in range(num_batches):
h = self.__calc_hidden_state(x[n * self.batch_size:(n + 1) * self.batch_size, :])
if self._use_bias:
h = np.column_stack([h, np.ones([h.shape[0], 1])])
hth += np.dot(h.T, h)
hty += np.dot(h.T, y[n * self.batch_size:(n + 1) * self.batch_size, :])
if rest > 0:
h = self.__calc_hidden_state(x[num_batches * self.batch_size:-1, :])
if self._use_bias:
h = np.column_stack([h, np.ones([h.shape[0], 1])])
hth += np.dot(h.T, h)
hty += np.dot(h.T, y[num_batches * self.batch_size:-1, :])
if self._use_bias:
hth += self.reg * np.identity(self.hid_dim + 1)
else:
hth += self.reg * np.identity(self.hid_dim)
self.out_weights = np.dot(np.linalg.pinv(hth), hty)
def apply(self, x):
"""Runs inference for input array x, batch_size still applies."""
if not isinstance(x, np.ndarray):
raise ValueError("'x' must be a numpy array")
if not self._initialized:
raise ValueError("Model is not initialized")
if x.ndim == 1:
x = np.reshape(x, (x.shape[0], 1))
if self._normalize:
x = self.normalize(x, overwrite=False)
num_samples = np.size(x, 0)
if num_samples < self.batch_size:
hs = self.__calc_hidden_state(x)
if self._use_bias: hs = np.column_stack([hs, np.ones([hs.shape[0], 1])])
y = np.dot(hs, self.out_weights)
else:
y = np.zeros((num_samples, self.out_dim))
num_batches = num_samples // self.batch_size
rest = num_samples % self.batch_size
for n in range(num_batches):
h = self.__calc_hidden_state(x[n * self.batch_size:(n + 1) * self.batch_size, :])
if self._use_bias:
h = np.column_stack([h, np.ones([h.shape[0], 1])])
y[n * self.batch_size:(n + 1) * self.batch_size, :] = np.dot(h, self.out_weights)
if rest > 0:
h = self.__calc_hidden_state(x[num_batches * self.batch_size:-1, :])
if self._use_bias:
h = np.column_stack([h, np.ones([h.shape[0], 1])])
y[num_batches * self.batch_size:-1, :] = np.dot(h, self.out_weights)
if self._normalize:
y = self.denormalize(y=y)
self.out = y
return self.out
def __calc_hidden_state(self, x):
g = x.dot(self.input_weights.T)
return utils.sigmoid(self.a * g + self.b)
def __bip(self, x):
x = x if utils.check_array(x) else np.asarray(x)
num_samples = np.size(x, 0)
g = x.dot(self.input_weights.T)
for hn in range(self.hid_dim):
targets = np.random.exponential(self.mu, size=num_samples)
hightars = np.size(targets[(targets >= 1) | (targets < 0)], 0)
while hightars > 0:
furthertargets = np.random.exponential(self.mu, size=hightars)
targets = np.concatenate((targets[(targets < 1) & (targets >= 0)], furthertargets))
hightars = np.size(targets[(targets >= 1) | (targets < 0)], 0)
targets = np.sort(targets)
s = np.sort(g[:, hn])
Phi = np.column_stack([s, np.ones(num_samples)])
targetsinv = np.array([-np.log(1. / targets - 1)])
w = np.linalg.pinv(Phi).dot(targetsinv.T)
self.a[hn] = w[0]
self.b[hn] = w[1]
class CELM(ELM):
"""
Implementation of an extreme learning machine (ELM) with output constraints.
This class extends the traditional ELM by allowing output constraints defined
as weighted sums of arbitrary partial derivatives of the output nodes. These
constraints are implemented as quadratic programming (QP) problems solved
iteratively until the desired constraint satisfaction is achieved.
Constraints can be added during initialization using the `cieqcs`, `ceqcs`,
`dieqcs`, `deqcs`, and `obj_fcts` parameters, representing continuous inequality
constraints, continuous equality constraints, discrete inequality constraints,
discrete equality constraints, and objective functions, respectively.
Args:
inp_dim (int): Dimensionality of the input layer.
out_dim (int): Dimensionality of the output layer.
hid_dim (int, optional): Number of neurons in the hidden layer. Defaults to 30.
max_iter (int, optional): Maximum number of iterations for constraint satisfaction. Defaults to 1000.
batch_size (int, optional): Batch size for training. Defaults to 10000.
reg (float, optional): Weight of L2 regularization. Defaults to 1e-6.
mu (float, optional): Activity level for batch intrinsic plasticity. Defaults to 0.3.
eps (float, optional): Relaxation parameter for equality constraint checks. Defaults to 1e-3.
bip (bool, optional): If True, applies batch intrinsic plasticity for improved training stability. Defaults to False.
normalize (bool, optional): If True, normalizes input data for better performance. Defaults to False.
verbose (int, optional): Verbosity level for training progress output (0: silent, 2: detailed). Defaults to 2.
callbacks (List[Callable], optional): Callback functions executed after each training iteration. Defaults to None.
cieqcs (np.ndarray, optional): Continuous inequality constraints. Defaults to an empty array.
ceqcs (np.ndarray, optional): Continuous equality constraints. Defaults to an empty array.
dieqcs (np.ndarray, optional): Discrete inequality constraints. Defaults to an empty array.
deqcs (np.ndarray, optional): Discrete equality constraints. Defaults to an empty array.
obj_fcts (np.ndarray, optional): Objective functions for solving additional constraints or differential equations. Defaults to an empty array.
Attributes:
terminate (bool): If True, allows manual interruption of training. Triggered by pressing escape.
"""
def __init__(self, inp_dim: int, out_dim: int,
hid_dim: int = 30,
max_iter=1000,
batch_size: int = 10000,
reg: float = 1e-6,
mu: float = 0.3,
eps: float = 1e-3,
bip: bool = False,
normalize: bool = False,
verbose: int = 2,
callbacks: List[Callable] | None = None,
cieqcs=np.array([]),
ceqcs=np.array([]),
dieqcs=np.array([]),
deqcs=np.array([]),
obj_fcts=np.array([])):
ELM.__init__(self, inp_dim, out_dim, True, hid_dim, bip, reg, mu, batch_size, normalize)
self.verbose = verbose
self.hid_dim = hid_dim
self._eps = eps
if callbacks is None:
callbacks = []
self.callbacks = callbacks
self.cieqcs = list(cieqcs)
self.ceqcs = list(ceqcs)
self.dieqcs = list(dieqcs)
self.deqcs = list(deqcs)
self.obj_fcts = list(obj_fcts)
self.max_iter = max_iter
self._aeq = np.array([])
self._beq = np.array([])
self._aieq = np.array([])
self._bieq = np.array([])
self.terminate = False
def on_press(key):
if key == Key.esc:
self.terminate = True
def on_release(key):
if key == Key.esc:
self.terminate = False
self._listener = Listener(on_press=on_press, on_release=on_release)
def init(self, x=None):
"""
Initialize the CELM model by setting up constraint test values and dimensionalities.
This method must be called before using the `train` or `apply` methods.
Args:
x (np.ndarray, optional): Input data for initialization. Defaults to None.
Raises:
ValueError: If `x` is not a numpy array or if required parameters are missing.
"""
if x is not None and not isinstance(x, np.ndarray):
raise ValueError("'x' must either be None or a numpy array")
if self.bip and x is None:
raise ValueError("Can only apply Batch Intrinic Plasticity when 'x' was passed")
ELM.init(self, x)
num_objfct = len(self.obj_fcts)
for i in range(num_objfct):
self.obj_fcts[i].inp_dim = self.inp_dim
num_dieqs = len(self.dieqcs)
for i in range(num_dieqs):
self.dieqcs[i].inp_dim = self.inp_dim
num_deqs = len(self.deqcs)
for i in range(num_deqs):
self.deqcs[i].inp_dim = self.inp_dim
num_cieqs = len(self.cieqcs)
for i in range(num_cieqs):
self.cieqcs[i].inp_dim = self.inp_dim
if self.cieqcs[i].max_test_value is None:
self.cieqcs[i].max_test_value = self.cieqcs[i].max_value
if self.cieqcs[i].min_test_value is None:
self.cieqcs[i].min_test_value = self.cieqcs[i].min_value
num_ceqs = len(self.ceqcs)
for i in range(num_ceqs):
self.ceqcs[i].inp_dim = self.inp_dim
if self.ceqcs[i].max_test_value is None:
self.ceqcs[i].max_test_value = self.__get_eq_test_value(self.ceqcs[i].value, self._eps)
if self.ceqcs[i].min_test_value is None:
self.ceqcs[i].min_test_value = self.__get_eq_test_value(self.ceqcs[i].value, -self._eps)
def train(self, x, y):
"""
Train the CELM model using input data `x` and target data `y`.
This method runs a sequential quadratic programming process to minimize
the mean squared error (MSE) while respecting constraints.
Args:
x (np.ndarray): Input data.
y (np.ndarray): Target data.
Returns:
dict: Training results containing iteration count, MSE values,
and constraint reliabilities.
"""
if not isinstance(x, np.ndarray):
raise ValueError("'x' must be a numpy array")
if not isinstance(y, np.ndarray):
raise ValueError("'y' must be a numpy array")
if not self._initialized:
raise ValueError("Model is not initialized")
mse = []
reliab = []
if x.ndim == 1:
x = np.reshape(x, (x.shape[0], 1))
if y.ndim == 1:
y = np.reshape(y, (y.shape[0], 1))
if self._normalize:
x = self.normalize(x, overwrite=True)
num_cieqcs = len(self.cieqcs)
num_ceqcs = len(self.ceqcs)
if self._normalize:
for con in self.dieqcs:
con.u = self.normalize(np.atleast_2d(con.u))
for con in self.deqcs:
con.u = self.normalize(np.atleast_2d(con.u))
self.__clear_constraints()
self.__fill_ieq_matrix(self.dieqcs)
self.__fill_eq_matrix(self.deqcs)
self.__qp(x, y)
if num_cieqcs + num_ceqcs != 0:
for i in range(self.max_iter):
if self.terminate:
print("Constrained learning was interrupted manually")
break
mse.append(self.__mse(x, y))
# constraint fulfillment check
test_samples_cieqcs = [[] for _ in range(num_cieqcs)]
violations_cieqcs = [0 for _ in range(num_cieqcs)]
ub_cieqcs = [0 for _ in range(num_cieqcs)]
lb_cieqcs = [0 for _ in range(num_cieqcs)]
test_samples_ceqcs = [[] for _ in range(num_ceqcs)]
violations_ceqcs = [0 for _ in range(num_ceqcs)]
ub_ceqcs = [0 for _ in range(num_ceqcs)]
lb_ceqcs = [0 for _ in range(num_ceqcs)]
# draw samples
for c, con in enumerate(self.cieqcs):
test_samples_cieqcs[c] = con.draw_test_samples()
if self._normalize:
test_samples_cieqcs[c] = self.normalize(test_samples_cieqcs[c])
for c, con in enumerate(self.ceqcs):
test_samples_ceqcs[c] = con.draw_test_samples()
if self._normalize:
test_samples_ceqcs[c] = self.normalize(test_samples_ceqcs[c])
# check inequality constraints
violationcount_cieqcs = np.zeros(num_cieqcs)
violationcount_ceqcs = np.zeros(num_ceqcs)
for c, con in enumerate(self.cieqcs):
violations_cieqcs[c] = 0
samples = self.__check_sample_dim(test_samples_cieqcs[c])
# calculate constraint function value
for idx, pd in enumerate(con.partials):
violations_cieqcs[c] += self.__fct(samples, pd, con.factors[idx])
# get bounds
ub_cieqcs[c] = self.__get_bound(con.max_test_value, samples)
lb_cieqcs[c] = self.__get_bound(con.min_test_value, samples)
# count violations
violationcount_cieqcs[c] = np.sum((violations_cieqcs[c] > ub_cieqcs[c]) |
(violations_cieqcs[c] < lb_cieqcs[c]))
# check equality constraints
for c, con in enumerate(self.ceqcs):
violations_ceqcs[c] = 0
samples = self.__check_sample_dim(test_samples_ceqcs[c])
# calculate constraint function value
for idx, pd in enumerate(con.partials):
violations_ceqcs[c] = self.__fct(samples, pd, con.factors[idx])
# get bounds
ub_ceqcs[c] = self.__get_bound(con.max_test_value, samples)
lb_ceqcs[c] = self.__get_bound(con.min_test_value, samples)
# count violations
violationcount_ceqcs[c] = np.sum((violations_ceqcs[c] > ub_ceqcs[c]) |
(violations_ceqcs[c] < lb_ceqcs[c]))
# cmd output
cmd_output = "Iter. (" + str(i + 1) + "): "
_reliability = []
if num_cieqcs > 0:
cmd_output += "IEQs: "
for c in range(num_cieqcs - 1):
nInputs = len(self.cieqcs[c].u)
reliability = 1 - (violationcount_cieqcs[c] / self.cieqcs[c].test_samples_per_iteration)
cmd_output += f"Rel. ({nInputs}): {reliability:.3f}, "
_reliability.append( ('CIEQC_'+str(c), reliability))
nInputs = len(self.cieqcs[num_cieqcs - 1].u)
reliability = 1 - (violationcount_cieqcs[num_cieqcs - 1] / self.cieqcs[
num_cieqcs - 1].test_samples_per_iteration)
cmd_output += f"Rel. ({nInputs}): {reliability:.3f}"
_reliability.append(('CIEQC_' + str(num_cieqcs - 1), reliability))
if num_ceqcs > 0:
cmd_output += "EQs: "
for c in range(num_ceqcs - 1):
nInputs = len(self.ceqcs[c].u)
reliability = 1 - (violationcount_ceqcs[c] / self.ceqcs[c].test_samples_per_iteration)
cmd_output += f"Rel. ({nInputs}): {reliability:.3f}, "
_reliability.append(('CEQC_' + str(c), reliability))
nInputs = len(self.ceqcs[num_ceqcs - 1].u)
reliability = 1 - (violationcount_ceqcs[num_ceqcs - 1] / self.ceqcs[
num_ceqcs - 1].test_samples_per_iteration)
cmd_output += f"Rel. ({nInputs}): {reliability:.3f}"
_reliability.append(('CEQC_' + str(num_cieqcs - 1), reliability))
reliab.append(_reliability)
# break test
test_samples_per_iteration_cieqcs = [con.test_samples_per_iteration for con in self.cieqcs]
test_samples_per_iteration_ceqcs = [con.test_samples_per_iteration for con in self.ceqcs]
satisfaction_thresholds_cieqcs = [con.satisfaction_threshold for con in self.cieqcs]
satisfaction_thresholds_ceqcs = [con.satisfaction_threshold for con in self.ceqcs]
flag_StopSampling_cieqcs = (1 - np.divide(violationcount_cieqcs,
test_samples_per_iteration_cieqcs)) > satisfaction_thresholds_cieqcs
flag_StopSampling_ceqcs = (1 - np.divide(violationcount_ceqcs,
test_samples_per_iteration_ceqcs)) > satisfaction_thresholds_ceqcs
if sum(flag_StopSampling_cieqcs) == num_cieqcs and sum(flag_StopSampling_ceqcs) == num_ceqcs:
break
# add most violating points (inequalities)
for c, con in enumerate(self.cieqcs):
if flag_StopSampling_cieqcs[c] == 0:
viol = violations_cieqcs[c]
ub = ub_cieqcs[c]
lb = lb_cieqcs[c]
if all(ub == np.inf):
viol = -(viol - lb)
elif all(lb == -np.inf):
viol -= ub
else:
viol = np.maximum(viol - ub, -(viol - lb))
sortval = np.sort(viol)[::-1]
sortind = np.argsort(viol)[::-1]
j = 1
counter = 0
test_samples_temp = test_samples_cieqcs[c][sortind, :]
while j < len(test_samples_temp) and counter < con.samples_per_iteration:
if sortval[j] > 0:
con.u = utils.stack([con.u, test_samples_temp[j, :]], 'v')
counter += 1
j += 1
# add most violating points (equalities)
for c, con in enumerate(self.ceqcs):
if flag_StopSampling_ceqcs[c] == 0:
viol = violations_ceqcs[c]
ub = ub_ceqcs[c]
lb = lb_ceqcs[c]
if all(ub == np.inf):
viol = -(viol - lb)
elif all(lb == -np.inf):
viol -= ub
else:
viol = np.maximum(viol - ub, -(viol - lb))
sortval = np.sort(viol)[::-1]
sortind = np.argsort(viol)[::-1]
j = 1
counter = 0
test_samples_temp = test_samples_ceqcs[c][sortind, :]
while j < len(test_samples_temp) and counter < con.samples_per_iteration:
if sortval[j] > 0:
con.u = utils.stack([con.u, test_samples_temp[j, :]], 'v')
counter += 1
j += 1
# constraint learning
self.__clear_constraints()
self.__fill_ieq_matrix(self.cieqcs)
self.__fill_eq_matrix(self.ceqcs)
self.__fill_ieq_matrix(self.dieqcs)
self.__fill_eq_matrix(self.deqcs)
try:
cmd_output += self.__qp(x, y)
except ValueError as e:
print(e)
break
if self.verbose == 1:
print("Iteration (" + str(i + 1) + ")")
elif self.verbose == 2:
print(cmd_output)
for callback in self.callbacks:
callback(i, self)
else:
i = 0
print("Learning finished")
return {
'iter': i,
'mse': mse,
'reliability': reliab
}
def grad(self, u):
"""
Compute the gradient of the output with respect to input `u`.
Args:
u (np.ndarray): Input data.
Returns:
np.ndarray: Gradient matrix.
"""
return np.array([-self.__fct(u, [[i]], [1]) for i in range(self.inp_dim)]).T
def __qp(self, x, y):
"""Solve quadratic program subject to constraints defined by self.aieq, self.aeq, self.bieq and self.beq."""
if not isinstance(x, np.ndarray):
raise ValueError("'x' must be a numpy array")
if not isinstance(y, np.ndarray):
raise ValueError("'y' must be a numpy array")
d = y.flatten('F')
h, _ = self.__objective_function(x, y)
xH = h.shape[0]
yH = h.shape[1]
for i in range(self.out_dim):
if i == 0:
C = np.hstack([np.zeros((xH, i * yH)), h, np.zeros((xH, (self.out_dim - i - 1) * yH))])
else:
C = np.vstack([C, np.hstack([np.zeros((xH, i * yH)), h, np.zeros((xH, (self.out_dim - i - 1) * yH))])])
C = np.vstack([C, np.sqrt(self.reg) * np.eye((self.hid_dim + 1) * self.out_dim)])
d = np.hstack([np.array([d]), np.zeros((1, (self.hid_dim + 1) * self.out_dim))]).T
P = matrix(C.T.dot(C))
q = matrix(-1 * C.T.dot(d))
no_eqs = (self._aeq.size == 0)
no_ieqs = (self._aieq.size == 0)
# trf constraint matrices
if not no_eqs:
inv = 1 / self._beq
mask = (inv == np.inf) | (inv == -np.inf)
Aeq = copy.deepcopy(self._aeq)
beq = copy.deepcopy(self._beq)
is_negative = beq < 0
Aeq[~mask] /= np.reshape(beq[~mask], (-1, 1))
beq[~mask] = 1.
Aeq[is_negative] *= -1.
beq[is_negative] *= -1.
if not no_ieqs:
inv = 1 / self._bieq
mask = (inv == np.inf) | (inv == -np.inf)
Aieq = copy.deepcopy(self._aieq)
bieq = copy.deepcopy(self._bieq)
is_negative = bieq < 0
Aieq[~mask] /= np.reshape(bieq[~mask], (-1, 1))
bieq[~mask] = 1.
Aieq[is_negative] *= -1.
bieq[is_negative] *= -1.
# parameterize and run solver
if no_eqs and no_ieqs:
sol = solvers.qp(P, q)
elif no_eqs:
Aieq = matrix(Aieq)
bieq = matrix(bieq)
sol = solvers.qp(P, q, G=Aieq, h=bieq)
self.out_weights = np.reshape(sol['x'], self.out_weights.shape, order='F')
elif no_ieqs:
Aeq = matrix(Aeq)
beq = matrix(beq)
sol = solvers.qp(P, q, A=Aeq, b=beq)
else:
Aieq = matrix(Aieq)
bieq = matrix(bieq)
Aeq = matrix(Aeq)
beq = matrix(beq)
sol = solvers.qp(P, q, G=Aieq, h=bieq, A=Aeq, b=beq)#, solver='mosek')
self.out_weights = np.reshape(sol['x'], self.out_weights.shape, order='F')
return f" | Solution [{sol['status']}], MSE: {self.__mse(x, y)}, MAE: {self.__mae(x, y)}"
def __objective_function(self, x, y):
"""Fill hidden state matrix according to list of linear objective functions"""
if not isinstance(x, np.ndarray):
raise ValueError("'x' must be a numpy array")
if not isinstance(y, np.ndarray):
raise ValueError("'y' must be a numpy array")
if not self.obj_fcts:
h = self._ELM__calc_hidden_state(x)
return (utils.stack((h, np.ones((h.shape[0], 1))), 'h'), y)
input_weights = self.input_weights.T
a = self.a.T
b = self.b.T
Heff = np.array([])
Yeff = np.array([])
for of, objfct in enumerate(self.obj_fcts):
num_samples = x.shape[0]
if num_samples == 0:
return
partials = objfct.partials
coeffs = objfct.factors
for idx, pd in enumerate(partials):
HTemp = np.array([])
factors = coeffs[idx]
if callable(factors):
factors = factors(x)
else:
factors = np.repeat(factors, num_samples)
for s in range(self.out_dim):
D = len(pd[s])
matTemp = np.ones((self.hid_dim, num_samples))
for p in pd[s]:
partial_input_weights = np.multiply(a, input_weights[p, :])
matTemp *= np.array([partial_input_weights]).T
hid_derivative = utils.sigmoid(a * (x.dot(input_weights)) + b, D) * matTemp.T
hid_derivative = utils.stack((hid_derivative, np.ones((hid_derivative.shape[0], 1))), 'h') if len(
pd[s]) == 0 else utils.stack((hid_derivative, np.zeros((hid_derivative.shape[0], 1))), 'h')
HTemp = utils.stack((HTemp, np.tile(factors[s], (self.hid_dim + 1, 1)).T * hid_derivative), 'h')
if idx == 0:
h = HTemp
else:
h += HTemp
Heff = utils.stack((Heff, h))
Yeff = utils.stack((Yeff, y[:, of]), 'h')
return (Heff, Yeff)
def __clear_constraints(self):
self._aeq = np.array([])
self._beq = np.array([])
self._aieq = np.array([])
self._bieq = np.array([])
def __fill_ieq_matrix(self, cons):
"""Fill self.aieq and self.bieq matrices to parametrize the solver according to linear inequality constraints."""
if len(cons) == 0:
return
input_weights = self.input_weights.T
a = self.a.T
b = self.b.T
for con in cons:
partials = con.partials
coeffs = con.factors
if con.min_value == -np.inf and con.max_value == np.inf:
continue
u = self.__check_sample_dim(np.asarray(con.u))
if u.size == 0:
continue
ub = self.__get_bound(con.max_test_value, u)
lb = self.__get_bound(con.min_test_value, u)
num_samples = u.shape[0]
if all(ub == np.inf) and all(lb == -np.inf):
continue
for idx, pd in enumerate(partials):
AieqMinTemp = np.array([])
bieqMinTemp = np.zeros((num_samples,))
AieqMaxTemp = np.array([])
bieqMaxTemp = np.zeros((num_samples,))
factors = coeffs[idx]
if callable(factors):
factors = factors(u)
else:
factors = factors
for s in range(self.out_dim):
D = len(pd[s])
matTemp = np.ones((self.hid_dim, num_samples))
for p in pd[s]:
partial_input_weights = np.multiply(a, input_weights[p, :])
matTemp *= np.array([partial_input_weights]).T
if self._normalize:
matTemp /= self._inp_scale[p]
hid_derivative = utils.sigmoid(a * (u.dot(input_weights)) + b, D) * matTemp.T
hid_derivative = utils.stack((hid_derivative, np.ones((hid_derivative.shape[0], 1))), 'h') if len(
pd[s]) == 0 else utils.stack((hid_derivative, np.zeros((hid_derivative.shape[0], 1))), 'h')
if con.min_value != -np.inf:
AieqMinTemp = utils.stack(
(AieqMinTemp, np.tile(-factors[s], (self.hid_dim + 1, 1)).T * hid_derivative), 'h')
bieqMinTemp -= lb
if con.max_value != np.inf:
AieqMaxTemp = utils.stack((AieqMaxTemp, np.tile(factors[s], (self.hid_dim + 1, 1)).T * hid_derivative),
'h')
bieqMaxTemp += ub
bieqMinTemp /= self.out_dim
bieqMaxTemp /= self.out_dim
if idx == 0:
AieqTempSum = utils.stack((AieqMinTemp, AieqMaxTemp))
if con.max_value != np.inf and con.min_value == -np.inf:
bieqTempSum = bieqMaxTemp
elif con.max_value == np.inf and con.min_value != -np.inf:
bieqTempSum = bieqMinTemp
else:
bieqTempSum = utils.stack((bieqMinTemp, bieqMaxTemp), 'h')
else:
AieqTempSum += utils.stack((AieqMinTemp, AieqMaxTemp))
if con.max_value != np.inf and con.min_value == -np.inf:
bieqTempSum += bieqMaxTemp
elif con.max_value == np.inf and con.min_value != -np.inf:
bieqTempSum += bieqMinTemp
else:
bieqTempSum += utils.stack((bieqMinTemp, bieqMaxTemp), 'h')
self._aieq = np.reshape(utils.stack((self._aieq, AieqTempSum)), (-1, (self.hid_dim + 1) * self.out_dim))
self._bieq = utils.stack([self._bieq, np.array([bieqTempSum]).flatten()], 'h')
self._bieq = self._bieq.flatten()
def __fill_eq_matrix(self, cons):
"""Fill self.aeq and self.beq matrices to parametrize the solver according to linear equality constraints."""
if len(cons) == 0:
return
input_weights = self.input_weights.T
a = self.a.T
b = self.b.T
for c, con in enumerate(cons):
u = self.__check_sample_dim(np.asarray(con.u))
if u.size == 0:
continue
tar = self.__get_bound(con.value, u)
num_samples = u.shape[0]
partials = con.partials
coeffs = con.factors
if u.size == 0:
continue
for idx, pd in enumerate(partials):
AeqTemp = np.array([])
beqTemp = 0
factors = coeffs[idx]
if callable(factors):
factors = factors(u)
else:
factors = factors
for s in range(self.out_dim):
D = len(pd[s])
matTemp = np.ones((self.hid_dim, num_samples))
for p in pd[s]:
partial_input_weights = np.multiply(a, input_weights[p, :])
matTemp *= np.array([partial_input_weights]).T
if self._normalize:
matTemp /= self._inp_scale[p]
hid_derivative = utils.sigmoid(a * (u.dot(input_weights)) + b, D) * matTemp.T
hid_derivative = utils.stack((hid_derivative, np.ones((hid_derivative.shape[0], 1))), 'h') if len(
pd[s]) == 0 else utils.stack((hid_derivative, np.zeros((hid_derivative.shape[0], 1))), 'h')
AeqTemp = utils.stack((AeqTemp, np.tile(-factors[s], (self.hid_dim + 1, 1)).T * hid_derivative), 'h')
beqTemp -= tar
if idx == 0:
AeqTempSum = AeqTemp
beqTempSum = beqTemp
else:
AeqTempSum = AeqTempSum + AeqTemp
beqTempSum = beqTempSum + beqTemp
self._aeq = utils.stack((self._aeq, AeqTempSum))
self._beq = np.append(self._beq, beqTempSum / self.out_dim)
def __fct(self, x, partials, factors):
"""Calculate linear combination of partial derivatives of the hidden state."""
input_weights = self.input_weights.T
a = self.a.T
b = self.b.T
x = np.asarray(x) if not utils.check_array(x) else x
if x.ndim == 1:
num_samples = 1
x = np.array([x])
else:
num_samples = x.shape[0]
out_dim = len(partials)
val = np.zeros((num_samples, out_dim))
if callable(factors):
facts = factors(x)
else:
facts = factors
for s in range(out_dim):
D = len(partials[s])
matTemp = np.ones((self.hid_dim, num_samples))
for p in partials[s]:
partial_input_weights = np.multiply(a, input_weights[p, :])