-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtraining.py
More file actions
68 lines (51 loc) · 2.13 KB
/
training.py
File metadata and controls
68 lines (51 loc) · 2.13 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision.transforms import ToPILImage
from torch.cuda.amp import autocast, GradScaler
from dataset.HumanLoader import HumanMattingDataset
from model.unet import U_net
from tqdm import tqdm
from model.Dice_Loss import DiceLoss
model = U_net(1).to('cuda')
model.load_state_dict(torch.load(r'weights/weights.pth'))
train_dataset = HumanMattingDataset(split='train')
val_dataset = HumanMattingDataset(split='val') # Initialize validation dataset
train_loader = DataLoader(train_dataset, batch_size=8, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=8, shuffle=False) # Initialize validation dataloader
criterion = DiceLoss() #nn.BCEWithLogitsLoss()
optimizer = optim.Adam(model.parameters(), lr=1e-4)
scaler = GradScaler()
num_epochs = 20
best_loss = float('inf') # Initialize with a high value
for epoch in range(num_epochs):
model.train()
for batch_idx, (images, masks, _, _) in tqdm(enumerate(train_loader), total=len(train_loader), desc=f"Epoch {epoch}"):
images, masks = images.cuda(), masks.cuda()
optimizer.zero_grad()
with autocast():
outputs = model(images)
loss = criterion(outputs, masks)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
if batch_idx % 100 == 0:
print()
print(f"Epoch [{epoch}/{num_epochs}] Batch [{batch_idx}/{len(train_loader)}] Training Loss: {loss.item()}")
model.eval()
val_loss = 0.0
with torch.no_grad():
for images, masks, _, _ in val_loader:
images, masks = images.cuda(), masks.cuda()
with autocast():
outputs = model(images)
loss = criterion(outputs, masks)
val_loss += loss.item()
val_loss /= len(val_loader)
print()
print(f"Epoch [{epoch}/{num_epochs}] Validation Loss: {val_loss}")
# Save model if the validation loss is improved
if val_loss < best_loss:
best_loss = val_loss
torch.save(model.state_dict(), r'weights\unet_model_best.pth')