{
  "fetched_at": "2026-10-19T06:27:59Z",
  "source_url": "https://www.kaggle.com/competitions/computer-vision-xm/data",
  "pages": [
    {
      "name": "data-description",
      "content": "Plant disease detection via computer vision could be a very important to protecting the agriculture industry. This dataset contains 4235 images of healthy and/or diseased leaves. Within this dataset, there are 10 different plant species with a variety of leaf shapes and degrees of disease progression. There are 3 csv files: train, test, and sample_submission. The train file has one column being the image (with the image_id) and the other being the label (0: healthy and 1: for diseased), the test file only having the image column (no answers).\n\n## Files\n\n*   **train.csv** - the training set\n*   **test.csv** - the test set\n*   **sample_submission.csv** - a sample submission file in the correct format\n\n## Columns\n\n*   `Images` - JPG image id\n*   `Labels` - 0: healthy and 1: diseased\n\n## Data Source\nDataset modified from the \"Healthy vs. Diseased Leaf Image Dataset\" (License CC0: Public domain) on Kaggle at https://www.kaggle.com/datasets/amandam1/healthy-vs-diseased-leaf-image-dataset ",
      "isPublished": false,
      "hasIsPublished": false,
      "postTitle": "",
      "hasPostTitle": false,
      "mimeType": "",
      "hasMimeType": false
    },
    {
      "name": "Description",
      "content": "In this lab, you will design a CNN that can detect diseased or healthy plant leaves. \n\n#**Computer Vision**\n\"Computer vision is an area of machine learning dedicated to interpreting and understanding images and video. It is used to help teach computers to “see” and to use visual information to perform visual tasks that humans can.\" (https://www.run.ai/guides/deep-learning-for-computer-vision#:~:text=Computer%20vision%20algorithms%20analyze%20certain,commonly%20used%20for%20computer%20vision.) \n\nThe link above is a great source to learn more about computer vision and how the CNN behind it work.\n\n# **Code Example**\n**Prepare Dataloader**\n```\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nimport torchvision.models as models\nfrom torch.utils.data import DataLoader, Dataset, random_split\nimport pandas as pd\nimport os\nfrom PIL import Image\nfrom tqdm import tqdm\nimport random\nimport numpy as np\nfrom sklearn.metrics import accuracy_score\n\n# Set random seed for reproducibility\nseed = 42\nrandom.seed(seed)\nnp.random.seed(seed)\ntorch.manual_seed(seed)\nif torch.cuda.is_available():\n    torch.cuda.manual_seed(seed)\n    torch.cuda.manual_seed_all(seed)\n\nclass CustomDataset(Dataset):\n    def __init__(self, csv_file, img_dir, transform=None):\n        self.labels_df = pd.read_csv(csv_file)\n        self.img_dir = img_dir\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.labels_df)\n\n    def __getitem__(self, idx):\n        img_name = self.labels_df.iloc[idx, 1]\n        img_path = os.path.join(self.img_dir, img_name)\n        image = Image.open(img_path)\n        label = self.labels_df.iloc[idx, 2] if 'Labels' in self.labels_df.columns else -1\n\n        if self.transform:\n            image = self.transform(image)\n\n        return image, label\n\n# Data augmentation and normalization for training\ntransform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.RandomHorizontalFlip(),\n    #transforms.RandomCrop(32, padding=4),\n    #transforms.ColorJitter(brightness=0.2, contrast=0.2, saturation=0.2, hue=0.2),\n    transforms.ToTensor(),\n    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n])\n\nbatch_size = 32\n\ntrain_dataset = CustomDataset(csv_file='/kaggle/input/computer-vision-xm/train.csv', img_dir='/kaggle/input/computer-vision-xm/images/kaggle/working/Reorganized_Data/images', transform=transform)\ntest_dataset = CustomDataset(csv_file='/kaggle/input/computer-vision-xm/test.csv', img_dir='/kaggle/input/computer-vision-xm/images/kaggle/working/Reorganized_Data/images', transform=transform)\n\n# Split the training dataset into training and validation sets\ntrain_size = int(0.8 * len(train_dataset))\nval_size = len(train_dataset) - train_size\ntrain_dataset, val_dataset = random_split(train_dataset, [train_size, val_size])\n\n# Create data loaders\ntrain_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)\nval_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=False)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False)\n```\n\n**Prepare Model**\n```\nclass CNN(nn.Module):\n```\n\n**Start Training**\n```\n# Calculate the total number of parameters\ntotal_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\nprint(f'Total number of parameters: {total_params}')\n\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.AdamW(model.parameters(), lr=0.001)\n\n# Move the model to GPU if available\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(device)\nmodel.to(device)\n\n# Training loop with early stopping\nepochs = 20\npatience = 10\nbest_val_loss = float('inf')\npatience_counter = 0\n\nfor epoch in range(epochs):\n    print(f'Epoch {epoch + 1}/{epochs}')\n    model.train()\n    running_loss = 0.0\n    for images, labels in tqdm(train_loader, desc=\"Training\"):\n        images, labels = images.to(device), labels.to(device)\n\n        # Zero gradients\n        optimizer.zero_grad()\n\n        # Forward pass\n        outputs = model(images)\n        loss = criterion(outputs, labels)\n        running_loss += loss.item()\n\n        # Backward pass\n        loss.backward()\n        optimizer.step()\n    \n    print(f'Training loss: {running_loss / len(train_loader)}')\n\n    # Validation loop\n    model.eval()\n    val_loss = 0.0\n    correct = 0\n    total = 0\n    with torch.no_grad():\n        for images, labels in tqdm(val_loader, desc=\"Validation\"):\n            images, labels = images.to(device), labels.to(device)\n\n            outputs = model(images)\n            loss = criterion(outputs, labels)\n            val_loss += loss.item()\n\n            # Convert the outputs to predicted class labels\n            _, predicted = torch.max(outputs, 1)\n\n            total += labels.size(0)\n            correct += (predicted == labels).sum().item()\n\n    val_accuracy = correct / total\n    print(f'Validation loss: {val_loss / len(val_loader)}')\n    print(f'Validation accuracy: {val_accuracy:.4f}')\n\n    # Early stopping\n    if val_loss < best_val_loss:\n        best_val_loss = val_loss\n        patience_counter = 0\n        torch.save(model.state_dict(), 'best_model.pth')\n        print(f'Best model saved with valid loss of {val_loss / len(val_loader)}')\n    else:\n        patience_counter += 1\n        if patience_counter >= patience:\n            print(\"Early stopping triggered\")\n            break\n```\n\n**Evaluate Performance**\n```\n# Load the best model\nmodel.load_state_dict(torch.load('best_model.pth'))\nmodel.to(device)\n\n# Make predictions on the test dataset\nmodel.eval()\npredictions = []\nwith torch.no_grad():\n    for images, _ in test_loader:\n        images = images.to(device)\n        outputs = model(images)\n        _, predicted = torch.max(outputs, 1)\n        predictions.extend(predicted.cpu().numpy())\n\n# Create a DataFrame with IDs and predictions\nsubmission_df = pd.DataFrame({\n    'Images': test_dataset.labels_df['Images'],\n    'Labels': predictions\n})\nsubmission_df.to_csv('submission.csv', index=False)\nprint('Submission file was created.')\n```\n\n# **Instructions**\n1. Load and look through the data\n2. I suggest some potential image augmentation, this is a large dataset\n3. Design a CNN that is able to accurately detect diseased and healthy leaves (Example above)\n- Try and find parameters that will give the best accuracy \n4. Look at sample submission on what you submission should look like ",
      "isPublished": false,
      "hasIsPublished": false,
      "postTitle": "",
      "hasPostTitle": false,
      "mimeType": "",
      "hasMimeType": false
    },
    {
      "name": "Evaluation",
      "content": "This lab will be graded on accuracy, the percentage of times the model is able to correctly identify diseased and healthy leaves. \n\n---\n\n## Submission File\nFor each ID in the test set, you must predict a probability for the TARGET variable. The file should contain a header and have the following format:\n\n         Images        Labels\n    1  0011_0100.JPG    0\n    2  0009_0053.JPG    1\n    etc.",
      "isPublished": false,
      "hasIsPublished": false,
      "postTitle": "",
      "hasPostTitle": false,
      "mimeType": "",
      "hasMimeType": false
    },
    {
      "name": "rules",
      "content": "Rules for this challenges:\n - Don't cheat!\n - Apply yourself!\n - Have fun!\n - Plants are the ultimate organism!\n",
      "isPublished": false,
      "hasIsPublished": false,
      "postTitle": "",
      "hasPostTitle": false,
      "mimeType": "",
      "hasMimeType": false
    },
    {
      "name": "abstract",
      "content": "**Goal:** Using computer vision CNN to detect healthy vs diseased plant leaves.",
      "isPublished": false,
      "hasIsPublished": false,
      "postTitle": "",
      "hasPostTitle": false,
      "mimeType": "",
      "hasMimeType": false
    }
  ]
}