# pip install torch torchvision
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
# Устройство
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Модель
model = nn.Sequential(
    nn.Flatten(),
    nn.Linear(784, 128),
    nn.Tanh(),
    nn.Linear(128, 10)
).to(device)
# Данные
transform = transforms.ToTensor()
train_dataset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
# Оптимизатор и функция потерь
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
# Обучение (1 эпоха)
model.train()
correct = total = 0
for images, labels in train_loader:
    images = images.view(-1, 784).to(device)
    labels = labels.to(device)
    optimizer.zero_grad()
    outputs = model(images)
    loss = criterion(outputs, labels)
    loss.backward()
    optimizer.step()
    _, predicted = torch.max(outputs, 1)
    total += labels.size(0)
    correct += (predicted == labels).sum().item()
print(f"Точность после 1 эпохи: {100 * correct / total:.2f}%")
