{"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":[{"sourceId":128792,"databundleVersionId":15494745,"sourceType":"competition"},{"sourceId":738203,"sourceType":"modelInstanceVersion","isSourceIdPinned":true,"modelInstanceId":562948,"modelId":575510}],"dockerImageVersionId":31260,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"\"\"\"\nSimple ConvNeXt Inference on First Training Image\nNo SAM segmentation - just direct image classification\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom torchvision import transforms, models\nfrom PIL import Image\nimport os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T07:40:09.445910Z","iopub.execute_input":"2026-02-03T07:40:09.446206Z","iopub.status.idle":"2026-02-03T07:40:18.827749Z","shell.execute_reply.started":"2026-02-03T07:40:09.446164Z","shell.execute_reply":"2026-02-03T07:40:18.827098Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Device setup\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(f\"Using device: {device}\")\n\n# Image preprocessing (same as training)\nmean = [0.485, 0.456, 0.406]\nstd = [0.229, 0.224, 0.225]\n\npredict_tfms = transforms.Compose([\n    transforms.Resize(256),\n    transforms.CenterCrop(224),\n    transforms.ToTensor(),\n    transforms.Normalize(mean, std),\n])\n\n# Class names (200 classes numbered 1-200)\nclass_names= ['1','10','100','101','102','103','104', '105','106','107','108', '109', '11', '110','111','112','113','114', '115','116','117','118','119','12','120','121','122','123','124','125','126','127','128','129','13','130','131','132','133','134','135', '136', '137','138','139','14','140','141','142','143','144','145','146','147','148','149','15','150','151','152','153','154','155','156', '157', '158', '159', '16', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '17', '170', '171', '172', '173', '174', '175', '176','177','178','179','18','180', '181', '182', '183', '184', '185', '186', '187', '188', '189', '19', '190', '191', '192', '193', '194', '195', '196','197','198','199','2','20','200','21','22','23','24','25','26','27','28','29','3','30','31','32','33','34','35','36','37','38','39','4','40','41', '42', '43', '44', '45', '46', '47', '48', '49', '5', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '6', '60', '61', '62', '63', '64', '65' '66', '67','68','69','7','70','71','72','73','74','75','76','77','78','79','8','80','81','82','83','84','85','86','87','88','89','9','90','91','92','93','94','95', '96','97','98','99']\n# Build ConvNeXt-Base model architecture\nnum_classes = 200\nconvnext_model = models.convnext_base(weights=None)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T07:41:57.893651Z","iopub.execute_input":"2026-02-03T07:41:57.894343Z","iopub.status.idle":"2026-02-03T07:41:59.308013Z","shell.execute_reply.started":"2026-02-03T07:41:57.894311Z","shell.execute_reply":"2026-02-03T07:41:59.307380Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Replace classifier head (must match training)\nnum_ftrs = convnext_model.classifier[-1].in_features  # 1024 for ConvNeXt-Base\nconvnext_model.classifier[-1] = nn.Sequential(\n    nn.Dropout(0.4),\n    nn.Linear(num_ftrs, 512),\n    nn.GELU(),\n    nn.Dropout(0.2),\n    nn.Linear(512, num_classes)\n)\n\nmodel_path = '/kaggle/input/convexnet-retail/pytorch/default/1/best_model.pth'  # UPDATE THIS PATH\ntry:\n    convnext_model.load_state_dict(torch.load(model_path, map_location=device, weights_only=True))\n    print(f\"✓ Loaded trained ConvNeXt-Base model from {model_path}\")\nexcept FileNotFoundError:\n    print(f\"ERROR: Model file not found at {model_path}\")\n    print(\"Please provide the path to your trained model weights\")\n    exit(1)\n\nconvnext_model = convnext_model.to(device)\nconvnext_model.eval()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T07:42:17.647091Z","iopub.execute_input":"2026-02-03T07:42:17.647451Z","iopub.status.idle":"2026-02-03T07:42:26.981411Z","shell.execute_reply.started":"2026-02-03T07:42:17.647424Z","shell.execute_reply":"2026-02-03T07:42:26.980657Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_images_folder = \"/kaggle/input/vista26/Vistas Dataset Public/Vistas Dataset Public/train\"  # UPDATE THIS PATH\n\ntry:\n    # Get first image from training folder\n    image_files = sorted([\n        f for f in os.listdir(train_images_folder)\n        if f.lower().endswith(('.jpg', '.png', '.jpeg'))\n    ])\n    \n    if not image_files:\n        print(f\"ERROR: No images found in {train_images_folder}\")\n        exit(1)\n    \n    first_image = image_files[0]\n    image_path = os.path.join(train_images_folder, first_image)\n    \n    print(f\"\\nProcessing: {first_image}\")\n    \n    # Load and preprocess image\n    image = Image.open(image_path).convert(\"RGB\")\n    img_tensor = predict_tfms(image).unsqueeze(0).to(device)\n    \n    # Run inference\n    with torch.no_grad():\n        outputs = convnext_model(img_tensor)\n        probabilities = torch.nn.functional.softmax(outputs, dim=1)\n        confidence, predicted_idx = torch.max(probabilities, 1)\n    \n    # Get prediction\n    predicted_class = class_names[predicted_idx.item()]\n    confidence_score = confidence.item()\n    \n    # Display results\n    print(\"\\n\" + \"=\"*50)\n    print(\"INFERENCE RESULTS\")\n    print(\"=\"*50)\n    print(f\"Image: {first_image}\")\n    print(f\"Predicted Class: {predicted_class}\")\n    print(f\"Confidence: {confidence_score:.4f} ({confidence_score*100:.2f}%)\")\n    print(\"=\"*50)\n    \n    # Optional: Show top 5 predictions\n    print(\"\\nTop 5 Predictions:\")\n    top5_prob, top5_idx = torch.topk(probabilities[0], 5)\n    for i, (prob, idx) in enumerate(zip(top5_prob, top5_idx)):\n        print(f\"  {i+1}. Class {class_names[idx.item()]}: {prob.item():.4f} ({prob.item()*100:.2f}%)\")\n\nexcept FileNotFoundError as e:\n    print(f\"ERROR: Training images folder not found at {train_images_folder}\")\n    print(\"Please provide the correct path to your training images folder\")\n    exit(1)\nexcept Exception as e:\n    print(f\"ERROR: {str(e)}\")\n    exit(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-03T07:43:32.816769Z","iopub.execute_input":"2026-02-03T07:43:32.817493Z","iopub.status.idle":"2026-02-03T07:43:48.571101Z","shell.execute_reply.started":"2026-02-03T07:43:32.817461Z","shell.execute_reply":"2026-02-03T07:43:48.570302Z"}},"outputs":[],"execution_count":null}]}