ubuntu
commited on
Commit
·
373be07
1
Parent(s):
6dc829b
Added one cycle lr and lr_finder and reduced jitter
Browse files- data_utils.py +2 -2
- lr_finder.py +48 -0
- main.py +14 -3
- utils.py +56 -0
data_utils.py
CHANGED
@@ -8,7 +8,7 @@ def get_train_transform():
|
|
8 |
return A.Compose([
|
9 |
A.RandomResizedCrop(height=224, width=224, scale=(0.08, 1.0), ratio=(3/4, 4/3), p=1.0),
|
10 |
A.HorizontalFlip(p=0.5),
|
11 |
-
A.ColorJitter(brightness=0.
|
12 |
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
13 |
ToTensorV2()
|
14 |
])
|
@@ -28,4 +28,4 @@ def get_data_loaders(train_transform, test_transform, batch_size_train=128, batc
|
|
28 |
testset = datasets.ImageFolder(root='/mnt/imagenet/ILSVRC/Data/CLS-LOC/val', transform=lambda img: test_transform(image=np.array(img))['image'])
|
29 |
testloader = DataLoader(testset, batch_size=batch_size_test, shuffle=False, num_workers=8, pin_memory=True)
|
30 |
|
31 |
-
return trainloader, testloader
|
|
|
8 |
return A.Compose([
|
9 |
A.RandomResizedCrop(height=224, width=224, scale=(0.08, 1.0), ratio=(3/4, 4/3), p=1.0),
|
10 |
A.HorizontalFlip(p=0.5),
|
11 |
+
A.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.05, p=0.8),
|
12 |
A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
|
13 |
ToTensorV2()
|
14 |
])
|
|
|
28 |
testset = datasets.ImageFolder(root='/mnt/imagenet/ILSVRC/Data/CLS-LOC/val', transform=lambda img: test_transform(image=np.array(img))['image'])
|
29 |
testloader = DataLoader(testset, batch_size=batch_size_test, shuffle=False, num_workers=8, pin_memory=True)
|
30 |
|
31 |
+
return trainloader, testloader
|
lr_finder.py
ADDED
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.optim as optim
|
3 |
+
import torch.nn as nn
|
4 |
+
from torch.optim.lr_scheduler import OneCycleLR
|
5 |
+
from torchvision import models, datasets, transforms
|
6 |
+
from torch.utils.data import DataLoader
|
7 |
+
|
8 |
+
# Load pretrained ResNet-50
|
9 |
+
model = models.resnet50(pretrained=True)
|
10 |
+
model.fc = nn.Linear(model.fc.in_features, num_classes) # Adjust for your dataset
|
11 |
+
model = model.to('cuda')
|
12 |
+
|
13 |
+
# Define optimizer and loss function
|
14 |
+
optimizer = optim.SGD(model.parameters(), lr=1e-3, momentum=0.9, weight_decay=1e-4)
|
15 |
+
criterion = nn.CrossEntropyLoss()
|
16 |
+
|
17 |
+
# Prepare dataset and DataLoader
|
18 |
+
transform = transforms.Compose([
|
19 |
+
transforms.Resize(256),
|
20 |
+
transforms.CenterCrop(224),
|
21 |
+
transforms.ToTensor(),
|
22 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
23 |
+
])
|
24 |
+
train_dataset = datasets.ImageFolder(root='/path/to/train', transform=transform)
|
25 |
+
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=4)
|
26 |
+
|
27 |
+
# Set One-Cycle LR scheduler
|
28 |
+
epochs = 10
|
29 |
+
steps_per_epoch = len(train_loader)
|
30 |
+
lr_max = 1e-3 # Adjust based on LR Finder or task size
|
31 |
+
|
32 |
+
scheduler = OneCycleLR(optimizer, max_lr=lr_max, epochs=epochs, steps_per_epoch=steps_per_epoch)
|
33 |
+
|
34 |
+
# Training loop
|
35 |
+
for epoch in range(epochs):
|
36 |
+
model.train()
|
37 |
+
for inputs, labels in train_loader:
|
38 |
+
inputs, labels = inputs.to('cuda'), labels.to('cuda')
|
39 |
+
|
40 |
+
optimizer.zero_grad()
|
41 |
+
outputs = model(inputs)
|
42 |
+
loss = criterion(outputs, labels)
|
43 |
+
loss.backward()
|
44 |
+
optimizer.step()
|
45 |
+
scheduler.step() # Update learning rate using One-Cycle policy
|
46 |
+
|
47 |
+
print(f"Epoch {epoch+1}/{epochs} completed.")
|
48 |
+
|
main.py
CHANGED
@@ -6,6 +6,7 @@ from data_utils import get_train_transform, get_test_transform, get_data_loaders
|
|
6 |
from train_test import train, test
|
7 |
from utils import save_checkpoint, load_checkpoint, plot_training_curves, plot_misclassified_samples
|
8 |
from torchsummary import summary
|
|
|
9 |
|
10 |
def main():
|
11 |
# Initialize model, loss function, and optimizer
|
@@ -15,7 +16,8 @@ def main():
|
|
15 |
model = model.to(device)
|
16 |
summary(model, input_size=(3, 224, 224))
|
17 |
criterion = nn.CrossEntropyLoss()
|
18 |
-
optimizer = optim.SGD(model.parameters(), lr=
|
|
|
19 |
|
20 |
# Load data
|
21 |
train_transform = get_train_transform()
|
@@ -34,8 +36,16 @@ def main():
|
|
34 |
results = []
|
35 |
learning_rates = []
|
36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
# Training loop
|
38 |
-
for epoch in range(start_epoch,
|
39 |
train_accuracy1, train_accuracy5, train_loss = train(model, device, trainloader, optimizer, criterion, epoch)
|
40 |
test_accuracy1, test_accuracy5, test_loss, misclassified_images, misclassified_labels, misclassified_preds = test(model, device, testloader, criterion)
|
41 |
print(f'Epoch {epoch} | Train Top-1 Acc: {train_accuracy1:.2f} | Test Top-1 Acc: {test_accuracy1:.2f}')
|
@@ -43,7 +53,8 @@ def main():
|
|
43 |
# Append results for this epoch
|
44 |
results.append((epoch, train_accuracy1, train_accuracy5, test_accuracy1, test_accuracy5, train_loss, test_loss))
|
45 |
learning_rates.append(optimizer.param_groups[0]['lr'])
|
46 |
-
|
|
|
47 |
# Save checkpoint
|
48 |
save_checkpoint(model, optimizer, epoch, test_loss, checkpoint_path)
|
49 |
|
|
|
6 |
from train_test import train, test
|
7 |
from utils import save_checkpoint, load_checkpoint, plot_training_curves, plot_misclassified_samples
|
8 |
from torchsummary import summary
|
9 |
+
from torch.optim.lr_scheduler import OneCycleLR
|
10 |
|
11 |
def main():
|
12 |
# Initialize model, loss function, and optimizer
|
|
|
16 |
model = model.to(device)
|
17 |
summary(model, input_size=(3, 224, 224))
|
18 |
criterion = nn.CrossEntropyLoss()
|
19 |
+
optimizer = optim.SGD(model.parameters(), lr=1e-3, momentum=0.9, weight_decay=1e-4)
|
20 |
+
|
21 |
|
22 |
# Load data
|
23 |
train_transform = get_train_transform()
|
|
|
36 |
results = []
|
37 |
learning_rates = []
|
38 |
|
39 |
+
# Set One-Cycle LR scheduler
|
40 |
+
num_epochs = 10
|
41 |
+
steps_per_epoch = len(trainloader)
|
42 |
+
lr_max = 1e-2
|
43 |
+
|
44 |
+
scheduler = OneCycleLR(optimizer, max_lr=lr_max, epochs=num_epochs, steps_per_epoch=steps_per_epoch)
|
45 |
+
|
46 |
+
|
47 |
# Training loop
|
48 |
+
for epoch in range(start_epoch+1, start_epoch + num_epochs):
|
49 |
train_accuracy1, train_accuracy5, train_loss = train(model, device, trainloader, optimizer, criterion, epoch)
|
50 |
test_accuracy1, test_accuracy5, test_loss, misclassified_images, misclassified_labels, misclassified_preds = test(model, device, testloader, criterion)
|
51 |
print(f'Epoch {epoch} | Train Top-1 Acc: {train_accuracy1:.2f} | Test Top-1 Acc: {test_accuracy1:.2f}')
|
|
|
53 |
# Append results for this epoch
|
54 |
results.append((epoch, train_accuracy1, train_accuracy5, test_accuracy1, test_accuracy5, train_loss, test_loss))
|
55 |
learning_rates.append(optimizer.param_groups[0]['lr'])
|
56 |
+
|
57 |
+
scheduler.step()
|
58 |
# Save checkpoint
|
59 |
save_checkpoint(model, optimizer, epoch, test_loss, checkpoint_path)
|
60 |
|
utils.py
CHANGED
@@ -65,3 +65,59 @@ def plot_misclassified_samples(misclassified_images, misclassified_labels, miscl
|
|
65 |
plt.title("Misclassified Samples")
|
66 |
plt.axis('off')
|
67 |
plt.show()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
65 |
plt.title("Misclassified Samples")
|
66 |
plt.axis('off')
|
67 |
plt.show()
|
68 |
+
|
69 |
+
def find_lr(model, criterion, optimizer, train_loader, num_epochs=1, start_lr=1e-7, end_lr=10, lr_multiplier=1.1):
|
70 |
+
"""
|
71 |
+
Find the optimal learning rate using LR Finder.
|
72 |
+
|
73 |
+
Args:
|
74 |
+
- model: The model to train
|
75 |
+
- criterion: Loss function (e.g., CrossEntropyLoss)
|
76 |
+
- optimizer: Optimizer (e.g., SGD)
|
77 |
+
- train_loader: DataLoader for training data
|
78 |
+
- num_epochs: Number of epochs to run the LR Finder (typically 1-2)
|
79 |
+
- start_lr: Starting learning rate for the experiment
|
80 |
+
- end_lr: Maximum learning rate (used for scaling)
|
81 |
+
- lr_multiplier: Factor by which the learning rate is increased every batch
|
82 |
+
|
83 |
+
Returns:
|
84 |
+
- A plot of loss vs learning rate
|
85 |
+
"""
|
86 |
+
lrs = []
|
87 |
+
losses = []
|
88 |
+
avg_loss = 0.0
|
89 |
+
batch_count = 0
|
90 |
+
|
91 |
+
lr = start_lr
|
92 |
+
for epoch in range(num_epochs):
|
93 |
+
model.train()
|
94 |
+
for inputs, labels in train_loader:
|
95 |
+
inputs, labels = inputs.to(device), labels.to(device)
|
96 |
+
optimizer.param_groups[0]['lr'] = lr # Set the learning rate
|
97 |
+
|
98 |
+
# Forward pass
|
99 |
+
optimizer.zero_grad()
|
100 |
+
outputs = model(inputs)
|
101 |
+
loss = criterion(outputs, labels)
|
102 |
+
loss.backward()
|
103 |
+
optimizer.step()
|
104 |
+
|
105 |
+
avg_loss += loss.item()
|
106 |
+
batch_count += 1
|
107 |
+
lrs.append(lr)
|
108 |
+
losses.append(loss.item())
|
109 |
+
|
110 |
+
# Increase the learning rate for next batch
|
111 |
+
lr *= lr_multiplier
|
112 |
+
|
113 |
+
avg_loss /= batch_count
|
114 |
+
print(f"Epoch [{epoch+1}/{num_epochs}], Avg Loss: {avg_loss:.4f}")
|
115 |
+
|
116 |
+
# Plot the loss vs learning rate
|
117 |
+
plt.plot(lrs, losses)
|
118 |
+
plt.xscale('log')
|
119 |
+
plt.xlabel('Learning Rate')
|
120 |
+
plt.ylabel('Loss')
|
121 |
+
plt.title('Learning Rate Finder')
|
122 |
+
plt.show()
|
123 |
+
|