Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import torch.nn as nn
|
5 |
+
import torch.optim as optim
|
6 |
+
from torch.utils.data import DataLoader
|
7 |
+
from torchvision import datasets, transforms
|
8 |
+
from tqdm import tqdm
|
9 |
+
import matplotlib.pyplot as plt
|
10 |
+
import timm
|
11 |
+
|
12 |
+
# Data augmentation and normalization
|
13 |
+
transform_train = transforms.Compose([
|
14 |
+
transforms.RandomResizedCrop(224, scale=(0.8, 1.0)),
|
15 |
+
transforms.RandomHorizontalFlip(),
|
16 |
+
transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),
|
17 |
+
transforms.RandomRotation(15),
|
18 |
+
transforms.RandomAffine(degrees=15, translate=(0.1, 0.1)),
|
19 |
+
transforms.GaussianBlur(kernel_size=3),
|
20 |
+
transforms.ToTensor(),
|
21 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
22 |
+
std=[0.229, 0.224, 0.225]),
|
23 |
+
])
|
24 |
+
|
25 |
+
transform_val = transforms.Compose([
|
26 |
+
transforms.Resize(224),
|
27 |
+
transforms.CenterCrop(224),
|
28 |
+
transforms.ToTensor(),
|
29 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
30 |
+
std=[0.229, 0.224, 0.225]),
|
31 |
+
])
|
32 |
+
|
33 |
+
# Dataset loading
|
34 |
+
train_dir = 'D:\\Dataset\\Potato Leaf Disease Dataset in Uncontrolled Environment'
|
35 |
+
full_ds = datasets.ImageFolder(train_dir, transform=transform_train)
|
36 |
+
train_size = int(0.8 * len(full_ds))
|
37 |
+
val_size = len(full_ds) - train_size
|
38 |
+
train_ds, val_ds = torch.utils.data.random_split(full_ds, [train_size, val_size])
|
39 |
+
val_ds.dataset.transform = transform_val # Apply validation transforms
|
40 |
+
|
41 |
+
train_loader = DataLoader(train_ds, batch_size=32, shuffle=True, num_workers=4)
|
42 |
+
val_loader = DataLoader(val_ds, batch_size=32, shuffle=False, num_workers=4)
|
43 |
+
|
44 |
+
# Device
|
45 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
46 |
+
|
47 |
+
# Model definition with custom classification head (optional improvement)
|
48 |
+
model = timm.create_model('mobilenetv3_large_100', pretrained=True)
|
49 |
+
in_features = model.classifier.in_features
|
50 |
+
model.classifier = nn.Sequential(
|
51 |
+
nn.Linear(in_features, 512),
|
52 |
+
nn.ReLU(),
|
53 |
+
nn.Dropout(0.3),
|
54 |
+
nn.Linear(512, len(full_ds.classes))
|
55 |
+
)
|
56 |
+
model.to(device)
|
57 |
+
|
58 |
+
# Loss and optimizer
|
59 |
+
criterion = nn.CrossEntropyLoss()
|
60 |
+
optimizer = optim.Adam(model.parameters(), lr=1e-4)
|
61 |
+
scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='max', factor=0.5, patience=3)
|
62 |
+
|
63 |
+
# MixUp augmentation
|
64 |
+
def mixup_data(x, y, alpha=1.0):
|
65 |
+
if alpha > 0:
|
66 |
+
lam = np.random.beta(alpha, alpha)
|
67 |
+
else:
|
68 |
+
lam = 1
|
69 |
+
batch_size = x.size(0)
|
70 |
+
index = torch.randperm(batch_size).to(x.device)
|
71 |
+
mixed_x = lam * x + (1 - lam) * x[index, :]
|
72 |
+
y_a, y_b = y, y[index]
|
73 |
+
return mixed_x, y_a, y_b, lam
|
74 |
+
|
75 |
+
def mixup_criterion(criterion, pred, y_a, y_b, lam):
|
76 |
+
return lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)
|
77 |
+
|
78 |
+
# Training function with MixUp
|
79 |
+
def train_epoch(model, train_loader, criterion, optimizer):
|
80 |
+
model.train()
|
81 |
+
running_loss, correct_preds, total_preds = 0.0, 0, 0
|
82 |
+
for inputs, labels in tqdm(train_loader, desc="Training Epoch", leave=False):
|
83 |
+
inputs, labels = inputs.to(device), labels.to(device)
|
84 |
+
inputs, targets_a, targets_b, lam = mixup_data(inputs, labels, alpha=1.0)
|
85 |
+
|
86 |
+
optimizer.zero_grad()
|
87 |
+
outputs = model(inputs)
|
88 |
+
loss = mixup_criterion(criterion, outputs, targets_a, targets_b, lam)
|
89 |
+
loss.backward()
|
90 |
+
optimizer.step()
|
91 |
+
|
92 |
+
_, preds = torch.max(outputs, 1)
|
93 |
+
correct_preds += (lam * preds.eq(targets_a).sum().item()
|
94 |
+
+ (1 - lam) * preds.eq(targets_b).sum().item())
|
95 |
+
total_preds += labels.size(0)
|
96 |
+
running_loss += loss.item()
|
97 |
+
|
98 |
+
return running_loss / len(train_loader), correct_preds / total_preds
|
99 |
+
|
100 |
+
# Validation function
|
101 |
+
def validate_epoch(model, val_loader, criterion):
|
102 |
+
model.eval()
|
103 |
+
running_loss, correct_preds, total_preds = 0.0, 0, 0
|
104 |
+
with torch.no_grad():
|
105 |
+
for inputs, labels in tqdm(val_loader, desc="Validating Epoch", leave=False):
|
106 |
+
inputs, labels = inputs.to(device), labels.to(device)
|
107 |
+
outputs = model(inputs)
|
108 |
+
loss = criterion(outputs, labels)
|
109 |
+
_, preds = torch.max(outputs, 1)
|
110 |
+
correct_preds += (preds == labels).sum().item()
|
111 |
+
total_preds += labels.size(0)
|
112 |
+
running_loss += loss.item()
|
113 |
+
return running_loss / len(val_loader), correct_preds / total_preds
|
114 |
+
|
115 |
+
# Plotting
|
116 |
+
def plot_metrics(train_loss, val_loss, train_acc, val_acc):
|
117 |
+
epochs = range(1, len(train_loss) + 1)
|
118 |
+
plt.figure(figsize=(12, 5))
|
119 |
+
plt.subplot(1, 2, 1)
|
120 |
+
plt.plot(epochs, train_loss, label='Training Loss')
|
121 |
+
plt.plot(epochs, val_loss, label='Validation Loss')
|
122 |
+
plt.xlabel('Epochs')
|
123 |
+
plt.ylabel('Loss')
|
124 |
+
plt.legend()
|
125 |
+
plt.subplot(1, 2, 2)
|
126 |
+
plt.plot(epochs, train_acc, label='Training Accuracy')
|
127 |
+
plt.plot(epochs, val_acc, label='Validation Accuracy')
|
128 |
+
plt.xlabel('Epochs')
|
129 |
+
plt.ylabel('Accuracy')
|
130 |
+
plt.legend()
|
131 |
+
plt.show()
|
132 |
+
|
133 |
+
# Training loop
|
134 |
+
num_epochs = 20
|
135 |
+
train_losses, val_losses = [], []
|
136 |
+
train_accuracies, val_accuracies = [], []
|
137 |
+
|
138 |
+
for epoch in range(num_epochs):
|
139 |
+
print(f"\nEpoch {epoch+1}/{num_epochs}")
|
140 |
+
train_loss, train_acc = train_epoch(model, train_loader, criterion, optimizer)
|
141 |
+
val_loss, val_acc = validate_epoch(model, val_loader, criterion)
|
142 |
+
scheduler.step(val_acc)
|
143 |
+
|
144 |
+
print(f"Train Loss: {train_loss:.4f}, Accuracy: {train_acc:.4f}")
|
145 |
+
print(f"Val Loss: {val_loss:.4f}, Accuracy: {val_acc:.4f}")
|
146 |
+
|
147 |
+
train_losses.append(train_loss)
|
148 |
+
val_losses.append(val_loss)
|
149 |
+
train_accuracies.append(train_acc)
|
150 |
+
val_accuracies.append(val_acc)
|
151 |
+
|
152 |
+
plot_metrics(train_losses, val_losses, train_accuracies, val_accuracies)
|
153 |
+
best_val_acc = 0.0
|
154 |
+
save_path = 'D:\\Dataset\\Potato Leaf Disease Dataset in Uncontrolled Environment\\best_model.pth'
|
155 |
+
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
156 |
+
|
157 |
+
if val_acc > best_val_acc:
|
158 |
+
best_val_acc = val_acc
|
159 |
+
torch.save(model.state_dict(), save_path)
|
160 |
+
print(f"✅ Best model saved with val_acc: {val_acc:.4f}")
|