Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
54 lines (45 loc) · 1.76 KB
/
Copy pathmain.py
File metadata and controls
54 lines (45 loc) · 1.76 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
# +---------------------------------------------------------------------+
# | (c) 2026 Mario Sieg <mario.sieg.64@gmail.com> |
# | Licensed under the Apache License, Version 2.0 |
# | |
# | Website : https://mariosieg.com |
# | GitHub : https://github.com/MarioSieg |
# | License : https://www.apache.org/licenses/LICENSE-2.0 |
# +---------------------------------------------------------------------+
from __future__ import annotations
from magnetron import Tensor, nn, optim, dtype
from matplotlib import pyplot as plt
EPOCHS: int = 100
LR: float = 1e-1
N = 100
x = -1.0 + Tensor.arange(0, N, 1, dtype=dtype.float32).reshape(N, 1) * (2.0 / (N - 1))
noise = Tensor.normal((N, 1), mean=0.0, std=0.2)
y = 3.0 * x + 0.5 + noise
# Create model, loss function, and optimizer
model = nn.Sequential(nn.Linear(1, 1))
criterion = nn.MSELoss()
opt = optim.SGD(model.parameters(), lr=LR)
# Train the model
losses = []
for epoch in range(EPOCHS):
pred = model(x)
loss = criterion(pred, y)
loss.backward()
opt.step()
opt.zero_grad()
if epoch % 10 == 0:
print(f'Epoch {epoch}, Loss: {loss.item()}')
losses.append(loss.item())
y_line = model(x) # Fitted line
# Plot results
plt.subplot(1, 2, 1)
plt.scatter([x[i].item() for i in range(x.numel)], [y[i].item() for i in range(y.numel)], s=16, label='Data')
plt.plot([x[i].item() for i in range(x.numel)], [y_line[i].item() for i in range(y_line.numel)], c='r', label='Fit')
plt.legend()
plt.title('Linear Regression Fit')
plt.subplot(1, 2, 2)
plt.plot(losses)
plt.title('Loss')
plt.xlabel('Epoch')
plt.tight_layout()
plt.show()