-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtest.py
40 lines (30 loc) · 875 Bytes
/
test.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
import penal_connection as pc
import torch
import torch.nn as nn
class Net(nn.Module):
def __init__(self):
super().__init__()
self.fc_1 = nn.Linear(1, 4)
# use as a layer
self.fc_2 = nn.Sequential(
nn.Linear(4, 4),
pc.PenalConnection(tau=1e-4),
)
self.fc_3 = nn.Linear(4, 4)
self.fc_4 = nn.Linear(4, 1)
def forward(self, x):
fc_1 = self.fc_1(x)
fc_2 = fc_1 + self.fc_2(fc_1)
# use as a function
fc_3 = fc_2 + pc.penal_connection(self.fc_3(fc_2), tau=1e-4)
return self.fc_4(fc_3)
net = Net()
optim = torch.optim.SGD(net.parameters(), lr=1e-3)
data = torch.randn(16, 1)
for i in range(100):
output = net(data)
loss = output.pow(2).sum()
optim.zero_grad()
loss.backward()
optim.step()
print(loss.item())