{"id":27194812,"url":"https://github.com/deepsalunkhee/plantdiseasedetection","last_synced_at":"2026-04-02T03:08:57.188Z","repository":{"id":285226093,"uuid":"948441697","full_name":"deepsalunkhee/PlantDiseaseDetection","owner":"deepsalunkhee","description":"A Classification model for planet disease detection along  web app for the same 🌿","archived":false,"fork":false,"pushed_at":"2025-04-14T11:52:59.000Z","size":78561,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2026-01-03T14:38:21.847Z","etag":null,"topics":["cnn-classification","express","python","pytorch","react","resnet"],"latest_commit_sha":null,"homepage":"https://pdd.deepsalunkhee.com","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/deepsalunkhee.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-03-14T10:46:49.000Z","updated_at":"2025-04-14T11:53:03.000Z","dependencies_parsed_at":"2025-06-26T06:48:01.108Z","dependency_job_id":null,"html_url":"https://github.com/deepsalunkhee/PlantDiseaseDetection","commit_stats":null,"previous_names":["deepsalunkhee/plantdiseasedetection"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/deepsalunkhee/PlantDiseaseDetection","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepsalunkhee%2FPlantDiseaseDetection","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepsalunkhee%2FPlantDiseaseDetection/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepsalunkhee%2FPlantDiseaseDetection/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepsalunkhee%2FPlantDiseaseDetection/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/deepsalunkhee","download_url":"https://codeload.github.com/deepsalunkhee/PlantDiseaseDetection/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/deepsalunkhee%2FPlantDiseaseDetection/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31294875,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-02T01:43:37.129Z","status":"online","status_checked_at":"2026-04-02T02:00:08.535Z","response_time":89,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cnn-classification","express","python","pytorch","react","resnet"],"created_at":"2025-04-09T19:36:35.194Z","updated_at":"2026-04-02T03:08:57.173Z","avatar_url":"https://github.com/deepsalunkhee.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Plant Disease Classification using ResNet-9 🌱\n\nThis repository contains a deep learning model for classifying plant diseases from leaf images using a custom ResNet-9 architecture implemented in PyTorch. The model can identify 38 different classes comprising healthy and diseased leaves across 14 different plant types.\n\n## Dataset Overview 📊\n\nThe model is trained on the PlantVillage dataset, which includes approximately 87,000 RGB images of healthy and diseased crop leaves. Key dataset characteristics:\n\n- **Classes**: 38 different classes (plant + disease combinations)\n- **Plants**: 14 unique plant types\n- **Diseases**: 26 different plant diseases\n- **Image size**: 256x256 RGB images\n- **Split**: 80/20 training/validation ratio\n- **Data distribution**: Fairly balanced across classes (~1,600-2,000 images per class)\n\n## Model Architecture 🏗️\n\nThe implementation uses a custom ResNet-9 architecture with residual connections:\n![Architecture](https://www.mdpi.com/remotesensing/remotesensing-11-01896/article_deploy/html/images/remotesensing-11-01896-g001.png)\n### Key Components\n\n1. **Convolutional Blocks**: Each block consists of:\n   - 2D Convolution\n   - Batch Normalization\n   - ReLU Activation\n   - Optional MaxPooling (stride 4)\n\n2. **Residual Blocks**: Two residual blocks that implement skip connections:\n   - First residual block after the second conv layer (128 channels)\n   - Second residual block after the fourth conv layer (512 channels)\n\n3. **Classifier**: Final classification head consisting of:\n   - MaxPooling\n   - Flatten\n   - Linear layer (512 to 38 classes)\n\n### Network Structure\n\n```\nResNet9(\n  (conv1): Sequential(Conv2d, BatchNorm2d, ReLU)\n  (conv2): Sequential(Conv2d, BatchNorm2d, ReLU, MaxPool2d) [Output: 128 x 64 x 64]\n  (res1): Sequential(\n    ConvBlock(128, 128),\n    ConvBlock(128, 128)\n  )\n  (conv3): Sequential(Conv2d, BatchNorm2d, ReLU, MaxPool2d) [Output: 256 x 16 x 16]\n  (conv4): Sequential(Conv2d, BatchNorm2d, ReLU, MaxPool2d) [Output: 512 x 4 x 4]\n  (res2): Sequential(\n    ConvBlock(512, 512),\n    ConvBlock(512, 512)\n  )\n  (classifier): Sequential(MaxPool2d, Flatten, Linear(512, 38))\n)\n```\n\n### Model Parameters\n- Total parameters: 6,589,734\n- Trainable parameters: 6,589,734\n- Input size: 0.75 MB\n- Forward/backward pass size: 343.95 MB\n- Parameters size: 25.14 MB\n\n## Training Methodology 🔄\n\nThe model was trained using several advanced techniques:\n\n### Optimization Strategy\n\n1. **One Cycle Learning Rate Policy**:\n   - Starting with a low learning rate\n   - Gradually increasing to a high rate (0.01) for ~30% of epochs\n   - Gradually decreasing to a very low value for remaining epochs\n   - Helps in faster convergence and better generalization\n\n2. **Weight Decay**: \n   - Value: 1e-4\n   - Prevents overfitting by penalizing large weights\n\n3. **Gradient Clipping**:\n   - Value: 0.1\n   - Prevents exploding gradients by limiting their magnitude\n\n4. **Optimizer**:\n   - Adam optimizer with initial max_lr of 0.01\n\n### Training Configuration\n\n- Batch size: 32\n- Epochs: 2 (achieved high accuracy very quickly)\n- Random seed: 7 (for reproducibility)\n- Loss function: Cross-Entropy Loss\n- Device: CUDA (GPU acceleration)\n\n## Performance Results 📈\n\nThe model achieved impressive results in a short training time:\n\n- Final validation accuracy: **99.23%**\n- Final validation loss: **0.0269**\n- Training time: ~20 minutes on P100 GPU\n- Test accuracy: **100%** (on a small test set of 33 images)\n\n### Learning Curves\n\nThe model showed rapid convergence:\n- Training loss decreased from 0.7466 to 0.1248\n- Validation loss decreased from 0.5865 to 0.0269\n- Validation accuracy increased from 83.19% to 99.23%\n\n## Model Usage Guide 🚀\n\n### Prerequisites\n\n```python\nimport torch\nimport torchvision.transforms as transforms\nfrom PIL import Image\n```\n\n### Loading the Model\n\n```python\n# Method 1: Load state_dict (recommended)\nmodel = ResNet9(3, 38)  # Create an instance of the model\nmodel.load_state_dict(torch.load('plant-disease-model.pth'))\n\n# Method 2: Load entire model\nmodel = torch.load('plant-disease-model-complete.pth')\n\n# Set to evaluation mode\nmodel.eval()\n```\n\n### Prediction Function\n\n```python\ndef predict_image(img, model):\n    \"\"\"\n    Predicts class for a single image\n    \n    Args:\n        img (torch.Tensor): Image tensor of shape [3, 256, 256]\n        model: Trained model\n        \n    Returns:\n        str: Predicted class name\n    \"\"\"\n    # Convert to batch of size 1\n    xb = img.unsqueeze(0)\n    # Get predictions\n    yb = model(xb)\n    # Get index of highest probability\n    _, preds = torch.max(yb, dim=1)\n    # Return class name\n    return classes[preds[0].item()]\n```\n\n### Example Usage\n\n```python\n# Load and preprocess image\ntransform = transforms.ToTensor()\nimg = Image.open('leaf_image.jpg')\nimg = transform(img)\n\n# Make prediction\npredicted_class = predict_image(img, model)\nprint(f\"Predicted disease: {predicted_class}\")\n```\n\n## Implementation Details 💻\n\n### Base Class for Training\n\n```python\nclass ImageClassificationBase(nn.Module):\n    def training_step(self, batch):\n        images, labels = batch\n        out = self(images)\n        loss = F.cross_entropy(out, labels)\n        return loss\n        \n    def validation_step(self, batch):\n        images, labels = batch\n        out = self(images)\n        loss = F.cross_entropy(out, labels)\n        acc = accuracy(out, labels)\n        return {\"val_loss\": loss.detach(), \"val_accuracy\": acc}\n        \n    def validation_epoch_end(self, outputs):\n        batch_losses = [x[\"val_loss\"] for x in outputs]\n        batch_accuracy = [x[\"val_accuracy\"] for x in outputs]\n        epoch_loss = torch.stack(batch_losses).mean()\n        epoch_accuracy = torch.stack(batch_accuracy).mean()\n        return {\"val_loss\": epoch_loss, \"val_accuracy\": epoch_accuracy}\n        \n    def epoch_end(self, epoch, result):\n        print(\"Epoch [{}], last_lr: {:.5f}, train_loss: {:.4f}, val_loss: {:.4f}, val_acc: {:.4f}\".format(\n            epoch, result['lrs'][-1], result['train_loss'], result['val_loss'], result['val_accuracy']))\n```\n\n### Helper Functions\n\n```python\n# Convolution block with BatchNormalization\ndef ConvBlock(in_channels, out_channels, pool=False):\n    layers = [\n        nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),\n        nn.BatchNorm2d(out_channels),\n        nn.ReLU(inplace=True)\n    ]\n    if pool:\n        layers.append(nn.MaxPool2d(4))\n    return nn.Sequential(*layers)\n\n# Accuracy calculation\ndef accuracy(outputs, labels):\n    _, preds = torch.max(outputs, dim=1)\n    return torch.tensor(torch.sum(preds == labels).item() / len(preds))\n```\n\n## Advantages of This Architecture 🌟\n\n1. **Efficient Design**: Achieves high accuracy with fewer parameters than standard ResNets\n2. **Fast Training**: Converges in just 2 epochs due to effective training strategies\n3. **High Accuracy**: 99%+ validation accuracy and perfect test set performance\n4. **Residual Connections**: Help in preventing the vanishing gradient problem\n5. **Batch Normalization**: Accelerates training and improves stability\n\n## Potential Applications 🌾\n\n- Automated disease diagnosis in agricultural settings\n- Mobile applications for farmers to identify plant diseases in the field\n- Integration with IoT devices for continuous crop monitoring\n- Early warning systems for disease outbreak prevention\n- Research tool for plant pathologists\n\n## Future Improvements 🔍\n\n1. **Data Augmentation**: Apply more aggressive augmentation techniques\n2. **Transfer Learning**: Compare with pre-trained models like ResNet-50\n3. **Model Pruning**: Reduce model size for mobile deployment\n4. **Grad-CAM Visualization**: Implement for better interpretability of decisions\n5. **Balanced Dataset**: Ensure equal representation across all classes\n6. **Deployment**: Create a web or mobile application interface\n\n## Citation ✍️\n\nIf you use this model or code, please cite the original PlantVillage dataset:\n\n```\nHughes, D., \u0026 Salathé, M. (2015). An open access repository of images on plant health to enable the development of mobile disease diagnostics. arXiv preprint arXiv:1511.08060.\n```\n\n## License 📄\n\nThis project is licensed under the MIT License - see the LICENSE file for details.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepsalunkhee%2Fplantdiseasedetection","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdeepsalunkhee%2Fplantdiseasedetection","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdeepsalunkhee%2Fplantdiseasedetection/lists"}