-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtrain.py
184 lines (145 loc) · 6.13 KB
/
train.py
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import os
from PIL import Image
import torch
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import jaccard_score
from tqdm import tqdm
# Set the environment variable for CUDA
os.environ["CUDA_VISIBLE_DEVICES"] = "3"
class BDD100KDataset(Dataset):
def __init__(self, images_dir, masks_dir, transform=None):
self.images_dir = images_dir
self.masks_dir = masks_dir
self.transform = transform
self.images = os.listdir(images_dir)
def __len__(self):
return len(self.images)
def __getitem__(self, idx):
img_name = self.images[idx]
img_path = os.path.join(self.images_dir, img_name)
mask_path = os.path.join(self.masks_dir, img_name.replace('.jpg', '.png'))
image = Image.open(img_path).convert("RGB")
mask = Image.open(mask_path).convert("L")
if self.transform:
image = self.transform(image)
mask = self.transform(mask)
return image, mask
transform = transforms.Compose([
transforms.Resize((256, 256)),
transforms.ToTensor(),
])
train_dataset = BDD100KDataset(
images_dir='/data/BDD100K/bdd100k/bdd_data/images/100k/train',
masks_dir='/data/BDD100K/bdd100k/bdd_data/bdd100k/labels/lane/masks/train',
transform=transform
)
val_dataset = BDD100KDataset(
images_dir='/data/BDD100K/bdd100k/bdd_data/images/100k/val',
masks_dir='/data/BDD100K/bdd100k/bdd_data/bdd100k/labels/lane/masks/val',
transform=transform
)
train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=16, shuffle=False)
class UNet(nn.Module):
def __init__(self, in_channels, out_channels):
super(UNet, self).__init__()
def CBR(in_channels, out_channels):
return nn.Sequential(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True),
nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
nn.BatchNorm2d(out_channels),
nn.ReLU(inplace=True)
)
self.enc1 = CBR(in_channels, 64)
self.enc2 = CBR(64, 128)
self.enc3 = CBR(128, 256)
self.enc4 = CBR(256, 512)
self.pool = nn.MaxPool2d(2)
self.bottleneck = CBR(512, 1024)
self.upconv4 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2)
self.dec4 = CBR(1024, 512)
self.upconv3 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2)
self.dec3 = CBR(512, 256)
self.upconv2 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2)
self.dec2 = CBR(256, 128)
self.upconv1 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2)
self.dec1 = CBR(128, 64)
self.conv = nn.Conv2d(64, out_channels, kernel_size=1)
def forward(self, x):
enc1 = self.enc1(x)
enc2 = self.enc2(self.pool(enc1))
enc3 = self.enc3(self.pool(enc2))
enc4 = self.enc4(self.pool(enc3))
bottleneck = self.bottleneck(self.pool(enc4))
dec4 = self.upconv4(bottleneck)
dec4 = torch.cat((dec4, enc4), dim=1)
dec4 = self.dec4(dec4)
dec3 = self.upconv3(dec4)
dec3 = torch.cat((dec3, enc3), dim=1)
dec3 = self.dec3(dec3)
dec2 = self.upconv2(dec3)
dec2 = torch.cat((dec2, enc2), dim=1)
dec2 = self.dec2(dec2)
dec1 = self.upconv1(dec2)
dec1 = torch.cat((dec1, enc1), dim=1)
dec1 = self.dec1(dec1)
return torch.sigmoid(self.conv(dec1))
# Instantiate the model
model = UNet(in_channels=3, out_channels=1).cuda()
def train_model(model, train_loader, val_loader, criterion, optimizer, num_epochs=25, model_path='unet_lane_detection.pth', start_epoch=0):
best_val_loss = float('inf')
for epoch in range(start_epoch, num_epochs):
model.train()
train_loss = 0
train_loader_tqdm = tqdm(train_loader, desc=f'Epoch {epoch+1}/{num_epochs} - Training')
for images, masks in train_loader_tqdm:
images = images.cuda()
masks = masks.cuda()
optimizer.zero_grad()
outputs = model(images)
loss = criterion(outputs, masks)
loss.backward()
optimizer.step()
train_loss += loss.item() * images.size(0)
train_loader_tqdm.set_postfix({'Loss': train_loss / len(train_loader.dataset)})
train_loss = train_loss / len(train_loader.dataset)
model.eval()
val_loss = 0
val_loader_tqdm = tqdm(val_loader, desc=f'Epoch {epoch+1}/{num_epochs} - Validation')
with torch.no_grad():
for images, masks in val_loader_tqdm:
images = images.cuda()
masks = masks.cuda()
outputs = model(images)
loss = criterion(outputs, masks)
val_loss += loss.item() * images.size(0)
val_loader_tqdm.set_postfix({'Loss': val_loss / len(val_loader.dataset)})
val_loss = val_loss / len(val_loader.dataset)
print(f'Epoch {epoch+1}/{num_epochs}, '
f'Train Loss: {train_loss:.4f}, '
f'Val Loss: {val_loss:.4f}')
# Save the model after every epoch
torch.save({
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'epoch': epoch
}, f'unet_lane_detection_epoch_{epoch+1}.pth')
# Additionally, save the best model
if val_loss < best_val_loss:
best_val_loss = val_loss
torch.save({
'model_state_dict': model.state_dict(),
'optimizer_state_dict': optimizer.state_dict(),
'epoch': epoch
}, 'best_unet_lane_detection.pth')
# Criterion and optimizer setup
criterion = nn.BCELoss()
optimizer = optim.Adam(model.parameters(), lr=1e-3)
# Start training
train_model(model, train_loader, val_loader, criterion, optimizer, num_epochs=20, model_path='unet_lane_detection.pth')