File: sequential.py

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (32 lines) | stat: -rw-r--r-- 693 bytes parent folder | download
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
import torch as th

print('Sequential model setup')
model = th.nn.Sequential(
        th.nn.Linear(28*28, 512),
        th.nn.ReLU(),
        th.nn.Linear(512, 128),
        th.nn.ReLU(),
        th.nn.Linear(128, 1)
        )
X = th.rand(10, 28*28)
Y = th.rand(10, 1)
optim = th.optim.SGD(model.parameters(), lr=0.1)

loss_curve = []
for i in range(10):
    # forward
    output = model.forward(X)
    loss = th.nn.functional.mse_loss(output, Y)

    # backward
    optim.zero_grad()
    loss.backward()

    # update
    optim.step()

    loss_curve.append(loss.item())
    print('iteration', i, 'loss', loss.item())

assert(loss_curve[-1] < loss_curve[0])
print('sequential model test ok')