{"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":"gpu","dataSources":[{"sourceId":126777,"databundleVersionId":15314950,"sourceType":"competition"}],"dockerImageVersionId":31259,"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        os.path.join(dirname, filename)\n        \n    print(\"Done loading Files!!\")\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-16T18:55:14.708836Z","iopub.execute_input":"2026-02-16T18:55:14.709230Z","iopub.status.idle":"2026-02-16T18:55:15.086589Z","shell.execute_reply.started":"2026-02-16T18:55:14.709190Z","shell.execute_reply":"2026-02-16T18:55:15.085760Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import pandas as pd \nimport numpy as np \nimport matplotlib.pyplot as plt \nfrom PIL import Image\nfrom tqdm import tqdm\nfrom pathlib import Path\nimport torch.nn.functional as F\nimport os\nimport torch\nfrom torch.utils.data import Dataset , DataLoader\nfrom torchvision import transforms\nimport torchvision.models as models\nimport torch.nn as nn\nimport torch.optim as optim\ndevice = torch.device('cuda' if torch.cuda.is_available else 'cpu')\nprint(device)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:15.088223Z","iopub.execute_input":"2026-02-16T18:55:15.088626Z","iopub.status.idle":"2026-02-16T18:55:17.794835Z","shell.execute_reply.started":"2026-02-16T18:55:15.088601Z","shell.execute_reply":"2026-02-16T18:55:17.794109Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_data = pd.read_csv(\"/kaggle/input/jaguar-re-id/train.csv\")\ntest_data = pd.read_csv('/kaggle/input/jaguar-re-id/test.csv')\n\ntrain_DIR = '/kaggle/input/jaguar-re-id/train/train/'\ntest_DIR = '/kaggle/input/jaguar-re-id/test/test'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:17.796160Z","iopub.execute_input":"2026-02-16T18:55:17.796590Z","iopub.status.idle":"2026-02-16T18:55:17.869207Z","shell.execute_reply.started":"2026-02-16T18:55:17.796566Z","shell.execute_reply":"2026-02-16T18:55:17.868396Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class CDataset(Dataset):\n    def __init__(self, df, feature , labels,train_DIR, labels_map=None,is_train=True, transform=None):\n        self.feature = feature\n        self.df = df\n        self.labels = labels\n        self.transform = transform\n        self.labels_map = labels_map\n        self.train_DIR = train_DIR\n        self.is_train = is_train\n        \n\n    def __len__(self):\n        return self.feature.shape[0]\n\n    def __getitem__(self,idx):\n        row = self.df.iloc[idx]\n        \n        image_path = os.path.join(self.train_DIR, str(self.feature[idx]))\n\n        image = Image.open(image_path).convert('RGB')\n        if self.transform:\n            img = self.transform(image)\n        if self.is_train:\n            label_str = row['ground_truth']\n            label = self.labels_map[label_str]\n            \n            return img , torch.tensor(label, dtype=torch.long)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:18.146174Z","iopub.execute_input":"2026-02-16T18:55:18.146666Z","iopub.status.idle":"2026-02-16T18:55:18.152699Z","shell.execute_reply.started":"2026-02-16T18:55:18.146638Z","shell.execute_reply":"2026-02-16T18:55:18.151735Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"feature = train_data['filename']\nlabels = train_data['ground_truth']\nlabels_map = {name: i for i, name in enumerate(train_data['ground_truth'].unique())}\ntarget_size = (384,384)\ntransform_train = transforms.Compose([\n    transforms.Resize(target_size),\n    transforms.CenterCrop(target_size),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\n# print(labels_map)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:18.383437Z","iopub.execute_input":"2026-02-16T18:55:18.384190Z","iopub.status.idle":"2026-02-16T18:55:18.390031Z","shell.execute_reply.started":"2026-02-16T18:55:18.384149Z","shell.execute_reply":"2026-02-16T18:55:18.389399Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_dataset = CDataset( train_data ,feature,labels, train_DIR,labels_map = labels_map,transform=transform_train)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:18.616873Z","iopub.execute_input":"2026-02-16T18:55:18.617709Z","iopub.status.idle":"2026-02-16T18:55:18.622709Z","shell.execute_reply.started":"2026-02-16T18:55:18.617654Z","shell.execute_reply":"2026-02-16T18:55:18.621898Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"type(print(train_dataset[0]))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T18:55:21.864659Z","iopub.execute_input":"2026-02-16T18:55:21.865378Z","iopub.status.idle":"2026-02-16T18:55:22.043344Z","shell.execute_reply.started":"2026-02-16T18:55:21.865347Z","shell.execute_reply":"2026-02-16T18:55:22.042672Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"batch_size = 100\nnum_label = len(labels_map)\ntr_dataloader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True,num_workers=4,pin_memory=True )","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T19:29:24.605409Z","iopub.execute_input":"2026-02-16T19:29:24.606202Z","iopub.status.idle":"2026-02-16T19:29:24.610098Z","shell.execute_reply.started":"2026-02-16T19:29:24.606170Z","shell.execute_reply":"2026-02-16T19:29:24.609240Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class Model(nn.Module):\n\n    def __init__(self,num_label):\n        super().__init__()\n        self.base_model = models.resnet18(weights='DEFAULT')\n        num_features = self.base_model.fc.in_features\n        self.base_model.fc = nn.Identity()\n\n        self.net = nn.Sequential(\n            nn.Linear(num_features, 256),\n            nn.BatchNorm1d(256),\n            nn.ReLU(),\n            nn.Dropout(0.2),\n\n            nn.Linear(256, 256),\n            nn.BatchNorm1d(256),\n            nn.ReLU(),\n            nn.Dropout(0.2),\n\n            nn.Linear(256,128)\n        )\n        self.classifier_head = nn.Linear(128,num_label)\n        \n\n    def forward(self,x):\n        features = self.base_model(x)\n        out = self.net(features)\n        return out\n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T19:29:26.586682Z","iopub.execute_input":"2026-02-16T19:29:26.587473Z","iopub.status.idle":"2026-02-16T19:29:26.593079Z","shell.execute_reply.started":"2026-02-16T19:29:26.587441Z","shell.execute_reply":"2026-02-16T19:29:26.592193Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"learning_rate = 5e-4\nepochs = 15\nloss_function =  nn.CrossEntropyLoss()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T19:29:32.272416Z","iopub.execute_input":"2026-02-16T19:29:32.273041Z","iopub.status.idle":"2026-02-16T19:29:32.276639Z","shell.execute_reply.started":"2026-02-16T19:29:32.273012Z","shell.execute_reply":"2026-02-16T19:29:32.275762Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = Model(num_label).to(device)\n\noptimizer = optim.Adam(model.parameters(),lr=learning_rate)\n\nfor epoch in range(epochs):\n    \n    for i , (X,y) in enumerate(tr_dataloader):\n        X , y = X.to(device) , y.to(device)\n\n        y_pred = model(X)\n\n        loss = loss_function(y_pred, y)\n\n        optimizer.zero_grad()\n\n        loss.backward()\n\n        optimizer.step()\n        if i % 20 == 0:\n            print(i)\n    print(f'epochs: {epoch+1}, loss: {loss.item()}')\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T19:29:34.156589Z","iopub.execute_input":"2026-02-16T19:29:34.156874Z","iopub.status.idle":"2026-02-16T20:31:39.444528Z","shell.execute_reply.started":"2026-02-16T19:29:34.156849Z","shell.execute_reply":"2026-02-16T20:31:39.443475Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"unique_test_images = pd.concat([test_data['query_image'],test_data['gallery_image']]).unique()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:31:59.371751Z","iopub.execute_input":"2026-02-16T20:31:59.372496Z","iopub.status.idle":"2026-02-16T20:31:59.397240Z","shell.execute_reply.started":"2026-02-16T20:31:59.372446Z","shell.execute_reply":"2026-02-16T20:31:59.396668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class testdataset(Dataset):\n    def __init__(self, feature,test_DIR,is_test=True, transform=None):\n        self.feature = feature\n        self.transform = transform\n        self.test_DIR = Path(test_DIR)\n        self.is_test = is_test\n        \n\n    def __len__(self):\n        return self.feature.shape[0]\n\n    def __getitem__(self,idx):\n        image_name = self.feature[idx]\n\n        image_path = self.test_DIR / image_name\n\n        img = Image.open(image_path).convert('RGB')    \n        if self.transform:\n            image = self.transform(img)\n            \n        return image , image_name\n        \n        ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:00.490535Z","iopub.execute_input":"2026-02-16T20:32:00.491286Z","iopub.status.idle":"2026-02-16T20:32:00.496512Z","shell.execute_reply.started":"2026-02-16T20:32:00.491254Z","shell.execute_reply":"2026-02-16T20:32:00.495630Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"target_size = (384,384)\ntransform_test = transforms.Compose([\n    transforms.Resize(target_size),\n    transforms.ToTensor(),\n    transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:03.024729Z","iopub.execute_input":"2026-02-16T20:32:03.025488Z","iopub.status.idle":"2026-02-16T20:32:03.029627Z","shell.execute_reply.started":"2026-02-16T20:32:03.025459Z","shell.execute_reply":"2026-02-16T20:32:03.028828Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset = testdataset(unique_test_images , test_DIR , transform=transform_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:03.571446Z","iopub.execute_input":"2026-02-16T20:32:03.572055Z","iopub.status.idle":"2026-02-16T20:32:03.575847Z","shell.execute_reply.started":"2026-02-16T20:32:03.572025Z","shell.execute_reply":"2026-02-16T20:32:03.574974Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_loader = DataLoader(test_dataset ,batch_size = 25,  shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:06.503590Z","iopub.execute_input":"2026-02-16T20:32:06.503865Z","iopub.status.idle":"2026-02-16T20:32:06.508014Z","shell.execute_reply.started":"2026-02-16T20:32:06.503840Z","shell.execute_reply":"2026-02-16T20:32:06.507150Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"test_dataset[0][0].shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:06.925529Z","iopub.execute_input":"2026-02-16T20:32:06.926106Z","iopub.status.idle":"2026-02-16T20:32:07.024472Z","shell.execute_reply.started":"2026-02-16T20:32:06.926075Z","shell.execute_reply":"2026-02-16T20:32:07.023795Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.eval()\nembedding_dict = {}\nwith torch.inference_mode():\n    for image , name in tqdm(test_loader):\n        image = image.to(device)\n        embedding = model(image)\n\n        for i , names in enumerate(name):\n            embedding_dict[names] = embedding[i].cpu()\n\nprediction = []\nfor index , row in tqdm(test_data.iterrows(), total=len(test_data)):\n    img_q_name = row['query_image']\n    img_g_name = row['gallery_image']\n\n    vec_q = embedding_dict[img_q_name]\n    vec_g = embedding_dict[img_g_name]\n\n    similarity = F.cosine_similarity(vec_q,vec_g,dim=0).item()\n    prediction.append(max(0.0,similarity))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:32:08.137578Z","iopub.execute_input":"2026-02-16T20:32:08.137883Z","iopub.status.idle":"2026-02-16T20:34:11.733370Z","shell.execute_reply.started":"2026-02-16T20:32:08.137856Z","shell.execute_reply":"2026-02-16T20:34:11.732447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission = pd.DataFrame({\n    'row_id': test_data['row_id'],\n    'similarity': prediction\n})\nsubmission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:34:14.341331Z","iopub.execute_input":"2026-02-16T20:34:14.341928Z","iopub.status.idle":"2026-02-16T20:34:14.362958Z","shell.execute_reply.started":"2026-02-16T20:34:14.341878Z","shell.execute_reply":"2026-02-16T20:34:14.362273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission_DL1.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2026-02-16T20:34:16.455589Z","iopub.execute_input":"2026-02-16T20:34:16.455858Z","iopub.status.idle":"2026-02-16T20:34:16.704587Z","shell.execute_reply.started":"2026-02-16T20:34:16.455835Z","shell.execute_reply":"2026-02-16T20:34:16.703865Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}