-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathget_targets.py
80 lines (55 loc) · 1.97 KB
/
get_targets.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
import torch
import numpy as np
def get_targets(target, a, model):
####extraction feature target#######
targets = {}
targets[a[-1]] = target
#Unwrap model
def unwrap_model(model):
weights = []
for name, weight in model._modules.items():
weights.append(weight)
return weights
#Get Weights
weights = unwrap_model(model)
taus = []
for weight in weights:
tau = []
for row in weight.weight.T:
t = (1/torch.sum(row**2))
tau.append(torch.maximum(t,torch.tensor(1)))
taus.append(torch.tensor(tau).detach())
loss = 0.5*torch.sum((targets[a[-1]] - a[-1])**2.0)
#########Feature Alignment############
for i in range(len(a)-2,-1,-1):
targets[a[i]] = a[i] - taus[i]*(torch.autograd.grad(loss, a[i], retain_graph=True)[0])
loss = 0.5*torch.sum((targets[a[i]]-a[i])**2.0)
#targets[a[i]] = targets[a[i]].detach()
######################################
return targets, targets[a[0]]
def get_targets2(target, a, model):
targets = {}
targets[a[-1]] = target
#Unwrap model
def unwrap_model(model):
weights = []
for name, weight in model._modules.items():
weights.append(weight)
return weights
#Get Weights
weights = unwrap_model(model)
taus = []
for weight in weights:
tau = []
for row in weight.weight.T:
t = (1/torch.sum(row**2))
tau.append(torch.maximum(t,torch.tensor(1)))
taus.append(torch.tensor(tau).detach())
#######extraction feature ##########
loss = 0.5*torch.sum((targets[a[-1]] - a[-1])**2.0)
for i in range(len(a)-2,-1,-1):
targets[a[i]] = a[i] - taus[i]*(torch.autograd.grad(loss, a[i], retain_graph=True)[0])
loss = 0.5*torch.sum((targets[a[i]]-a[i])**2.0)
targets[a[i]] = targets[a[i]].detach()
####################################
return targets, targets[a[0]]