Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,160 +1,51 @@
|
|
| 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 |
-
#
|
| 13 |
-
|
| 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 |
-
|
| 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(
|
| 55 |
)
|
|
|
|
| 56 |
model.to(device)
|
|
|
|
| 57 |
|
| 58 |
-
#
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 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 |
-
#
|
| 101 |
-
def
|
| 102 |
-
|
| 103 |
-
running_loss, correct_preds, total_preds = 0.0, 0, 0
|
| 104 |
with torch.no_grad():
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 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 |
-
|
| 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}")
|
|
|
|
|
|
|
|
|
|
| 1 |
import torch
|
| 2 |
import torch.nn as nn
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import timm
|
| 4 |
+
import gradio as gr
|
| 5 |
+
from torchvision import transforms
|
| 6 |
+
from PIL import Image
|
| 7 |
|
| 8 |
+
# Define class labels
|
| 9 |
+
class_names = ['Bacteria', 'Fungi', 'Healthy', 'Nematode', 'Pest', 'Phytopthora', 'Virus']
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
+
# Load model
|
|
|
|
|
|
|
|
|
|
| 12 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 13 |
+
model = timm.create_model('mobilenetv3_large_100', pretrained=False)
|
|
|
|
|
|
|
|
|
|
| 14 |
model.classifier = nn.Sequential(
|
| 15 |
+
nn.Linear(model.classifier.in_features, 512),
|
| 16 |
nn.ReLU(),
|
| 17 |
nn.Dropout(0.3),
|
| 18 |
+
nn.Linear(512, len(class_names))
|
| 19 |
)
|
| 20 |
+
model.load_state_dict(torch.load('best_model.pth', map_location=device))
|
| 21 |
model.to(device)
|
| 22 |
+
model.eval()
|
| 23 |
|
| 24 |
+
# Transform for input image
|
| 25 |
+
transform = transforms.Compose([
|
| 26 |
+
transforms.Resize(256),
|
| 27 |
+
transforms.CenterCrop(224),
|
| 28 |
+
transforms.ToTensor(),
|
| 29 |
+
transforms.Normalize([0.485, 0.456, 0.406],
|
| 30 |
+
[0.229, 0.224, 0.225])
|
| 31 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
# Inference function
|
| 34 |
+
def predict(image):
|
| 35 |
+
image = transform(image).unsqueeze(0).to(device)
|
|
|
|
| 36 |
with torch.no_grad():
|
| 37 |
+
outputs = model(image)
|
| 38 |
+
_, predicted = torch.max(outputs, 1)
|
| 39 |
+
confidence = torch.softmax(outputs, dim=1)[0][predicted.item()].item()
|
| 40 |
+
return {class_names[predicted.item()]: float(confidence)}
|
| 41 |
+
|
| 42 |
+
# Gradio interface
|
| 43 |
+
interface = gr.Interface(
|
| 44 |
+
fn=predict,
|
| 45 |
+
inputs=gr.Image(type="pil"),
|
| 46 |
+
outputs=gr.Label(num_top_classes=3),
|
| 47 |
+
title="Potato Leaf Disease Classification",
|
| 48 |
+
description="Upload an image of a potato leaf to detect the disease type."
|
| 49 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
+
interface.launch()
|
|
|
|
|
|
|
|
|