{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":112509,"databundleVersionId":14254895,"sourceType":"competition"}],"dockerImageVersionId":31192,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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,"execution":{"iopub.status.busy":"2025-11-11T04:01:06.030954Z","iopub.execute_input":"2025-11-11T04:01:06.031179Z","iopub.status.idle":"2025-11-11T04:01:06.636674Z","shell.execute_reply.started":"2025-11-11T04:01:06.031151Z","shell.execute_reply":"2025-11-11T04:01:06.635548Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# =========================================================\n# 📦 Import Libraries\n# =========================================================\nimport pandas as pd\nimport numpy as np\nimport os\nimport gc\nimport torch\nimport torchvision.transforms as T\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import models\nimport torch.nn as nn\nfrom tqdm import tqdm\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:01:21.809110Z","iopub.execute_input":"2025-11-11T04:01:21.809722Z","iopub.status.idle":"2025-11-11T04:01:29.206244Z","shell.execute_reply.started":"2025-11-11T04:01:21.809696Z","shell.execute_reply":"2025-11-11T04:01:29.205649Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 🧾 Load Data\n# =========================================================\ntrain_df = pd.read_csv(\"/kaggle/input/csiro-biomass/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/csiro-biomass/test.csv\")\nsample_submission = pd.read_csv(\"/kaggle/input/csiro-biomass/sample_submission.csv\")\n\nprint(\"Train shape:\", train_df.shape)\nprint(\"Test shape:\", test_df.shape)\ntrain_df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:01:44.077325Z","iopub.execute_input":"2025-11-11T04:01:44.077783Z","iopub.status.idle":"2025-11-11T04:01:44.123280Z","shell.execute_reply.started":"2025-11-11T04:01:44.077757Z","shell.execute_reply":"2025-11-11T04:01:44.122699Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from PIL import Image\n\nclass PastureDataset(Dataset):\n    def __init__(self, df, img_dir, transform=None, train=True):\n        self.df = df\n        self.img_dir = img_dir\n        self.transform = transform\n        self.train = train\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        img_path = os.path.join(self.img_dir, row['image_path'])\n        image = Image.open(img_path).convert(\"RGB\")\n        if self.transform:\n            image = self.transform(image)\n        if self.train:\n            target = torch.tensor(row['target'], dtype=torch.float32)\n            return image, target\n        return image, row['sample_id']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:01:59.749775Z","iopub.execute_input":"2025-11-11T04:01:59.750634Z","iopub.status.idle":"2025-11-11T04:01:59.756748Z","shell.execute_reply.started":"2025-11-11T04:01:59.750605Z","shell.execute_reply":"2025-11-11T04:01:59.755859Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 🔧 Transforms\n# =========================================================\ntransform = T.Compose([\n    T.Resize((224, 224)),\n    T.ToTensor(),\n    T.Normalize(mean=[0.485, 0.456, 0.406],\n                std=[0.229, 0.224, 0.225])\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:02:09.394403Z","iopub.execute_input":"2025-11-11T04:02:09.394712Z","iopub.status.idle":"2025-11-11T04:02:09.399132Z","shell.execute_reply.started":"2025-11-11T04:02:09.394683Z","shell.execute_reply":"2025-11-11T04:02:09.398243Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 🧠 Model (ResNet18)\n# =========================================================\nclass BiomassModel(nn.Module):\n    def __init__(self):\n        super(BiomassModel, self).__init__()\n        self.backbone = models.resnet18(weights=models.ResNet18_Weights.DEFAULT)\n        self.backbone.fc = nn.Linear(self.backbone.fc.in_features, 1)\n\n    def forward(self, x):\n        return self.backbone(x).squeeze(1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:02:19.498524Z","iopub.execute_input":"2025-11-11T04:02:19.499290Z","iopub.status.idle":"2025-11-11T04:02:19.503858Z","shell.execute_reply.started":"2025-11-11T04:02:19.499262Z","shell.execute_reply":"2025-11-11T04:02:19.502993Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ⚙️ Training Config\n# =========================================================\ndevice = \"cuda\" if torch.cuda.is_available() else \"cpu\"\nmodel = BiomassModel().to(device)\ncriterion = nn.MSELoss()\noptimizer = torch.optim.AdamW(model.parameters(), lr=1e-4)\n\ntrain_dataset = PastureDataset(train_df, \"/kaggle/input/csiro-biomass\", transform)\ntrain_loader = DataLoader(train_dataset, batch_size=16, shuffle=True, num_workers=2)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:02:29.304905Z","iopub.execute_input":"2025-11-11T04:02:29.305190Z","iopub.status.idle":"2025-11-11T04:02:29.893954Z","shell.execute_reply.started":"2025-11-11T04:02:29.305167Z","shell.execute_reply":"2025-11-11T04:02:29.893273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 🚀 Training Loop (Tiny Epochs for Baseline)\n# =========================================================\nfor epoch in range(2):  # Increase later\n    model.train()\n    running_loss = 0.0\n    for imgs, targets in tqdm(train_loader):\n        imgs, targets = imgs.to(device), targets.to(device)\n        optimizer.zero_grad()\n        outputs = model(imgs)\n        loss = criterion(outputs, targets)\n        loss.backward()\n        optimizer.step()\n        running_loss += loss.item() * imgs.size(0)\n    print(f\"Epoch [{epoch+1}/2] Loss: {running_loss / len(train_loader.dataset):.4f}\")\n    gc.collect()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:02:42.452282Z","iopub.execute_input":"2025-11-11T04:02:42.453050Z","iopub.status.idle":"2025-11-11T04:10:50.059758Z","shell.execute_reply.started":"2025-11-11T04:02:42.453024Z","shell.execute_reply":"2025-11-11T04:10:50.059013Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 📈 Inference\n# =========================================================\ntest_dataset = PastureDataset(test_df, \"/kaggle/input/csiro-biomass\", transform, train=False)\ntest_loader = DataLoader(test_dataset, batch_size=16, shuffle=False, num_workers=2)\n\nmodel.eval()\npreds = []\nids = []\nwith torch.no_grad():\n    for imgs, sample_ids in tqdm(test_loader):\n        imgs = imgs.to(device)\n        outputs = model(imgs)\n        preds.extend(outputs.cpu().numpy())\n        ids.extend(sample_ids)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:11:08.995922Z","iopub.execute_input":"2025-11-11T04:11:08.996478Z","iopub.status.idle":"2025-11-11T04:11:09.777499Z","shell.execute_reply.started":"2025-11-11T04:11:08.996451Z","shell.execute_reply":"2025-11-11T04:11:09.776659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 📤 Submission\n# =========================================================\nsubmission = pd.DataFrame({\n    \"sample_id\": ids,\n    \"target\": preds\n})\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"✅ submission.csv ready!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:11:22.258579Z","iopub.execute_input":"2025-11-11T04:11:22.258974Z","iopub.status.idle":"2025-11-11T04:11:22.271426Z","shell.execute_reply.started":"2025-11-11T04:11:22.258945Z","shell.execute_reply":"2025-11-11T04:11:22.270845Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nos.environ['KAGGLE_USERNAME'] = 'yokesh29'\nos.environ['KAGGLE_KEY'] = '91c3ae926e135a39808021f4163bd931'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:11:38.177412Z","iopub.execute_input":"2025-11-11T04:11:38.178257Z","iopub.status.idle":"2025-11-11T04:11:38.181796Z","shell.execute_reply.started":"2025-11-11T04:11:38.178229Z","shell.execute_reply":"2025-11-11T04:11:38.181091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"!kaggle competitions download -c csiro-biomass\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-11T04:12:27.458026Z","iopub.execute_input":"2025-11-11T04:12:27.458792Z","iopub.status.idle":"2025-11-11T04:13:05.099133Z","shell.execute_reply.started":"2025-11-11T04:12:27.458765Z","shell.execute_reply":"2025-11-11T04:13:05.098364Z"}},"outputs":[],"execution_count":null}]}