Repository navigation
Expand file tree
/
Copy pathfitting.py
More file actions
83 lines (63 loc) · 2.15 KB
/
Copy pathfitting.py
File metadata and controls
83 lines (63 loc) · 2.15 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
import torch
import torch.nn as nn
import numpy as np
from NeuralODE import NeuralODE
class NNet(nn.Module):
def __init__(self):
super().__init__()
self.fc1 = nn.Linear(1, 50)
self.fc2 = nn.Linear(50, 1)
def forward(self, tk, yk):
out = yk ** 3
out = self.fc1(out)
out = self.fc2(out)
return out
def test_init():
print ("===== init network func ====")
nnet = NNet()
for param in nnet.parameters():
param.requires_grad_(True)
neuralODE = NeuralODE(model=nnet)
return neuralODE
def test_forward():
neuralODE = test_init()
print ("===== forward ====")
input = torch.tensor(1.0).view(-1, 1).float()
input.requires_grad_(True)
output = neuralODE.forward(input)
print (f"input: {input.data}; output: {output.data}")
return output
def test_backward():
output = test_forward()
print ("===== backward ====")
target = torch.tensor(1.2, dtype=torch.float32).view(-1, 1)
loss = nn.MSELoss()(output, target)
loss.backward()
print (f"output: {output.data}; target: {target.data}; loss: {loss.data}")
return loss
def test_training(device='cpu'):
nnet = NNet().to(device)
for param in nnet.parameters():
param.requires_grad_(True)
neuralODE = NeuralODE(model=nnet)
input = torch.tensor(1.0).view(-1, 1).float().to(device)
input.requires_grad_(True)
target = torch.tensor(1.2, dtype=torch.float32).view(-1, 1).to(device)
# updated_params = [input]
# updated_params = [w for w in nnet.parameters()]
updated_params = [input] + [w for w in nnet.parameters()]
# TODO:RMSPropOptimizer
optimizer = torch.optim.SGD(
updated_params, lr=0.001
)
for i in range(100):
output = neuralODE.forward(input)
loss = nn.MSELoss()(output, target)
loss.backward()
optimizer.step()
for params in updated_params:
if params.grad is not None:
params.grad.data.zero_()
print (f"iter: {i}; input: {input.data}; output: {output.data}, loss: {loss.data}")
if __name__ == "__main__":
test_training("cuda")