1import torch
2
3
4
5model = torch.nn.Sequential()
6model.add_module('layer_1', torch.nn.Linear(2,2))
7model.add_module('fun_1', torch.nn.Tanh())
8model.add_module('layer_2', torch.nn.Linear(2,1))
9
10
11
12
13
14optim = torch.optim.SGD(model.parameters(),
15 lr=5e-1)
16
17
18X_train = torch.tensor([[1., 1.],
19 [1., -1.],
20 [-1., 1.],
21 [-1., -1.]])
22y_train = torch.tensor([-1., 1., 1., -1.]).reshape(-1,1)
23
24print("\nDados de treinamento")
25print("X_train =")
26print(X_train)
27print("y_train = ")
28print(y_train)
29
30
31nepochs = 5000
32tol = 1e-3
33
34for epoch in range(nepochs):
35
36
37 y_est = model(X_train)
38
39
40 loss = torch.mean((y_est - y_train)**2)
41
42 print(f'{epoch}: {loss.item():.4e}')
43
44
45 if (loss.item() < tol):
46 break
47
48
49 optim.zero_grad()
50 loss.backward()
51 optim.step()
52
53
54
55y = model(X_train)
56print(f'y_est = {y}')