{"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":71549,"databundleVersionId":8561470,"sourceType":"competition"}],"dockerImageVersionId":31089,"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\n# import numpy as np # linear algebra\n# import 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\n# import os\n# for 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-08-23T16:42:47.773994Z","iopub.execute_input":"2025-08-23T16:42:47.774296Z","iopub.status.idle":"2025-08-23T16:42:47.779102Z","shell.execute_reply.started":"2025-08-23T16:42:47.774271Z","shell.execute_reply":"2025-08-23T16:42:47.777809Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport torch\nimport torch.nn as nn\nfrom torchvision.transforms import transforms\nimport os","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:25.282626Z","iopub.execute_input":"2025-08-30T16:27:25.282868Z","iopub.status.idle":"2025-08-30T16:27:27.902258Z","shell.execute_reply.started":"2025-08-30T16:27:25.282849Z","shell.execute_reply":"2025-08-30T16:27:27.900780Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"root=\"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:27.903391Z","iopub.execute_input":"2025-08-30T16:27:27.904033Z","iopub.status.idle":"2025-08-30T16:27:27.909800Z","shell.execute_reply.started":"2025-08-30T16:27:27.903997Z","shell.execute_reply":"2025-08-30T16:27:27.908530Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.path.join(root, \"train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:27.911014Z","iopub.execute_input":"2025-08-30T16:27:27.912022Z","iopub.status.idle":"2025-08-30T16:27:27.945641Z","shell.execute_reply.started":"2025-08-30T16:27:27.911964Z","shell.execute_reply":"2025-08-30T16:27:27.944263Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train = pd.read_csv(os.path.join(root, \"train.csv\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:27.947011Z","iopub.execute_input":"2025-08-30T16:27:27.947283Z","iopub.status.idle":"2025-08-30T16:27:28.007163Z","shell.execute_reply.started":"2025-08-30T16:27:27.947262Z","shell.execute_reply":"2025-08-30T16:27:28.006128Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:28.010581Z","iopub.execute_input":"2025-08-30T16:27:28.011016Z","iopub.status.idle":"2025-08-30T16:27:28.046896Z","shell.execute_reply.started":"2025-08-30T16:27:28.010984Z","shell.execute_reply":"2025-08-30T16:27:28.046062Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train_label_coordinates = pd.read_csv(os.path.join(root, \"train_label_coordinates.csv\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:28.047835Z","iopub.execute_input":"2025-08-30T16:27:28.048070Z","iopub.status.idle":"2025-08-30T16:27:28.173369Z","shell.execute_reply.started":"2025-08-30T16:27:28.048049Z","shell.execute_reply":"2025-08-30T16:27:28.172172Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_train_label_coordinates.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:28.174503Z","iopub.execute_input":"2025-08-30T16:27:28.174877Z","iopub.status.idle":"2025-08-30T16:27:28.187522Z","shell.execute_reply.started":"2025-08-30T16:27:28.174849Z","shell.execute_reply":"2025-08-30T16:27:28.186583Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_img_path = \"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/100206310/1012284084/1.dcm\"","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:28.188676Z","iopub.execute_input":"2025-08-30T16:27:28.189034Z","iopub.status.idle":"2025-08-30T16:27:28.210901Z","shell.execute_reply.started":"2025-08-30T16:27:28.189002Z","shell.execute_reply":"2025-08-30T16:27:28.209504Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from pydicom import dcmread","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:28.211765Z","iopub.execute_input":"2025-08-30T16:27:28.211980Z","iopub.status.idle":"2025-08-30T16:27:29.041914Z","shell.execute_reply.started":"2025-08-30T16:27:28.211963Z","shell.execute_reply":"2025-08-30T16:27:29.040668Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dcm_output = dcmread(sample_img_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.043921Z","iopub.execute_input":"2025-08-30T16:27:29.044418Z","iopub.status.idle":"2025-08-30T16:27:29.076402Z","shell.execute_reply.started":"2025-08-30T16:27:29.044382Z","shell.execute_reply":"2025-08-30T16:27:29.074713Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dcm_output","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.077774Z","iopub.execute_input":"2025-08-30T16:27:29.078158Z","iopub.status.idle":"2025-08-30T16:27:29.089407Z","shell.execute_reply.started":"2025-08-30T16:27:29.078128Z","shell.execute_reply":"2025-08-30T16:27:29.087691Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dcm_img = dcm_output.pixel_array","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.090538Z","iopub.execute_input":"2025-08-30T16:27:29.090938Z","iopub.status.idle":"2025-08-30T16:27:29.122328Z","shell.execute_reply.started":"2025-08-30T16:27:29.090914Z","shell.execute_reply":"2025-08-30T16:27:29.120708Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"dcm_img.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.123513Z","iopub.execute_input":"2025-08-30T16:27:29.124028Z","iopub.status.idle":"2025-08-30T16:27:29.152268Z","shell.execute_reply.started":"2025-08-30T16:27:29.123996Z","shell.execute_reply":"2025-08-30T16:27:29.150647Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.154952Z","iopub.execute_input":"2025-08-30T16:27:29.155274Z","iopub.status.idle":"2025-08-30T16:27:29.183625Z","shell.execute_reply.started":"2025-08-30T16:27:29.155252Z","shell.execute_reply":"2025-08-30T16:27:29.182685Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(dcm_img, cmap='gray')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.184724Z","iopub.execute_input":"2025-08-30T16:27:29.185085Z","iopub.status.idle":"2025-08-30T16:27:29.566862Z","shell.execute_reply.started":"2025-08-30T16:27:29.185056Z","shell.execute_reply":"2025-08-30T16:27:29.565492Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"idx=10\nsample_img_path = f\"/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/100206310/2092806862/{idx}.dcm\"\ndcm_img = dcmread(sample_img_path).pixel_array\nplt.imshow(dcm_img, cmap='gray')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.567910Z","iopub.execute_input":"2025-08-30T16:27:29.568268Z","iopub.status.idle":"2025-08-30T16:27:29.883968Z","shell.execute_reply.started":"2025-08-30T16:27:29.568238Z","shell.execute_reply":"2025-08-30T16:27:29.882706Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# df_train \ndf_labels = pd.read_csv(os.path.join(root, \"train.csv\"))\n# df_train_label_coordinates\ndf_img = pd.read_csv(os.path.join(root, \"train_label_coordinates.csv\"))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.887217Z","iopub.execute_input":"2025-08-30T16:27:29.887502Z","iopub.status.idle":"2025-08-30T16:27:29.969499Z","shell.execute_reply.started":"2025-08-30T16:27:29.887483Z","shell.execute_reply":"2025-08-30T16:27:29.968497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"patients_id = df_labels['study_id'].unique()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.971143Z","iopub.execute_input":"2025-08-30T16:27:29.972054Z","iopub.status.idle":"2025-08-30T16:27:29.981967Z","shell.execute_reply.started":"2025-08-30T16:27:29.972014Z","shell.execute_reply":"2025-08-30T16:27:29.980292Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_labels[df_labels['study_id']==4003253]['spinal_canal_stenosis_l1_l2']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:29.983481Z","iopub.execute_input":"2025-08-30T16:27:29.983821Z","iopub.status.idle":"2025-08-30T16:27:30.007492Z","shell.execute_reply.started":"2025-08-30T16:27:29.983786Z","shell.execute_reply":"2025-08-30T16:27:30.006620Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"patient_table = df_img[df_img['study_id']==4003253]\nseries_id = patient_table['series_id'].unique()\npatient_position = patient_table[patient_table['series_id']==702807833]\npatient_img = patient_position[patient_position['instance_number']==8]\ncondition = patient_img.iloc[0]['condition']\nlevel = patient_img.iloc[0]['level']\n\ncol_name = condition.lower().replace(' ','_') + '_' + level.lower().replace('/', '_')\n\n\nstatus = df_labels[df_labels['study_id']==4003253][col_name].values[0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:30.008607Z","iopub.execute_input":"2025-08-30T16:27:30.008852Z","iopub.status.idle":"2025-08-30T16:27:30.036560Z","shell.execute_reply.started":"2025-08-30T16:27:30.008834Z","shell.execute_reply":"2025-08-30T16:27:30.035519Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for row in patient_img:\n    print(row)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:30.037397Z","iopub.execute_input":"2025-08-30T16:27:30.037668Z","iopub.status.idle":"2025-08-30T16:27:30.060148Z","shell.execute_reply.started":"2025-08-30T16:27:30.037650Z","shell.execute_reply":"2025-08-30T16:27:30.059091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"imgs_path = []\nlabels = []\nroot_path = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/'\nfor patient_id in patients_id:\n    patient_table = df_img[df_img['study_id']==patient_id]\n    series_id = patient_table['series_id'].unique()\n    for serie_id in series_id:\n        patient_position = patient_table[patient_table['series_id']==serie_id]\n        instance_numbers = patient_position['instance_number'].unique()\n        for instance_number in instance_numbers:\n            patient_img = patient_position[patient_position['instance_number']==instance_number]\n            for row in range(len(patient_img)):\n                condition = patient_img.iloc[row]['condition']\n                level = patient_img.iloc[row]['level']\n                col_name = condition.lower().replace(' ','_') + '_' + level.lower().replace('/', '_')\n\n                status = df_labels[df_labels['study_id']==patient_id][col_name].values[0]\n\n                if status.lower() == 'Normal/Mild'.lower()\n                    label = 0\n                \n                if status.lower() == 'Moderate'.lower()\n                    label = 1\n                \n                if status.lower() == 'Severe'.lower()\n                    label = 2\n\n                img_path = os.path.join(root_path, str(patient_id), str(serie_id), str(instance_number))\n\n                imgs_path.append(img_path)\n                labels.append(label)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:30.061406Z","iopub.execute_input":"2025-08-30T16:27:30.061722Z","iopub.status.idle":"2025-08-30T16:27:30.082823Z","shell.execute_reply.started":"2025-08-30T16:27:30.061695Z","shell.execute_reply":"2025-08-30T16:27:30.081629Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.path.join(\"1\",'2','3')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:41.788894Z","iopub.execute_input":"2025-08-30T16:27:41.789161Z","iopub.status.idle":"2025-08-30T16:27:41.796478Z","shell.execute_reply.started":"2025-08-30T16:27:41.789143Z","shell.execute_reply":"2025-08-30T16:27:41.794978Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"root_path = '/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/'","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:42.557685Z","iopub.execute_input":"2025-08-30T16:27:42.558244Z","iopub.status.idle":"2025-08-30T16:27:42.562680Z","shell.execute_reply.started":"2025-08-30T16:27:42.558221Z","shell.execute_reply":"2025-08-30T16:27:42.561659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader, random_split\nimport math\n\nclass lumbar_dataset(Dataset):\n    def __init__(self, root_path, df_train_path, df_coord_path, transform):\n        self.imgs_path = []\n        self.labels = []\n\n        self.transform = transform\n        \n        df_img = pd.read_csv(df_coord_path)\n        df_labels = pd.read_csv(df_train_path)\n        \n        for patient_id in patients_id[:10]:\n            patient_table = df_img[df_img['study_id']==patient_id]\n            series_id = patient_table['series_id'].unique()\n            for serie_id in series_id:\n                patient_position = patient_table[patient_table['series_id']==serie_id]\n                instance_numbers = patient_position['instance_number'].unique()\n                for instance_number in instance_numbers:\n                    patient_img = patient_position[patient_position['instance_number']==instance_number]\n                    for row in range(len(patient_img)):\n                        condition = patient_img.iloc[row]['condition']\n                        level = patient_img.iloc[row]['level']\n                        col_name = condition.lower().replace(' ','_') + '_' + level.lower().replace('/', '_')\n        \n                        status = df_labels[df_labels['study_id']==patient_id][col_name].values[0]\n                        if type(status) is not str: #or math.isnan(status):\n                            # print(f\"patient_id: {patient_id}, col_name: {col_name}, status: {status},\\\n                            # serie_id: {serie_id}, instance_number: {instance_number}, row: {row},\\\n                            # condition: {condition}, level: {level}\")\n                            print(f\"In patient_id: {patient_id} Nan occured!\")\n                            continue\n                            \n                        try:\n                            if status.lower() == 'Normal/Mild'.lower():\n                                label = 0\n                            \n                            elif status.lower() == 'Moderate'.lower():\n                                label = 1\n                            \n                            elif status.lower() == 'Severe'.lower():\n                                label = 2\n    \n                            else:\n                                assert False, f\"The status didn't match any of predefined labels: {status}\"\n\n                        except:\n                            assert False, f\"patient_id: {patient_id}, col_name: {col_name}, status: {status},\\\n                            serie_id: {serie_id}, instance_number: {instance_number}, row: {row},\\\n                            condition: {condition}, level: {level}\"\n                        \n                        img_path = os.path.join(root_path, str(patient_id), str(serie_id), str(instance_number) + '.dcm')\n\n                        if os.path.exists(img_path):\n                            self.imgs_path.append(img_path)\n                            self.labels.append(label)\n                        else:\n                            print(f\"Image path does not exists! {img_path}\")\n                            continue\n\n        # assert False==True, \"Error\"\n        assert len(self.imgs_path) == len(self.labels), \"ERROR: images and labels mismatch lentgh\"\n        \n    def __len__(self):\n        return len(self.imgs_path)\n\n    def __getitem__(self, idx):\n        img_array = dcmread(self.imgs_path[idx]).pixel_array\n        label = self.labels[idx]\n\n        img = self.transform(img_array.astype(np.uint8))\n        \n        return img, label","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:55:32.658410Z","iopub.execute_input":"2025-08-30T16:55:32.658860Z","iopub.status.idle":"2025-08-30T16:55:32.670087Z","shell.execute_reply.started":"2025-08-30T16:55:32.658835Z","shell.execute_reply":"2025-08-30T16:55:32.669219Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from torchvision.transforms import v2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:27:50.756911Z","iopub.execute_input":"2025-08-30T16:27:50.757193Z","iopub.status.idle":"2025-08-30T16:27:50.761610Z","shell.execute_reply.started":"2025-08-30T16:27:50.757175Z","shell.execute_reply":"2025-08-30T16:27:50.760653Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"torch.__version__","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:52:44.067135Z","iopub.execute_input":"2025-08-30T16:52:44.067498Z","iopub.status.idle":"2025-08-30T16:52:44.073213Z","shell.execute_reply.started":"2025-08-30T16:52:44.067477Z","shell.execute_reply":"2025-08-30T16:52:44.072497Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torchvision\ntorchvision.__version__","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T16:53:12.412869Z","iopub.execute_input":"2025-08-30T16:53:12.413142Z","iopub.status.idle":"2025-08-30T16:53:12.419619Z","shell.execute_reply.started":"2025-08-30T16:53:12.413123Z","shell.execute_reply":"2025-08-30T16:53:12.418770Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"transform = v2.Compose([\n    v2.ToPILImage(),\n    v2.Grayscale(num_output_channels=3),\n    v2.Resize(256), # v2.Resize(224, 224)\n    v2.CenterCrop(224),\n    v2.RandomRotation(30),\n    v2.RandomApply([v2.GaussianBlur(3, 1)],p=0.5),\n    v2.RandomHorizontalFlip(p=0.5),\n    v2.ToTensor(),\n    v2.RandomApply([v2.GaussianNoise(0,0.01),],p=0.5),\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T17:19:55.957100Z","iopub.execute_input":"2025-08-30T17:19:55.957365Z","iopub.status.idle":"2025-08-30T17:19:55.963918Z","shell.execute_reply.started":"2025-08-30T17:19:55.957344Z","shell.execute_reply":"2025-08-30T17:19:55.963043Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# TODO: check dataset for len images !!!!\nfull_dataset = lumbar_dataset(root_path='/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_images/',\n                            df_train_path='/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train.csv',\n                            df_coord_path='/kaggle/input/rsna-2024-lumbar-spine-degenerative-classification/train_label_coordinates.csv',\n                            transform = transform)\n\ntrain_size = int(0.8 * len(full_dataset))\nval_size = len(full_dataset) - train_size\n\ntrain_dataset, val_dataset = random_split(full_dataset, [train_size, val_size])\n\nprint(f\"len(train_dataset): {len(train_dataset)}, len(val_dataset): {len(val_dataset)}\")\n\ntrain_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)\neval_loader = DataLoader(val_dataset, batch_size=64, shuffle=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T17:19:58.668525Z","iopub.execute_input":"2025-08-30T17:19:58.668832Z","iopub.status.idle":"2025-08-30T17:19:59.096347Z","shell.execute_reply.started":"2025-08-30T17:19:58.668812Z","shell.execute_reply":"2025-08-30T17:19:59.095321Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from tqdm import tqdm\ndef train(loader, optimizer, criterion, model, device, epoch):\n    total_loss = []\n    model.train()\n    pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n    for imgs, labels in pbar:\n        imgs, labels = imgs.to(device), labels.to(device)\n        optimizer.zero_grad()\n        pred = model(imgs)\n        loss = criterion(pred, labels)\n        pbar.set_postfix(loss=loss.item())\n        total_loss.append(loss.item())\n        loss.backward()\n        optimizer.step()\n\n    return np.mean(total_loss)\n\n\ndef evaluation(loader, criterion, model, device, epoch):\n    total_loss = []\n    model.eval()\n    pbar = tqdm(loader, desc=f\"Epoch {epoch}\")\n    with torch.no_grad():\n        for imgs, labels in pbar:\n            imgs, labels = imgs.to(device), labels.to(device)\n            pred = model(imgs)\n            loss = criterion(pred, labels)\n            pbar.set_postfix(loss=loss.item())\n            total_loss.append(loss.item())\n            \n    return np.mean(total_loss)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T17:20:53.569475Z","iopub.execute_input":"2025-08-30T17:20:53.569766Z","iopub.status.idle":"2025-08-30T17:20:53.576956Z","shell.execute_reply.started":"2025-08-30T17:20:53.569748Z","shell.execute_reply":"2025-08-30T17:20:53.575625Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model = torchvision.models.resnet50(weights=\"IMAGENET1K_V1\")\nmodel.fc = nn.Linear(in_features=model.fc.in_features, out_features=3)\n\nfor name, param in model.named_parameters():\n    if 'fc' not in name:\n        param.requires_grad = False\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\noptimizer = torch.optim.SGD(model.parameters(),lr=0.01)\ncriterion = nn.CrossEntropyLoss().to(device)\nmodel = model.to(device)\n\nepochs=50","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T17:20:54.106316Z","iopub.execute_input":"2025-08-30T17:20:54.106644Z","iopub.status.idle":"2025-08-30T17:20:54.522348Z","shell.execute_reply.started":"2025-08-30T17:20:54.106615Z","shell.execute_reply":"2025-08-30T17:20:54.521443Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"for epoch in range(epochs):\n    train_loss = train(train_loader, optimizer, criterion, model, device)\n    eval_loss = evaluation(eval_loader, criterion, model, device)\n    print(f\"Epoch {epoch}/{epochs}: train loss: {train_loss}, validation loss: {eval_loss}\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-30T17:20:54.746227Z","iopub.execute_input":"2025-08-30T17:20:54.746515Z","iopub.status.idle":"2025-08-30T17:23:27.238686Z","shell.execute_reply.started":"2025-08-30T17:20:54.746495Z","shell.execute_reply":"2025-08-30T17:23:27.237378Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# The difference between Resize, CenterCrop","metadata":{}},{"cell_type":"code","source":"!wget https://www.mount-it.com/cdn/shop/articles/Ultrawide_Monitor_a8d20e1e-12b9-4e0c-b6cf-678ca76b3ccf.webp?v=1747237890 -O ./im.jpg","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:33:39.544064Z","iopub.execute_input":"2025-08-26T16:33:39.544441Z","iopub.status.idle":"2025-08-26T16:33:39.946484Z","shell.execute_reply.started":"2025-08-26T16:33:39.544412Z","shell.execute_reply":"2025-08-26T16:33:39.945259Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"t","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:49:29.147320Z","iopub.execute_input":"2025-08-26T16:49:29.147656Z","iopub.status.idle":"2025-08-26T16:49:29.154490Z","shell.execute_reply.started":"2025-08-26T16:49:29.147631Z","shell.execute_reply":"2025-08-26T16:49:29.153470Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import cv2","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:34:10.213268Z","iopub.execute_input":"2025-08-26T16:34:10.213598Z","iopub.status.idle":"2025-08-26T16:34:10.558991Z","shell.execute_reply.started":"2025-08-26T16:34:10.213572Z","shell.execute_reply":"2025-08-26T16:34:10.558135Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img = cv2.imread('./im.jpg')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:34:28.605708Z","iopub.execute_input":"2025-08-26T16:34:28.606024Z","iopub.status.idle":"2025-08-26T16:34:28.645949Z","shell.execute_reply.started":"2025-08-26T16:34:28.606005Z","shell.execute_reply":"2025-08-26T16:34:28.644784Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"t1 = v2.Compose([\n    v2.ToPILImage(),\n    v2.Resize(256), # v2.Resize(224, 224)\n    v2.CenterCrop(224),\n    v2.ToTensor()\n])\nt2 = v2.Compose([\n    v2.ToPILImage(),\n    v2.Resize((224, 224)),\n    v2.ToTensor()\n])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:36:10.375241Z","iopub.execute_input":"2025-08-26T16:36:10.375615Z","iopub.status.idle":"2025-08-26T16:36:10.381955Z","shell.execute_reply.started":"2025-08-26T16:36:10.375587Z","shell.execute_reply":"2025-08-26T16:36:10.380914Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"im1 = t1(img)\nim2 = t2(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:36:12.187012Z","iopub.execute_input":"2025-08-26T16:36:12.187339Z","iopub.status.idle":"2025-08-26T16:36:12.205313Z","shell.execute_reply.started":"2025-08-26T16:36:12.187306Z","shell.execute_reply":"2025-08-26T16:36:12.204091Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:37:02.580684Z","iopub.execute_input":"2025-08-26T16:37:02.581063Z","iopub.status.idle":"2025-08-26T16:37:02.586017Z","shell.execute_reply.started":"2025-08-26T16:37:02.581036Z","shell.execute_reply":"2025-08-26T16:37:02.584904Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(im1.permute(1,2,0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:37:08.297357Z","iopub.execute_input":"2025-08-26T16:37:08.297691Z","iopub.status.idle":"2025-08-26T16:37:08.591125Z","shell.execute_reply.started":"2025-08-26T16:37:08.297665Z","shell.execute_reply":"2025-08-26T16:37:08.589905Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.imshow(im2.permute(1,2,0))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-08-26T16:37:13.876871Z","iopub.execute_input":"2025-08-26T16:37:13.877192Z","iopub.status.idle":"2025-08-26T16:37:14.181216Z","shell.execute_reply.started":"2025-08-26T16:37:13.877170Z","shell.execute_reply":"2025-08-26T16:37:14.180172Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}