{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.12.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceType":"competition","sourceId":131587,"databundleVersionId":15786880},{"sourceType":"datasetVersion","sourceId":15821253,"datasetId":10141594,"databundleVersionId":16770057}],"dockerImageVersionId":31329,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import kagglehub\n\n# Download latest version\npath = kagglehub.competition_download('cs-460-muffin-vs-chihuahua-classification-challenge')\n\nprint(\"Path to competition files:\", path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T13:02:49.325373Z","iopub.execute_input":"2026-04-19T13:02:49.325664Z","iopub.status.idle":"2026-04-19T13:02:50.568954Z","shell.execute_reply.started":"2026-04-19T13:02:49.325639Z","shell.execute_reply":"2026-04-19T13:02:50.568234Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =============================\n# 1. IMPORTS\n# =============================\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms, models\nfrom torch.utils.data import DataLoader, random_split\nfrom PIL import Image\nimport pandas as pd\nimport os\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n# =============================\n# 2. DATASET (AUTO SPLIT)\n# =============================\ndata_dir = \"/kaggle/input/datasets/otaku09/chihuahua\"\n\ntransform = transforms.Compose([\n    transforms.Resize((224, 224)),\n    transforms.ToTensor(),\n])\n\nfull_dataset = datasets.ImageFolder(\n    os.path.join(data_dir, \"train\"),\n    transform=transform\n)\n\ntrain_size = int(0.8 * len(full_dataset))\nval_size = len(full_dataset) - train_size\n\ntrain_data, val_data = random_split(full_dataset, [train_size, val_size])\n\ntrain_loader = DataLoader(train_data, batch_size=32, shuffle=True)\nval_loader = DataLoader(val_data, batch_size=32)\n\n# =============================\n# 3. MODEL FUNCTION\n# =============================\ndef get_model(name):\n    if name == \"resnet\":\n        model = models.resnet18(pretrained=True)\n        model.fc = nn.Linear(model.fc.in_features, 2)\n\n    elif name == \"efficientnet\":\n        model = models.efficientnet_b0(pretrained=True)\n        model.classifier[1] = nn.Linear(model.classifier[1].in_features, 2)\n\n    elif name == \"mobilenet\":\n        model = models.mobilenet_v2(pretrained=True)\n        model.classifier[1] = nn.Linear(model.classifier[1].in_features, 2)\n\n    elif name == \"densenet\":\n        model = models.densenet121(pretrained=True)\n        model.classifier = nn.Linear(model.classifier.in_features, 2)\n\n    elif name == \"vit\":\n        model = models.vit_b_16(pretrained=True)\n        model.heads.head = nn.Linear(model.heads.head.in_features, 2)\n\n    return model.to(device)\n\n# =============================\n# 4. TRAIN + VALIDATE FUNCTION\n# =============================\ndef train_model(model, name, epochs=5):\n    criterion = nn.CrossEntropyLoss()\n    optimizer = optim.Adam(model.parameters(), lr=0.0001)\n\n    best_acc = 0\n\n    for epoch in range(epochs):\n        # ---- TRAIN ----\n        model.train()\n        train_loss = 0\n        correct = 0\n        total = 0\n\n        for images, labels in train_loader:\n            images, labels = images.to(device), labels.to(device)\n\n            optimizer.zero_grad()\n            outputs = model(images)\n            loss = criterion(outputs, labels)\n\n            loss.backward()\n            optimizer.step()\n\n            train_loss += loss.item()\n            _, pred = torch.max(outputs, 1)\n            total += labels.size(0)\n            correct += (pred == labels).sum().item()\n\n        train_acc = 100 * correct / total\n\n        # ---- VALIDATION ----\n        model.eval()\n        correct = 0\n        total = 0\n\n        with torch.no_grad():\n            for images, labels in val_loader:\n                images, labels = images.to(device), labels.to(device)\n                outputs = model(images)\n\n                _, pred = torch.max(outputs, 1)\n                total += labels.size(0)\n                correct += (pred == labels).sum().item()\n\n        val_acc = 100 * correct / total\n\n        print(f\"{name} | Epoch {epoch+1}\")\n        print(f\"Train Loss: {train_loss:.4f} | Train Acc: {train_acc:.2f}%\")\n        print(f\"Val Acc: {val_acc:.2f}%\\n\")\n\n        # Save best model\n        if val_acc > best_acc:\n            best_acc = val_acc\n            torch.save(model.state_dict(), f\"/kaggle/working/best_{name}.pth\")\n\n    return best_acc\n\n# =============================\n# 5. TRAIN ALL MODELS\n# =============================\nmodel_names = [\"resnet\", \"efficientnet\", \"mobilenet\", \"densenet\", \"vit\"]\nresults = {}\n\nfor name in model_names:\n    print(f\"\\n🔥 Training {name}...\\n\")\n    model = get_model(name)\n\n    best_acc = train_model(model, name, epochs=5)\n    results[name] = best_acc\n\nprint(\"\\nAll Results:\", results)\n\n# =============================\n# 6. SELECT BEST MODEL\n# =============================\nbest_model_name = max(results, key=results.get)\nprint(\"\\n🏆 Best Model:\", best_model_name)\n\nmodel = get_model(best_model_name)\nmodel.load_state_dict(torch.load(f\"/kaggle/working/best_{best_model_name}.pth\"))\nmodel.eval()\n\n# =============================\n# 7. TEST PREDICTION\n# =============================\n# =============================\n# 7. TEST PREDICTION\n# =============================\ntest_dir = \"/kaggle/input/datasets/otaku09/chihuahua/kaggle_test_final\"\n\nclass_names = full_dataset.classes  # ['chihuahua', 'muffin']\n\nresults = []\n\nfor img_name in os.listdir(test_dir):\n    img_path = os.path.join(test_dir, img_name)\n\n    image = Image.open(img_path).convert(\"RGB\")\n    image = transform(image).unsqueeze(0).to(device)\n\n    with torch.no_grad():\n        output = model(image)\n        _, pred = torch.max(output, 1)\n\n    label_name = class_names[pred.item()]\n    results.append([img_name, label_name])\n\n# =============================\n# 8. SAVE CSV\n# =============================\ndf = pd.DataFrame(results, columns=[\"ID\", \"Label\"])\ndf.to_csv(\"/kaggle/working/submission.csv\", index=False)\n\nprint(\"✅ Submission file created!\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T15:57:16.980627Z","iopub.execute_input":"2026-04-19T15:57:16.981083Z","iopub.status.idle":"2026-04-19T16:39:03.196384Z","shell.execute_reply.started":"2026-04-19T15:57:16.981050Z","shell.execute_reply":"2026-04-19T16:39:03.195666Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-04-19T13:52:17.289614Z","iopub.execute_input":"2026-04-19T13:52:17.289939Z","iopub.status.idle":"2026-04-19T13:52:17.422795Z","shell.execute_reply.started":"2026-04-19T13:52:17.289881Z","shell.execute_reply":"2026-04-19T13:52:17.421855Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =============================\n# 7. TEST PREDICTION\n# =============================\ntest_dir = \"/kaggle/input/datasets/otaku09/chihuahua/kaggle_test_final\"\n\nclass_names = full_dataset.classes  # ['chihuahua', 'muffin']\n\nresults = []\n\nfor img_name in os.listdir(test_dir):\n    img_path = os.path.join(test_dir, img_name)\n\n    image = Image.open(img_path).convert(\"RGB\")\n    image = transform(image).unsqueeze(0).to(device)\n\n    with torch.no_grad():\n        output = model(image)\n        _, pred = torch.max(output, 1)\n\n    # =============================\n    # OPTION 1 (CURRENT - CLASS NAME)\n    # =============================\n    label_name = class_names[pred.item()]\n    results.append([img_name, label_name])\n\n    # =============================\n    # OPTION 2 (NUMERIC OUTPUT - COMMENTED)\n    # =============================\n    # results.append([img_name, pred.item()])","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}