-
Notifications
You must be signed in to change notification settings - Fork 2
/
semitorchstocclass.py
655 lines (528 loc) · 24.6 KB
/
semitorchstocclass.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
"""
``semitorchstocclass`` provides classes implementing various domain adaptation methods using torch and stochastic gradient method.
All domain adaptation methods have to be subclass of BaseEstimator.
This implementation takes advantage of gradient method to optimize covariance match or MMD match in addition to mean match.
"""
from abc import abstractmethod
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import mmd
# check gpu avail
device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
# simple linear model in torch
class LinearModel(nn.Module):
def __init__(self, d):
super(LinearModel, self).__init__()
self.lin1 = nn.Linear(d, 1, bias=True)
def forward(self, x):
x = self.lin1(x)
return x
class BaseEstimator():
"""Base class for domain adaptation"""
@abstractmethod
def fit(self, data, source, target):
"""Fit model.
Arguments:
data (dict of (X, y) pairs): maps env index to the (X, y) pair in that env
source (list of indexes): indexes of source envs
target (int): single index of the target env
"""
self.source = source
self.target = target
return self
@abstractmethod
def predict(self, X):
"""Use the learned estimator to predict labels on fresh target data X
"""
def __str__(self):
"""For easy name printing
"""
return self.__class__.__name__
class Tar(BaseEstimator):
"""Oracle Linear regression (with l1 or l2 penalty) trained on the target domain"""
def __init__(self, lamL2=0.0, lamL1=0.0, lr=1e-4, epochs=10):
self.lamL2 = lamL2
self.lamL1 = lamL1
self.lr = lr
self.epochs = epochs
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
# get the input dimension
# assume it is a TensorDataset
d = dataloaders[target].dataset[0][0].shape[0]
model = LinearModel(d).to(device)
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
self.losses = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(dataloaders[target]):
xtar, ytar = data[0].to(device), data[1].to(device)
opt.zero_grad()
loss = loss_fn(model(xtar).view(-1), ytar) + \
self.lamL2 * torch.sum(model.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
# Perform gradient descent
loss.backward()
opt.step()
running_loss += loss.item()
self.losses[epoch] = running_loss
self.model = model
return self
def predict(self, X):
ypredX = self.model(X)
return ypredX
def __str__(self):
return self.__class__.__name__ + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class Src(BaseEstimator):
"""Src Linear regression (with l1 or l2 penalty) trained on the source domain"""
def __init__(self, lamL2=0.0, lamL1=0.0, sourceInd = 0, lr=1e-4, epochs=10):
self.lamL2 = lamL2
self.lamL1 = lamL1
self.sourceInd = sourceInd
self.lr = lr
self.epochs = epochs
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
# get the input dimension
# assume it is a TensorDataset
d = dataloaders[target].dataset[0][0].shape[0]
model = LinearModel(d).to(device)
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
self.losses = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(dataloaders[source[self.sourceInd]]):
x, y = data[0].to(device), data[1].to(device)
opt.zero_grad()
loss = loss_fn(model(x).view(-1), y) + \
self.lamL2 * torch.sum(model.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
# Perform gradient descent
loss.backward()
opt.step()
running_loss += loss.item()
self.losses[epoch] = running_loss
self.model = model
return self
def predict(self, X):
ypredX = self.model(X)
return ypredX
def __str__(self):
return self.__class__.__name__ + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class SrcPool(BaseEstimator):
"""Pool all source data together and then run linear regression
with l1 or l2 penalty """
def __init__(self, lamL2=0.0, lamL1=0.0, lr=1e-4, epochs=10):
self.lamL2 = lamL2
self.lamL1 = lamL1
self.lr = lr
self.epochs = epochs
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
# get the input dimension
# assume it is a TensorDataset
d = dataloaders[target].dataset[0][0].shape[0]
model = LinearModel(d).to(device)
# custom initialization
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
self.losses = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(zip(*[dataloaders[m] for m in source])):
opt.zero_grad()
loss = 0
for mindex, m in enumerate(source):
x, y = data[mindex][0].to(device), data[mindex][1].to(device)
loss += loss_fn(model(x).view(-1), y) / len(source)
loss += self.lamL2 * torch.sum(model.lin1.weight ** 2)
loss += self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
loss.backward()
opt.step()
running_loss += loss.item()
self.losses[epoch] = running_loss
self.model = model
return self
def predict(self, X):
ypredX = self.model(X)
return ypredX
def __str__(self):
return self.__class__.__name__ + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class DIP(BaseEstimator):
"""Pick one source, match mean of X * beta between source and target"""
def __init__(self, lamMatch=10., lamL2=0., lamL1=0., sourceInd = 0, lr=1e-4, epochs=10,
wayMatch='mean', sigma_list=[0.1, 1, 10, 100]):
self.lamMatch = lamMatch
self.lamL2 = lamL2
self.lamL1 = lamL1
self.sourceInd = sourceInd
self.lr = lr
self.epochs = epochs
self.wayMatch = wayMatch
self.sigma_list = sigma_list
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
d = dataloaders[target].dataset[0][0].shape[0]
model = LinearModel(d).to(device)
# custom initialization
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
self.losses = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(zip(dataloaders[source[self.sourceInd]], dataloaders[target])):
opt.zero_grad()
loss = 0
x, y = data[0][0].to(device), data[0][1].to(device)
xtar = data[1][0].to(device)
loss += loss_fn(model(x).view(-1), y)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
loss += self.lamMatch * discrepancy(model(x), model(xtar))
elif self.wayMatch == 'mmd':
loss += self.lamMatch * mmd.mix_rbf_mmd2(model(x), model(xtar), self.sigma_list)
else:
print('error discrepancy')
loss += self.lamL2 * torch.sum(model.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
loss.backward()
opt.step()
running_loss += loss.item()
self.losses[epoch] = running_loss
self.model = model
return self
def predict(self, X):
ypredX = self.model(X)
return ypredX
def __str__(self):
return self.__class__.__name__ + self.wayMatch + "_Match{:.1f}".format(self.lamMatch) + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class DIPweigh(BaseEstimator):
'''loop throught all source envs, match the mean of X * beta between source env i and target, weigh the final prediction based loss of env i'''
def __init__(self, lamMatch=10., lamL2=0., lamL1=0., lr=1e-4,
epochs=10, wayMatch='mean', sigma_list=[0.1, 1, 10, 100]):
self.lamMatch = lamMatch
self.lamL2 = lamL2
self.lamL1 = lamL1
self.lr = lr
self.epochs = epochs
self.wayMatch = wayMatch
self.sigma_list = sigma_list
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
d = dataloaders[target].dataset[0][0].shape[0]
models = {}
diffs = {}
ypreds = {}
losses_all = {}
self.total_weight = 0
for m in source:
model = LinearModel(d).to(device)
models[m] = model
# custom initialization
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
losses_all[m] = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(zip(dataloaders[m], dataloaders[target])):
opt.zero_grad()
loss = 0
x, y = data[0][0].to(device), data[0][1].to(device)
xtar = data[1][0].to(device)
loss += loss_fn(model(x).view(-1), y)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
loss += self.lamMatch * discrepancy(model(x), model(xtar))
elif self.wayMatch == 'mmd':
loss += self.lamMatch * mmd.mix_rbf_mmd2(model(x), model(xtar), self.sigma_list)
else:
raise('error discrepancy')
loss += self.lamL2 * torch.sum(model.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
loss.backward()
opt.step()
running_loss += loss.item()
losses_all[m][epoch] = running_loss
# need to calculate the diffs
diffs[m] = 0
with torch.no_grad():
for i, data in enumerate(zip(dataloaders[m], dataloaders[target])):
x, y = data[0][0].to(device), data[0][1].to(device)
xtar = data[1][0].to(device)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
local_match_res = discrepancy(model(x), model(xtar))
elif self.wayMatch == 'mmd':
local_match_res = mmd.mix_rbf_mmd2(model(x), model(xtar), self.sigma_list)
else:
raise('error discrepancy')
diffs[m] += local_match_res / self.epochs / (len(dataloaders[m].dataset)/dataloaders[m].batch_size)
self.total_weight += torch.exp(-100.*diffs[m])
self.models = models
self.diffs = diffs
minDiff = diffs[source[0]]
minDiffIndx = source[0]
for m in source:
if diffs[m] < minDiff:
minDiff = diffs[m]
minDiffIndx = m
self.minDiffIndx = minDiffIndx
print(minDiffIndx)
self.losses = losses_all[minDiffIndx]
return self
def predict(self, X):
ypredX1 = 0
for m in self.source:
ypredX1 += torch.exp(-100.*self.diffs[m]) * self.models[m](X)
ypredX1 /= self.total_weight
return ypredX1
def __str__(self):
return self.__class__.__name__ + self.wayMatch + "_Match{:.1f}".format(self.lamMatch) + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class CIP(BaseEstimator):
"""Match the conditional (on Y) mean of X * beta across source envs, no target env is needed"""
def __init__(self, lamCIP=10., lamL2=0., lamL1=0., lr=1e-4, epochs=10,
wayMatch='mean', sigma_list = [0.1, 1, 10, 100]):
self.lamCIP = lamCIP
self.lamL2 = lamL2
self.lamL1 = lamL1
self.lr = lr
self.epochs = epochs
self.wayMatch = wayMatch
self.sigma_list = sigma_list
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
d = dataloaders[target].dataset[0][0].shape[0]
model = LinearModel(d).to(device)
# custom initialization
with torch.no_grad():
model.lin1.bias.data = torch.zeros_like(model.lin1.bias)
torch.nn.init.xavier_normal_(model.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(model.parameters(), lr=self.lr)
self.losses = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(zip(*[dataloaders[m] for m in source])):
opt.zero_grad()
loss = 0
for mindex, m in enumerate(source):
x, y = data[mindex][0].to(device), data[mindex][1].to(device)
loss += loss_fn(model(x).view(-1), y)/float(len(source))
xmod = x - torch.mm(y.view(-1, 1), torch.mm(y.view(1, -1), x))/torch.sum(y**2)
# conditional invariance penalty
for jindex, j in enumerate(source):
if j > m:
xj, yj = data[jindex][0].to(device), data[jindex][1].to(device)
xmodj = xj - torch.mm(yj.view(-1, 1), torch.mm(yj.view(1, -1), xj))/torch.sum(yj**2)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
loss += self.lamCIP/float(len(source)**2) * discrepancy(model(xmod), model(xmodj))
elif self.wayMatch == 'mmd':
loss += self.lamCIP/float(len(source)**2) * \
mmd.mix_rbf_mmd2(model(xmod), model(xmodj), self.sigma_list)
else:
raise('error discrepancy')
loss += self.lamL2 * torch.sum(model.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(model.lin1.weight))
# Perform gradient descent
loss.backward()
opt.step()
running_loss += loss.item()
self.losses[epoch] = running_loss
self.model = model
return self
def predict(self, X):
ypredX = self.model(X)
return ypredX
def __str__(self):
return self.__class__.__name__ + self.wayMatch + "_CIP{:.1f}".format(self.lamCIP) + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)
class CIRMweigh(BaseEstimator):
"""Match the conditional (on Y) mean of X * beta across source envs, use Yhat as proxy of Y to remove the Y parts in X.
Match on the residual between one source env and target env"""
def __init__(self, lamMatch=10., lamCIP=10., lamL2=0., lamL1=0., lr=1e-4, epochs=10,
wayMatch='mean', sigma_list=[0.1, 1, 10, 100]):
self.lamMatch = lamMatch
self.lamCIP = lamCIP
self.lamL2 = lamL2
self.lamL1 = lamL1
self.lr = lr
self.epochs = epochs
self.wayMatch = wayMatch
self.sigma_list = sigma_list
def fit(self, dataloaders, source, target):
super().fit(dataloaders, source, target)
d = dataloaders[target].dataset[0][0].shape[0]
# Step 1: use source envs to match the conditional mean
# find beta_invariant
models1 = LinearModel(d).to(device)
# custom initialization
with torch.no_grad():
models1.lin1.bias.data = torch.zeros_like(models1.lin1.bias)
torch.nn.init.xavier_normal_(models1.lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(models1.parameters(), lr=self.lr)
losses1 = np.zeros(self.epochs)
for epoch in range(self.epochs):
running_loss = 0.0
for i, data in enumerate(zip(*[dataloaders[m] for m in source])):
loss = 0
for mindex, m in enumerate(source):
x, y = data[mindex][0].to(device), data[mindex][1].to(device)
loss += loss_fn(models1(x).view(-1), y)/float(len(source))
xmod = x - torch.mm(y.view(-1, 1), torch.mm(y.view(1, -1), x))/torch.sum(y**2)
# conditional invariance penalty
for jindex, j in enumerate(source):
xj, yj = data[jindex][0].to(device), data[jindex][1].to(device)
if j > m:
xmodj = xj - torch.mm(yj.view(-1, 1), torch.mm(yj.view(1, -1), xj))/torch.sum(yj**2)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
loss += self.lamCIP/float(len(source)**2) * discrepancy(models1(xmod), models1(xmodj))
elif self.wayMatch == 'mmd':
loss += self.lamCIP/float(len(source)**2) * \
mmd.mix_rbf_mmd2(models1(xmod), models1(xmodj), self.sigma_list)
else:
raise('error discrepancy')
loss += self.lamL2 * torch.sum(models1.lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(models1.lin1.weight))
# Perform gradient descent
loss.backward()
opt.step()
opt.zero_grad()
running_loss += loss.item()
losses1[epoch] = running_loss
self.models1 = models1
# fix grads now
for param in models1.lin1.parameters():
param.requires_grad = False
# Step 2: remove the invariant part on all source envs, so that everything is independent of Y
# get that coefficient b
YsrcMean = 0
ntotal = 0
for m in source:
YsrcMean += torch.sum(dataloaders[m].dataset.tensors[1])
ntotal += dataloaders[m].dataset.tensors[1].shape[0]
YsrcMean /= ntotal
YTX = 0
YTY = 0
for m in source:
for i, data in enumerate(dataloaders[m]):
x, y = data[0].to(device), data[1].to(device)
yguess = self.models1(x)
yCentered = y - YsrcMean
YTY += torch.sum(yguess.t() * yCentered)
YTX += torch.mm(yCentered.view(1, -1), x)
b = YTX / YTY
self.b = b
# Step 3: mean match between source and target on the residual, after transforming the covariates X - (X * beta_invariant) * b_invariant
models = {}
diffs = {}
losses_all = {}
self.total_weight = 0
for m in source:
models[m] = LinearModel(d).to(device)
# custom initialization
with torch.no_grad():
models[m].lin1.bias.data = torch.zeros_like(models[m].lin1.bias)
torch.nn.init.xavier_normal_(models[m].lin1.weight, gain=0.01)
# Define loss function
loss_fn = F.mse_loss
opt = optim.Adam(models[m].parameters(), lr=self.lr)
losses_all[m] = np.zeros(self.epochs)
for epoch in range(self.epochs): # loop over the dataset multiple times
running_loss = 0.0
for i, data in enumerate(zip(dataloaders[m], dataloaders[target])):
opt.zero_grad()
loss = 0
x, y = data[0][0].to(device), data[0][1].to(device)
yguess = self.models1(x)
xmod = x - torch.mm(yguess, b)
xtar = data[1][0].to(device)
ytarguess = self.models1(xtar)
xtarmod = xtar - torch.mm(ytarguess, b)
loss += loss_fn(models[m](x).view(-1), y)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
loss += self.lamMatch * discrepancy(models[m](xmod),
models[m](xtarmod))
elif self.wayMatch == 'mmd':
loss += self.lamMatch * mmd.mix_rbf_mmd2(models[m](xmod),
models[m](xtarmod),
self.sigma_list)
else:
raise('error discrepancy')
loss += self.lamL2 * torch.sum(models[m].lin1.weight ** 2) + \
self.lamL1 * torch.sum(torch.abs(models[m].lin1.weight))
loss.backward()
opt.step()
running_loss += loss.item()
losses_all[m][epoch] = running_loss
# need to compute diff after training
diffs[m] = 0.
with torch.no_grad():
for i, data in enumerate(zip(dataloaders[m], dataloaders[target])):
x, y = data[0][0].to(device), data[0][1].to(device)
yguess = self.models1(x)
xmod = x - torch.mm(yguess, b)
xtar = data[1][0].to(device)
ytarguess = self.models1(xtar)
xtarmod = xtar - torch.mm(ytarguess, b)
if self.wayMatch == 'mean':
discrepancy = torch.nn.MSELoss()
diffs[m] += discrepancy(models[m](xmod), models[m](xtarmod)) / \
self.epochs / (len(dataloaders[m].dataset)/dataloaders[m].batch_size)
elif self.wayMatch == 'mmd':
diffs[m] += mmd.mix_rbf_mmd2(models[m](xmod), models[m](xtarmod), self.sigma_list) / \
self.epochs / (len(dataloaders[m].dataset)/dataloaders[m].batch_size)
else:
raise('error discrepancy')
self.total_weight += torch.exp(-100.*diffs[m])
# take the min diff loss to be current best losses and model
minDiff = diffs[source[0]]
minDiffIndx = source[0]
self.losses = losses_all[source[0]]
for m in source:
if diffs[m] < minDiff:
minDiff = diffs[m]
minDiffIndx = m
self.losses = losses_all[m]
self.model = models[m]
self.minDiffIndx = minDiffIndx
self.models = models
self.diffs = diffs
return self
def predict(self, X):
ypredX1 = 0
for m in self.source:
ypredX1 += torch.exp(-100.*self.diffs[m]) * self.models[m](X)
ypredX1 /= self.total_weight
return ypredX1
def __str__(self):
return self.__class__.__name__ + self.wayMatch + "_Match{:.1f}".format(self.lamMatch) + "_L2={:.1f}".format(self.lamL2) + "_L1={:.1f}".format(self.lamL1)