Lesson 4 of 7 · 2 min
Train
# run locally: train.py
import torch, torchvision as tv, torchvision.transforms as T
from sklearn.metrics import classification_report, confusion_matrix
device = "cuda" if torch.cuda.is_available() else "mps" if torch.backends.mps.is_available() else "cpu"
norm = T.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
base = [T.Grayscale(3), T.Resize((224, 224))]
train = tv.datasets.ImageFolder("data/Training", T.Compose(base + [T.RandomRotation(10), T.RandomHorizontalFlip(), T.ToTensor(), norm]))
test = tv.datasets.ImageFolder("data/Testing", T.Compose(base + [T.ToTensor(), norm]))
n_val = len(train) // 8
train, val = torch.utils.data.random_split(train, [len(train) - n_val, n_val], torch.Generator().manual_seed(0))
loader = lambda d, s=False: torch.utils.data.DataLoader(d, 32, shuffle=s)
net = tv.models.efficientnet_b0(weights="DEFAULT")
net.classifier[1] = torch.nn.Linear(net.classifier[1].in_features, 4)
net.to(device)
def evaluate(data):
net.eval()
truth, guess = [], []
with torch.no_grad():
for x, y in loader(data):
truth += y.tolist()
guess += net(x.to(device)).argmax(1).cpu().tolist()
return truth, guess
opt = torch.optim.AdamW(net.parameters(), lr=2e-4, weight_decay=0.01)
best = 0
for epoch in range(8):
net.train()
for x, y in loader(train, True):
opt.zero_grad()
torch.nn.functional.cross_entropy(net(x.to(device)), y.to(device)).backward()
opt.step()
t, g = evaluate(val)
acc = sum(a == b for a, b in zip(t, g)) / len(t)
print(epoch, f"validation {acc:.2%}")
if acc > best:
best = acc
torch.save(net.state_dict(), "mri.pt")
net.load_state_dict(torch.load("mri.pt"))
t, g = evaluate(test)
print(confusion_matrix(t, g))
print(classification_report(t, g, target_names=test.classes, digits=3))