{"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":"none","dataSources":[{"sourceType":"competition","sourceId":112509,"databundleVersionId":14254895}],"dockerImageVersionId":31286,"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":"2026-02-22T19:06:06.679332Z","iopub.execute_input":"2026-02-22T19:06:06.679672Z","iopub.status.idle":"2026-02-22T19:06:13.932991Z","shell.execute_reply.started":"2026-02-22T19:06:06.679643Z","shell.execute_reply":"2026-02-22T19:06:13.931894Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"BASE_DIR = \"/kaggle/input/csiro-biomass\"\nTRAIN_CSV = f\"{BASE_DIR}/train.csv\"\nTEST_CSV = f\"{BASE_DIR}/test.csv\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:13:53.172404Z","iopub.execute_input":"2026-02-22T19:13:53.172785Z","iopub.status.idle":"2026-02-22T19:13:53.178534Z","shell.execute_reply.started":"2026-02-22T19:13:53.172723Z","shell.execute_reply":"2026-02-22T19:13:53.177534Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nfrom PIL import Image\nfrom torch.utils.data import Dataset\n\nclass BiomassDataset(Dataset):\n    def __init__(self, csv_file, base_dir, transform=None, train=True):\n        self.df = pd.read_csv(csv_file)\n        self.base_dir = base_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\n        img_path = os.path.join(self.base_dir, row[\"image_path\"])\n        image = Image.open(img_path).convert(\"RGB\")\n\n        if self.transform:\n            image = self.transform(image)\n\n        if self.train:\n            target = row[\"target\"]\n            return image, target\n        else:\n            sample_id = row[\"sample_id\"]\n            target_name = row[\"target_name\"]\n            return image, sample_id, target_name","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:13:54.577760Z","iopub.execute_input":"2026-02-22T19:13:54.578177Z","iopub.status.idle":"2026-02-22T19:13:54.586598Z","shell.execute_reply.started":"2026-02-22T19:13:54.578144Z","shell.execute_reply":"2026-02-22T19:13:54.585600Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torchvision.transforms as T\n\ntransform = T.Compose([\n    T.Resize((224, 224)),\n    T.ToTensor()\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:13:56.792596Z","iopub.execute_input":"2026-02-22T19:13:56.792973Z","iopub.status.idle":"2026-02-22T19:13:56.798151Z","shell.execute_reply.started":"2026-02-22T19:13:56.792941Z","shell.execute_reply":"2026-02-22T19:13:56.797257Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport pytorch_lightning as pl\n\nclass BiomassModel(pl.LightningModule):\n    def __init__(self):\n        super().__init__()\n        \n        self.conv1 = nn.Conv2d(3, 16, 3, padding=1)\n        self.conv2 = nn.Conv2d(16, 32, 3, padding=1)\n        self.pool = nn.MaxPool2d(2)\n\n        self.fc1 = nn.Linear(32 * 56 * 56, 128)\n        self.fc2 = nn.Linear(128, 1)\n\n    def forward(self, x):\n        x = self.pool(F.relu(self.conv1(x)))\n        x = self.pool(F.relu(self.conv2(x)))\n        \n        x = torch.flatten(x, 1)\n        x = F.relu(self.fc1(x))\n        x = self.fc2(x)\n        \n        return x.squeeze()\n\n    def training_step(self, batch, batch_idx):\n        x, y = batch\n        y_hat = self(x)\n        \n        loss = F.mse_loss(y_hat, y.float())\n        self.log(\"train_loss\", loss)\n        return loss\n\n    def configure_optimizers(self):\n        return torch.optim.Adam(self.parameters(), lr=1e-3)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:13:58.398161Z","iopub.execute_input":"2026-02-22T19:13:58.398507Z","iopub.status.idle":"2026-02-22T19:13:58.408455Z","shell.execute_reply.started":"2026-02-22T19:13:58.398476Z","shell.execute_reply":"2026-02-22T19:13:58.407579Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import DataLoader\n\ntrain_dataset = BiomassDataset(\n    TRAIN_CSV,\n    base_dir=BASE_DIR,\n    transform=transform,\n    train=True\n)\n\ntest_dataset = BiomassDataset(\n    TEST_CSV,\n    base_dir=BASE_DIR,\n    transform=transform,\n    train=False\n)\n\ntrain_loader = DataLoader(\n    train_dataset,\n    batch_size=32,\n    shuffle=True,\n    num_workers=2\n)\n\ntest_loader = DataLoader(\n    test_dataset,\n    batch_size=32,\n    shuffle=False,\n    num_workers=2\n)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:14:00.403483Z","iopub.execute_input":"2026-02-22T19:14:00.403865Z","iopub.status.idle":"2026-02-22T19:14:00.437273Z","shell.execute_reply.started":"2026-02-22T19:14:00.403812Z","shell.execute_reply":"2026-02-22T19:14:00.435921Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = BiomassModel()\n\ntrainer = pl.Trainer(\n    max_epochs=10,\n    accelerator=\"auto\"\n)\n\ntrainer.fit(model, train_loader)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:14:02.596444Z","iopub.execute_input":"2026-02-22T19:14:02.596803Z","iopub.status.idle":"2026-02-22T19:29:17.437064Z","shell.execute_reply.started":"2026-02-22T19:14:02.596761Z","shell.execute_reply":"2026-02-22T19:29:17.435917Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_loader = DataLoader(test_dataset, batch_size=32)\npredictions = []\n\nmodel.eval()\nmodel.freeze()\n\nfor batch in test_loader:\n    images, sample_ids, target_names = batch\n    preds = model(images)\n\n    for sid, pred in zip(sample_ids, preds):\n        predictions.append((sid, pred.item()))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:29:17.443274Z","iopub.execute_input":"2026-02-22T19:29:17.443715Z","iopub.status.idle":"2026-02-22T19:29:18.016641Z","shell.execute_reply.started":"2026-02-22T19:29:17.443654Z","shell.execute_reply":"2026-02-22T19:29:18.015698Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sub = pd.DataFrame(predictions, columns=[\"sample_id\", \"target\"])\nsub.to_csv(\"submission.csv\", index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-22T19:31:01.322613Z","iopub.execute_input":"2026-02-22T19:31:01.323008Z","iopub.status.idle":"2026-02-22T19:31:01.331182Z","shell.execute_reply.started":"2026-02-22T19:31:01.322972Z","shell.execute_reply":"2026-02-22T19:31:01.329779Z"}},"outputs":[],"execution_count":null}]}