# The network that reads digits, with PyTorch.
# Run it next to digits.csv: python network_pytorch.py

import numpy as np
import torch
from torch import nn

data = np.loadtxt("digits.csv", delimiter=",")
images = torch.tensor(data[:, :64] / 16, dtype=torch.float32)   # 64 pixels per image, between 0 and 1
labels = torch.tensor(data[:, 64], dtype=torch.long)            # the expected digit

train_x, train_y = images[:1500], labels[:1500]   # 1,500 images for training
test_x, test_y = images[1500:], labels[1500:]     # 297 images set aside

torch.manual_seed(0)   # the seed, like random.seed in step 6

model = nn.Sequential(
    nn.Linear(64, 32),
    nn.ReLU(),
    nn.Linear(32, 10),
)

loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=0.3)

for epoch in range(30):
    for start in range(0, 1500, 20):
        x = train_x[start:start + 20]
        y = train_y[start:start + 20]

        loss = loss_fn(model(x), y)
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

guesses = model(test_x).argmax(dim=1)   # pour chaque image, le chiffre le plus probable
score = (guesses == test_y).float().mean().item()
print(round(100 * score), "% on unseen images")
