{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":91498,"databundleVersionId":11655853,"sourceType":"competition"}],"dockerImageVersionId":31011,"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 os\nimport torch\nimport pandas as pd\nimport numpy as np\nfrom pathlib import Path\nfrom torch import nn\nfrom torch.utils.data import Dataset, DataLoader\nfrom torchvision import transforms, models\nfrom PIL import Image\nfrom tqdm import tqdm\nfrom glob import glob\nfrom sklearn.cluster import DBSCAN\nfrom sklearn.metrics import pairwise_distances_argmin_min\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:39:56.099886Z","iopub.execute_input":"2025-05-02T04:39:56.100058Z","iopub.status.idle":"2025-05-02T04:40:04.61285Z","shell.execute_reply.started":"2025-05-02T04:39:56.10004Z","shell.execute_reply":"2025-05-02T04:40:04.612038Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 1. CONFIGS\n# ====================\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nTRAIN_DIR = '/kaggle/input/image-matching-challenge-2025/train'\nTEST_DIR = '/kaggle/input/image-matching-challenge-2025/test'\nBATCH_SIZE = 32\nEPOCHS = 3\nLR = 1e-5  # Lowered learning rate\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:40:09.105394Z","iopub.execute_input":"2025-05-02T04:40:09.10594Z","iopub.status.idle":"2025-05-02T04:40:09.19321Z","shell.execute_reply.started":"2025-05-02T04:40:09.105915Z","shell.execute_reply":"2025-05-02T04:40:09.192447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 2. TRANSFORM\n# ====================\ntransform = transforms.Compose([\n    transforms.Resize((512, 512)),\n    transforms.ToTensor(),\n    transforms.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-05-02T04:40:18.751031Z","iopub.execute_input":"2025-05-02T04:40:18.751308Z","iopub.status.idle":"2025-05-02T04:40:18.755328Z","shell.execute_reply.started":"2025-05-02T04:40:18.751271Z","shell.execute_reply":"2025-05-02T04:40:18.754799Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 3. DATA PREP\n# ====================\ntrain_df = pd.read_csv('/kaggle/input/image-matching-challenge-2025/train_labels.csv')\ntrain_df['image_path'] = train_df.apply(lambda row: os.path.join(TRAIN_DIR, row['dataset'], row['image']), axis=1)\ntrain_df['rotation_matrix'] = train_df['rotation_matrix'].apply(lambda x: np.array(list(map(float, x.split(';')))))\ntrain_df['translation_vector'] = train_df['translation_vector'].apply(lambda x: np.array(list(map(float, x.split(';')))))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:40:29.461415Z","iopub.execute_input":"2025-05-02T04:40:29.462278Z","iopub.status.idle":"2025-05-02T04:40:29.522782Z","shell.execute_reply.started":"2025-05-02T04:40:29.46225Z","shell.execute_reply":"2025-05-02T04:40:29.52227Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Remove NaN or Inf entries\ntrain_df = train_df[\n    train_df['rotation_matrix'].apply(lambda x: np.isfinite(x).all()) &\n    train_df['translation_vector'].apply(lambda x: np.isfinite(x).all())\n]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:40:48.557485Z","iopub.execute_input":"2025-05-02T04:40:48.558187Z","iopub.status.idle":"2025-05-02T04:40:48.578388Z","shell.execute_reply.started":"2025-05-02T04:40:48.558161Z","shell.execute_reply":"2025-05-02T04:40:48.577639Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Remove corrupted images\nvalid_paths = []\nfor path in tqdm(train_df['image_path'], desc=\"Checking images\"):\n    try:\n        _ = Image.open(path).convert('RGB')\n        valid_paths.append(True)\n    except:\n        valid_paths.append(False)\ntrain_df = train_df[valid_paths]\n\nclass PoseDataset(Dataset):\n    def __init__(self, df, is_test=False):\n        self.df = df\n        self.is_test = is_test\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        row = self.df.iloc[idx]\n        image = Image.open(row['image_path']).convert('RGB')\n        image = self.transform(image)\n        if self.is_test:\n            return image, row['image'], row['dataset'], row.get('scene', 'dummy')\n        else:\n            rot = torch.tensor(row['rotation_matrix'], dtype=torch.float32)\n            trans = torch.tensor(row['translation_vector'], dtype=torch.float32)\n            return image, rot, trans\n\ntrain_dataset = PoseDataset(train_df)\ntrain_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:41:03.242351Z","iopub.execute_input":"2025-05-02T04:41:03.24286Z","iopub.status.idle":"2025-05-02T04:43:45.53508Z","shell.execute_reply.started":"2025-05-02T04:41:03.242835Z","shell.execute_reply":"2025-05-02T04:43:45.534501Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 4. MODEL\n# ====================\nclass PoseModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        import torchvision.models as models\n        import torch\n\n        self.backbone = models.resnet18()\n        self.backbone.load_state_dict(torch.load('/kaggle/input/renset18weights/resnet18-f37072fd.pth'))\n        self.backbone.fc = nn.Identity()\n        self.fc_rot = nn.Linear(512, 9)\n        self.fc_trans = nn.Linear(512, 3)\n\n    def forward(self, x):\n        features = self.backbone(x)\n        rot = torch.tanh(self.fc_rot(features))  # Normalize outputs\n        trans = self.fc_trans(features)\n        return rot, trans\n\nmodel = PoseModel().to(device)\ncriterion = nn.MSELoss()\noptimizer = torch.optim.Adam(model.parameters(), lr=LR)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-05-02T04:43:48.612363Z","iopub.execute_input":"2025-05-02T04:43:48.612691Z","iopub.status.idle":"2025-05-02T04:43:48.895155Z","shell.execute_reply.started":"2025-05-02T04:43:48.612667Z","shell.execute_reply":"2025-05-02T04:43:48.89423Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 5. CLUSTERING FUNCTION\n# ====================\ndef cluster_images(features, eps=0.01, min_samples=5):\n    db = DBSCAN(eps=eps, min_samples=min_samples, metric='euclidean')\n    cluster_labels = db.fit_predict(features)\n    return cluster_labels\n\n# ====================\n# 6. TRAINING\n# ====================\nbest_loss = float('inf')\nfor epoch in range(EPOCHS):\n    model.train()\n    total_loss = 0\n    feature_list = []\n    for imgs, rots, trans in tqdm(train_loader, desc=f\"Epoch {epoch+1}\"):\n        imgs, rots, trans = imgs.to(device), rots.to(device), trans.to(device)\n        pred_rots, pred_trans = model(imgs)\n        loss = criterion(pred_rots, rots) + criterion(pred_trans, trans)\n        \n        if torch.isnan(loss):\n            print(\"⚠️ NaN loss encountered. Skipping batch...\")\n            continue\n        \n        optimizer.zero_grad()\n        loss.backward()\n        torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)\n        optimizer.step()\n        total_loss += loss.item()\n        \n        feature_list.append(pred_rots.cpu().detach().numpy())\n\n    avg_loss = total_loss / len(train_loader)\n    print(f\"Epoch {epoch+1} Loss: {avg_loss:.4f}\")\n    if avg_loss < best_loss:\n        torch.save(model.state_dict(), 'best_model.pth')\n        best_loss = avg_loss\n        print(\"✅ Best model saved\")\n\n","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# ====================\n# 7. TEST INFERENCE\n# ====================\nmodel.load_state_dict(torch.load('best_model.pth'))\nmodel.eval()\nsample_submission = pd.read_csv('/kaggle/input/image-matching-challenge-2025/sample_submission.csv')\ntest_paths = glob(f'{TEST_DIR}/*/*.png')\n\ntest_df = pd.DataFrame(test_paths, columns=['image_path'])\ntest_df['image'] = test_df['image_path'].apply(lambda x: Path(x).name)\ntest_df['dataset'] = test_df['image_path'].apply(lambda x: Path(x).parts[-2])\ntest_df['scene'] = 'dummy'\ntest_df['image_id'] = test_df['dataset'] + '_' + test_df['image']\n\ntest_dataset = PoseDataset(test_df, is_test=True)\ntest_loader = DataLoader(test_dataset, batch_size=BATCH_SIZE, shuffle=False)\n\nrotations, translations, scenes = [], [], []\nfeature_list = []\n\nwith torch.no_grad():\n    for imgs, image_names, datasets, scenes_batch in tqdm(test_loader, desc=\"Predicting\"):\n        imgs = imgs.to(device)\n        pred_rots, pred_trans = model(imgs)\n        for rot, trans in zip(pred_rots, pred_trans):\n            rotations.append(';'.join(f'{r:.6f}' for r in rot.cpu().numpy()))\n            translations.append(';'.join(f'{t:.6f}' for t in trans.cpu().numpy()))\n        feature_list.append(pred_rots.cpu().numpy())\n\nfeatures = np.vstack(feature_list)\ncluster_labels = cluster_images(features)\ntest_df['scene'] = ['cluster' + str(label) if label != -1 else 'outliers' for label in cluster_labels]\ntest_df['rotation_matrix'] = rotations\ntest_df['translation_vector'] = translations\n\nsubmission_df = test_df[['image_id', 'dataset', 'scene', 'image', 'rotation_matrix', 'translation_vector']]\nsubmission_df.to_csv('submission.csv', index=False)\nprint(\"✅ Submission saved as submission.csv\")","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}