{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":20270,"databundleVersionId":1222630,"sourceType":"competition"},{"sourceId":1253590,"sourceType":"datasetVersion","datasetId":720563},{"sourceId":1225697,"sourceType":"datasetVersion","datasetId":701123}],"dockerImageVersionId":30648,"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\ninput_directory = '/kaggle/input'\nfor dirpath, dirnames, filenames in os.walk(input_directory):\n    for dirname in dirnames:\n        print(dirname)\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","execution":{"iopub.status.busy":"2024-01-30T10:23:10.011364Z","iopub.execute_input":"2024-01-30T10:23:10.012235Z","iopub.status.idle":"2024-01-30T10:25:02.126748Z","shell.execute_reply.started":"2024-01-30T10:23:10.0122Z","shell.execute_reply":"2024-01-30T10:25:02.125518Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install torchtoolbox","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:25:02.128775Z","iopub.execute_input":"2024-01-30T10:25:02.129914Z","iopub.status.idle":"2024-01-30T10:25:14.562733Z","shell.execute_reply.started":"2024-01-30T10:25:02.12987Z","shell.execute_reply":"2024-01-30T10:25:14.561442Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sb\nimport cv2\nfrom PIL import Image\nimport gc","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:25:34.46474Z","iopub.execute_input":"2024-01-30T10:25:34.465143Z","iopub.status.idle":"2024-01-30T10:25:34.98109Z","shell.execute_reply.started":"2024-01-30T10:25:34.465104Z","shell.execute_reply":"2024-01-30T10:25:34.980312Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nfrom torch import nn\nfrom torch import optim\nimport torch.nn.functional as F\nfrom torchvision import datasets, transforms, models\nfrom torch.utils.data import Dataset\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\n\n#import torchtoolbox.transform as transforms\nfrom torch.utils.data import Dataset, DataLoader","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:25:37.35782Z","iopub.execute_input":"2024-01-30T10:25:37.358576Z","iopub.status.idle":"2024-01-30T10:25:40.885248Z","shell.execute_reply.started":"2024-01-30T10:25:37.358542Z","shell.execute_reply":"2024-01-30T10:25:40.884395Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import time\nimport datetime\nimport random\n\nfrom sklearn.model_selection import StratifiedKFold, GroupKFold, train_test_split\nfrom sklearn.metrics import accuracy_score, roc_auc_score, confusion_matrix\n\n!pip install efficientnet_pytorch\nfrom efficientnet_pytorch import EfficientNet\n\nimport warnings\nwarnings.simplefilter('ignore')\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:25:40.886782Z","iopub.execute_input":"2024-01-30T10:25:40.887435Z","iopub.status.idle":"2024-01-30T10:25:52.898356Z","shell.execute_reply.started":"2024-01-30T10:25:40.887405Z","shell.execute_reply":"2024-01-30T10:25:52.897427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import wandb\nwandb.init(project='Skin Melanoma Detection Project', save_code=True,)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:26:05.886348Z","iopub.execute_input":"2024-01-30T10:26:05.887323Z","iopub.status.idle":"2024-01-30T10:26:40.820765Z","shell.execute_reply.started":"2024-01-30T10:26:05.887279Z","shell.execute_reply":"2024-01-30T10:26:40.819721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# SEEDS","metadata":{}},{"cell_type":"code","source":"# Creating seeds to make results reproducible\ndef seed_everything(seed_value):\n    np.random.seed(seed_value)\n    torch.manual_seed(seed_value)\n    os.environ['PYTHONHASHSEED'] = str(seed_value)\n    \n    if torch.cuda.is_available(): \n        torch.cuda.manual_seed(seed_value)\n        torch.cuda.manual_seed_all(seed_value)\n        torch.backends.cudnn.deterministic = True\n        torch.backends.cudnn.benchmark = True\n\nseed = 1234\nseed_everything(seed)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:27:02.682167Z","iopub.execute_input":"2024-01-30T10:27:02.682863Z","iopub.status.idle":"2024-01-30T10:27:03.384343Z","shell.execute_reply.started":"2024-01-30T10:27:02.682825Z","shell.execute_reply":"2024-01-30T10:27:03.383407Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setting up the device","metadata":{}},{"cell_type":"code","source":"# Setting up GPU for processing or CPU if GPU isn't available\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint (device)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:27:11.594671Z","iopub.execute_input":"2024-01-30T10:27:11.595039Z","iopub.status.idle":"2024-01-30T10:27:14.069567Z","shell.execute_reply.started":"2024-01-30T10:27:11.595006Z","shell.execute_reply":"2024-01-30T10:27:14.068556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading Data\n\n## Creating Custom Dataset\n\n","metadata":{}},{"cell_type":"code","source":"class CustomDataset(Dataset):\n  def __init__(self, df: pd.DataFrame, img_dir, train: bool = True, transforms= None):\n    self.df = df\n    self.img_dir = img_dir\n    self.transforms = transforms\n    self.train = train\n\n  def __getitem__(self, index):\n    img_path = os.path.join(self.img_dir, self.df.iloc[index]['image_name'] + '.jpg')\n    #images = Image.open(img_path)\n    images = cv2.imread(img_path)\n\n    if self.transforms:\n        images = self.transforms(images)\n\n    if self.train:\n        labels = self.df.iloc[index]['target']\n        #return images, labels\n        return torch.tensor(images, dtype=torch.float32), torch.tensor(labels, dtype=torch.float32)\n    \n    else:\n        #return (images)\n        return torch.tensor(images, dtype=torch.float32)\n    \n  def __len__(self):\n        return len(self.df)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:27:15.41827Z","iopub.execute_input":"2024-01-30T10:27:15.41864Z","iopub.status.idle":"2024-01-30T10:27:16.209463Z","shell.execute_reply.started":"2024-01-30T10:27:15.418607Z","shell.execute_reply":"2024-01-30T10:27:16.208572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CustomDataset(Dataset):\n    def __init__(self, df: pd.DataFrame, img_dir, train: bool = True, transforms=None):\n        self.df = df\n        self.img_dir = img_dir\n        self.transforms = transforms\n        self.train = train\n\n    def __getitem__(self, index):\n        img_path = os.path.join(self.img_dir, f\"{self.df.iloc[index]['image_name']}.jpg\")\n\n        try:\n            # Load image using cv2\n            image = cv2.imread(img_path)\n\n            # Check if the image is loaded successfully\n            if image is None:\n                raise Exception(f\"Error loading image at index {index}. Image is None. Path: {img_path}\")\n\n            # Convert BGR to RGB (OpenCV loads images in BGR format)\n            image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n\n            if self.transforms:\n                image = self.transforms(image)\n\n            if self.train:\n                label = torch.tensor(self.df.iloc[index]['target'], dtype=torch.float32)\n                return image, label\n            else:\n                return image\n\n        except Exception as e:\n            print(f\"Error loading image at index {index}: {e}\")\n            # Return a default value or raise the exception if needed\n            return None, None\n\n    def __len__(self):\n        return len(self.df)\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:40:38.003893Z","iopub.execute_input":"2024-01-30T10:40:38.004317Z","iopub.status.idle":"2024-01-30T10:40:38.864827Z","shell.execute_reply.started":"2024-01-30T10:40:38.004278Z","shell.execute_reply":"2024-01-30T10:40:38.863888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating Dataframes and image directories","metadata":{}},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/melanoma-external-malignant-256/train_concat.csv')\ntest_df = pd.read_csv('/kaggle/input/siim-isic-melanoma-classification/test.csv')\ntest_img_dir = '/kaggle/input/melanoma-external-malignant-256/test'\ntrain_img_dir = '/kaggle/input/melanoma-external-malignant-256/train'","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:40:41.565926Z","iopub.execute_input":"2024-01-30T10:40:41.566316Z","iopub.status.idle":"2024-01-30T10:40:42.506813Z","shell.execute_reply.started":"2024-01-30T10:40:41.566284Z","shell.execute_reply":"2024-01-30T10:40:42.505798Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(df))\nprint(len(test_df))\nprint(len(test_img_dir))\nprint(len(train_img_dir))","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:36:53.190739Z","iopub.execute_input":"2024-01-30T10:36:53.191119Z","iopub.status.idle":"2024-01-30T10:36:53.940007Z","shell.execute_reply.started":"2024-01-30T10:36:53.191085Z","shell.execute_reply":"2024-01-30T10:36:53.93907Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Creating Validation Data from the Training Data","metadata":{}},{"cell_type":"code","source":"vld_size=0.20\n\ntrain, valid = train_test_split (df, stratify=df.target, test_size = vld_size, random_state=42) \n\ntrain_df=pd.DataFrame(train)\nvalidation_df=pd.DataFrame(valid)\n\nprint(len(validation_df))\nprint(len(train_df))","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:40:45.206897Z","iopub.execute_input":"2024-01-30T10:40:45.207636Z","iopub.status.idle":"2024-01-30T10:40:46.108292Z","shell.execute_reply.started":"2024-01-30T10:40:45.207604Z","shell.execute_reply":"2024-01-30T10:40:46.107325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import StratifiedKFold\n\n# Assuming df is your DataFrame with 'image_name' and 'target' columns\nskf = StratifiedKFold(n_splits=5)\n\n# Iterate over the folds\nfor fold, (train_ix, val_ix) in enumerate(skf.split(df['image_name'].to_numpy(), df['target'].to_numpy())): \n    print(f\"Fold {fold + 1} - Train Size: {len(train_ix)}, Validation Size: {len(val_ix)}\")\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:40:47.518026Z","iopub.execute_input":"2024-01-30T10:40:47.518425Z","iopub.status.idle":"2024-01-30T10:40:48.384836Z","shell.execute_reply.started":"2024-01-30T10:40:47.518396Z","shell.execute_reply":"2024-01-30T10:40:48.383721Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df = df.iloc[train_ix].reset_index(drop=True)\nvalidation_df = df.iloc[val_ix].reset_index(drop=True)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:17.216331Z","iopub.execute_input":"2024-01-30T10:41:17.216719Z","iopub.status.idle":"2024-01-30T10:41:18.033389Z","shell.execute_reply.started":"2024-01-30T10:41:17.216688Z","shell.execute_reply":"2024-01-30T10:41:18.03242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_df))\nprint(len(validation_df))\nprint(len(test_df))","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:19.209819Z","iopub.execute_input":"2024-01-30T10:41:19.210586Z","iopub.status.idle":"2024-01-30T10:41:20.040677Z","shell.execute_reply.started":"2024-01-30T10:41:19.21055Z","shell.execute_reply":"2024-01-30T10:41:20.039718Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Distribution of Targets in Training and Validation sets","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\n# Assuming you have the required data and libraries imported\n\nfig, axes = plt.subplots(nrows=2, ncols=5, figsize=(20, 10))\n\nfor fold, (train_ix, val_ix) in enumerate(skf.split(df['image_name'].to_numpy(), df['target'].to_numpy())): \n    train_df = df.iloc[train_ix].reset_index(drop=True)\n    validation_df = df.iloc[val_ix].reset_index(drop=True)\n\n    # Plotting the bar chart for the training set\n    counts1 = train_df['target'].value_counts()\n    dx = ['Benign', 'Malignant']\n    axes[0, fold].bar(dx, counts1)  \n    axes[0, fold].set_title(f\"Training Set - Fold {fold+1}\")\n    axes[0, fold].legend()\n\n    # Adding text labels on top of each bar in the training set plot\n    for i, v in enumerate(counts1):\n        axes[0, fold].text(i - 0.1, v / counts1[i] + 200, counts1[i], fontsize=10)\n\n    # Plotting the bar chart for the validation set\n    counts2 = validation_df['target'].value_counts()\n    axes[1, fold].bar(dx, counts2)  \n    axes[1, fold].set_title(f\"Validation Set - Fold {fold+1}\")\n    axes[1, fold].legend()\n\n    # Adding text labels on top of each bar in the validation set plot\n    for i, v in enumerate(counts2):\n        axes[1, fold].text(i - 0.1, v / counts2[i] + 100, counts2[i], fontsize=10)\n\nplt.tight_layout()\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:23.405284Z","iopub.execute_input":"2024-01-30T10:41:23.405665Z","iopub.status.idle":"2024-01-30T10:41:25.754311Z","shell.execute_reply.started":"2024-01-30T10:41:23.405628Z","shell.execute_reply":"2024-01-30T10:41:25.753359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Defining Transformations","metadata":{}},{"cell_type":"code","source":"class AdvancedHairAugmentation:\n    \"\"\"\n    Impose an image of a hair to the target image\n\n    Args:\n        hairs (int): maximum number of hairs to impose\n        hairs_folder (str): path to the folder with hairs images\n    \"\"\"\n\n    def __init__(self, hairs: int = 5, hairs_folder: str = \"../input/melanoma-hairs\"):\n        self.hairs = hairs\n        self.hairs_folder = hairs_folder\n\n    def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to draw hairs on.\n\n        Returns:\n            PIL Image: Image with drawn hairs.\n        \"\"\"\n        n_hairs = random.randint(0, self.hairs)\n        \n        if not n_hairs:\n            return img\n        \n        height, width, _ = img.shape  # target image width and height\n        hair_images = [im for im in os.listdir(self.hairs_folder) if 'png' in im]\n        \n        for _ in range(n_hairs):\n            hair = cv2.imread(os.path.join(self.hairs_folder, random.choice(hair_images)))\n            hair = cv2.flip(hair, random.choice([-1, 0, 1]))\n            hair = cv2.rotate(hair, random.choice([0, 1, 2]))\n\n            h_height, h_width, _ = hair.shape  # hair image width and height\n            roi_ho = random.randint(0, img.shape[0] - hair.shape[0])\n            roi_wo = random.randint(0, img.shape[1] - hair.shape[1])\n            roi = img[roi_ho:roi_ho + h_height, roi_wo:roi_wo + h_width]\n\n            # Creating a mask and inverse mask\n            img2gray = cv2.cvtColor(hair, cv2.COLOR_BGR2GRAY)\n            ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY)\n            mask_inv = cv2.bitwise_not(mask)\n\n            # Now black-out the area of hair in ROI\n            img_bg = cv2.bitwise_and(roi, roi, mask=mask_inv)\n\n            # Take only region of hair from hair image.\n            hair_fg = cv2.bitwise_and(hair, hair, mask=mask)\n\n            # Put hair in ROI and modify the target image\n            dst = cv2.add(img_bg, hair_fg)\n\n            img[roi_ho:roi_ho + h_height, roi_wo:roi_wo + h_width] = dst\n                \n        return img\n\n    def __repr__(self):\n        return f'{self.__class__.__name__}(hairs={self.hairs}, hairs_folder=\"{self.hairs_folder}\")'\n\nclass DrawHair:\n    \"\"\"\n    Draw a random number of pseudo hairs\n\n    Args:\n        hairs (int): maximum number of hairs to draw\n        width (tuple): possible width of the hair in pixels\n    \"\"\"\n\n    def __init__(self, hairs:int = 4, width:tuple = (1, 2)):\n        self.hairs = hairs\n        self.width = width\n\n    def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to draw hairs on.\n\n        Returns:\n            PIL Image: Image with drawn hairs.\n        \"\"\"\n        if not self.hairs:\n            return img\n        \n        width, height, _ = img.shape\n        \n        for _ in range(random.randint(0, self.hairs)):\n            # The origin point of the line will always be at the top half of the image\n            origin = (random.randint(0, width), random.randint(0, height // 2))\n            # The end of the line \n            end = (random.randint(0, width), random.randint(0, height))\n            color = (0, 0, 0)  # color of the hair. Black.\n            cv2.line(img, origin, end, color, random.randint(self.width[0], self.width[1]))\n        \n        return img\n\n    def __repr__(self):\n        return f'{self.__class__.__name__}(hairs={self.hairs}, width={self.width})'","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:30.499866Z","iopub.execute_input":"2024-01-30T10:41:30.500544Z","iopub.status.idle":"2024-01-30T10:41:31.368993Z","shell.execute_reply.started":"2024-01-30T10:41:30.500509Z","shell.execute_reply":"2024-01-30T10:41:31.367877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class Microscope:\n    \"\"\"\n    Cutting out the edges around the center circle of the image\n    Imitating a picture, taken through the microscope\n\n    Args:\n        p (float): probability of applying an augmentation\n    \"\"\"\n\n    def __init__(self, p: float = 0.5):\n        self.p = p\n\n    def __call__(self, img):\n        \"\"\"\n        Args:\n            img (PIL Image): Image to apply transformation to.\n\n        Returns:\n            PIL Image: Image with transformation.\n        \"\"\"\n        if random.random() < self.p:\n            circle = cv2.circle((np.ones(img.shape) * 255).astype(np.uint8), # image placeholder\n                        (img.shape[0]//2, img.shape[1]//2), # center point of circle\n                        random.randint(img.shape[0]//2 - 3, img.shape[0]//2 + 15), # radius\n                        (0, 0, 0), # color\n                        -1)\n\n            mask = circle - 255\n            img = np.multiply(img, mask)\n        \n        return img\n\n    def __repr__(self):\n        return f'{self.__class__.__name__}(p={self.p})'","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:32.855873Z","iopub.execute_input":"2024-01-30T10:41:32.856278Z","iopub.status.idle":"2024-01-30T10:41:33.829658Z","shell.execute_reply.started":"2024-01-30T10:41:32.856246Z","shell.execute_reply":"2024-01-30T10:41:33.828642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Setting up transformations","metadata":{"execution":{"iopub.status.busy":"2024-01-30T08:50:39.98844Z","iopub.execute_input":"2024-01-30T08:50:39.989019Z","iopub.status.idle":"2024-01-30T08:50:41.208531Z","shell.execute_reply.started":"2024-01-30T08:50:39.988979Z","shell.execute_reply":"2024-01-30T08:50:41.207641Z"}}},{"cell_type":"code","source":"# Defining transforms for the training, validation, and testing sets\ntraining_transforms = transforms.Compose([#Microscope(),\n                                          AdvancedHairAugmentation(),\n                                          transforms.RandomRotation(30),\n                                          transforms.RandomResizedCrop(256, scale=(0.8, 1.0)),\n                                          transforms.RandomHorizontalFlip(),\n                                          transforms.RandomVerticalFlip(),\n                                          transforms.ColorJitter(brightness=32. / 255.,saturation=0.5,hue=0.01),\n                                          transforms.ToTensor(),\n                                          transforms.Normalize([0.485, 0.456, 0.406], \n                                                               [0.229, 0.224, 0.225])])\n\nvalidation_transforms = transforms.Compose([transforms.Resize(256),\n                                            transforms.CenterCrop(256),\n                                            transforms.ToTensor(),\n                                            transforms.Normalize([0.485, 0.456, 0.406], \n                                                                 [0.229, 0.224, 0.225])])\n\ntesting_transforms = transforms.Compose([transforms.Resize(256),\n                                         transforms.CenterCrop(256),\n                                         transforms.ToTensor(),\n                                         transforms.Normalize([0.485, 0.456, 0.406], \n                                                              [0.229, 0.224, 0.225])])","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:41:59.467243Z","iopub.execute_input":"2024-01-30T10:41:59.467976Z","iopub.status.idle":"2024-01-30T10:42:00.270966Z","shell.execute_reply.started":"2024-01-30T10:41:59.467946Z","shell.execute_reply":"2024-01-30T10:42:00.27013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Loading Datasets","metadata":{}},{"cell_type":"code","source":"# Loading the datasets with the transforms previously defined\ntraining_dataset = CustomDataset(df = train_df,\n                                 img_dir = train_img_dir, \n                                 train = True,\n                                 transforms = training_transforms )\n\nvalidation_dataset = CustomDataset(df = validation_df,\n                                   img_dir = train_img_dir, \n                                   train = True,\n                                   transforms = training_transforms )\n\ntesting_dataset = CustomDataset(df = test_df,\n                                img_dir = test_img_dir,\n                                train= False, \n                                transforms = testing_transforms )","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:03.289597Z","iopub.execute_input":"2024-01-30T10:42:03.290562Z","iopub.status.idle":"2024-01-30T10:42:04.067675Z","shell.execute_reply.started":"2024-01-30T10:42:03.29052Z","shell.execute_reply":"2024-01-30T10:42:04.066793Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Defining Dataloaders","metadata":{}},{"cell_type":"code","source":"# Using the image datasets with the transforms, defining the dataloaders\ntrain_loader = torch.utils.data.DataLoader(training_dataset, batch_size=32, num_workers=4, shuffle=True)\nvalidate_loader = torch.utils.data.DataLoader(validation_dataset, batch_size=16, shuffle = False)\ntest_loader = torch.utils.data.DataLoader(testing_dataset, batch_size=16, shuffle = False)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:06.287898Z","iopub.execute_input":"2024-01-30T10:42:06.288744Z","iopub.status.idle":"2024-01-30T10:42:07.139613Z","shell.execute_reply.started":"2024-01-30T10:42:06.288713Z","shell.execute_reply":"2024-01-30T10:42:07.138611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(len(train_loader))\nprint(len(validate_loader))\nprint(len(test_loader))","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:37:33.086019Z","iopub.execute_input":"2024-01-30T10:37:33.086703Z","iopub.status.idle":"2024-01-30T10:37:33.804783Z","shell.execute_reply.started":"2024-01-30T10:37:33.086671Z","shell.execute_reply":"2024-01-30T10:37:33.803872Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Figuring out how much time the Transformations take","metadata":{}},{"cell_type":"code","source":"'''import time\ntransform_start = time.time()\nfor i, data in enumerate(train_loader):\n    images = data\nend = time.time()\ntime_spent = (end-transform_start)/60\nprint(f\"{time_spent:.3} minutes\")","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:28:45.006591Z","iopub.execute_input":"2024-01-30T10:28:45.00744Z","iopub.status.idle":"2024-01-30T10:28:46.613829Z","shell.execute_reply.started":"2024-01-30T10:28:45.007405Z","shell.execute_reply":"2024-01-30T10:28:46.612209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building the Model","metadata":{}},{"cell_type":"code","source":"class Net(nn.Module):\n    def __init__(self, arch):\n        super(Net, self).__init__()\n        self.arch = arch\n        if 'fgdf' in str(arch.__class__):\n            self.arch.fc = nn.Linear(in_features=1280, out_features=500, bias=True)\n        if 'EfficientNet' in str(arch.__class__):   \n            self.arch._fc = nn.Linear(in_features=1408, out_features=500, bias=True)\n            #self.dropout1 = nn.Dropout(0.2)\n            \n        self.ouput = nn.Linear(500, 1)\n        \n    def forward(self, images):\n        \"\"\"\n        No sigmoid in forward because we are going to use BCEWithLogitsLoss\n        Which applies sigmoid for us when calculating a loss\n        \"\"\"\n        x = images\n        features = self.arch(x)\n        output = self.ouput(features)\n        \n        return output","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:12.314395Z","iopub.execute_input":"2024-01-30T10:42:12.314779Z","iopub.status.idle":"2024-01-30T10:42:13.676077Z","shell.execute_reply.started":"2024-01-30T10:42:12.314744Z","shell.execute_reply":"2024-01-30T10:42:13.675126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"arch = EfficientNet.from_pretrained('efficientnet-b2')\nmodel = Net(arch=arch)  \nmodel = model.to(device)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:16.59225Z","iopub.execute_input":"2024-01-30T10:42:16.593139Z","iopub.status.idle":"2024-01-30T10:42:17.623745Z","shell.execute_reply.started":"2024-01-30T10:42:16.593103Z","shell.execute_reply":"2024-01-30T10:42:17.622662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(model)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:37:45.105955Z","iopub.execute_input":"2024-01-30T10:37:45.106741Z","iopub.status.idle":"2024-01-30T10:37:45.912383Z","shell.execute_reply.started":"2024-01-30T10:37:45.106702Z","shell.execute_reply":"2024-01-30T10:37:45.911463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# If we need to freeze the pretrained model parameters to avoid backpropogating through them, turn to \"False\"\nfor parameter in model.parameters():\n    parameter.requires_grad = True","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:24.375221Z","iopub.execute_input":"2024-01-30T10:42:24.375601Z","iopub.status.idle":"2024-01-30T10:42:25.260267Z","shell.execute_reply.started":"2024-01-30T10:42:24.375563Z","shell.execute_reply":"2024-01-30T10:42:25.259315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Total Parameters (If the model is unfrozen the trainning params will be the same as the Total params)\ntotal_params = sum(p.numel() for p in model.parameters())\nprint(f'{total_params:,} total parameters.')\ntotal_trainable_params = sum(\n    p.numel() for p in model.parameters() if p.requires_grad)\nprint(f'{total_trainable_params:,} training parameters.')","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:25.262203Z","iopub.execute_input":"2024-01-30T10:42:25.262567Z","iopub.status.idle":"2024-01-30T10:42:26.021534Z","shell.execute_reply.started":"2024-01-30T10:42:25.262531Z","shell.execute_reply":"2024-01-30T10:42:26.020575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Hyperparameters","metadata":{}},{"cell_type":"code","source":"# Empty variable to be stored with best validation accuracy\nbest_val_acc = 0\n\n# Path and filename to save model to\nmodel_path = f'melanoma_model_{best_val}.pth'  \n\n# Number of Epochs\nepochs = 10\n\n# Early stopping if no change in accurancy\nes_patience = 3\n\n# Loss Function:\ncriterion = nn.BCEWithLogitsLoss()\n\n# Optimizer (gradient descent):\noptimizer = optim.Adam(model.parameters(), lr=0.0005) \n\n# Scheduler\nscheduler = ReduceLROnPlateau(optimizer=optimizer, mode='max', patience=1, verbose=True, factor=0.2)","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:28.040367Z","iopub.execute_input":"2024-01-30T10:42:28.041064Z","iopub.status.idle":"2024-01-30T10:42:28.869422Z","shell.execute_reply.started":"2024-01-30T10:42:28.041024Z","shell.execute_reply":"2024-01-30T10:42:28.868475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training the Model","metadata":{}},{"cell_type":"code","source":"\n# Empty variable to be stored with best validation accuracy\nbest_val_acc = 0\n\n# Number of consecutive epochs with no improvement to trigger early stopping\nes_patience = 3\nearly_stopping_counter = 0\n\n# Number of epochs\nepochs = 10\n\n# Log the configuration parameters\nconfig = {\n    \"learning_rate\": 0.0005,\n    \"batch_size\": 64,\n    \"architecture\": \"EfficientNet-B2\",\n    \"num_epochs\": epochs,\n}\nwandb.config.update(config)\n\nfor epoch in range(epochs):\n    # Training\n    model.train()\n    total_loss = 0.0\n    correct_train = 0\n    total_train = 0\n\n    for images, labels in train_loader:\n        images, labels = images.to(device), labels.to(device)\n\n        optimizer.zero_grad()\n\n        outputs = model(images)\n        loss = criterion(outputs.squeeze(), labels.float())\n        loss.backward()\n        optimizer.step()\n\n        total_loss += loss.item()\n\n        # Calculate accuracy\n        predictions = torch.round(torch.sigmoid(outputs))\n        correct_train += (predictions == labels.unsqueeze(1)).sum().item()\n        total_train += labels.size(0)\n\n    train_loss = total_loss / len(train_loader)\n    train_acc = correct_train / total_train\n\n    # Validation\n    model.eval()\n    total_val_loss = 0.0\n    correct_val = 0\n    total_val = 0\n\n    with torch.no_grad():\n        for images, labels in validate_loader:\n            images, labels = images.to(device), labels.to(device)\n\n            outputs = model(images)\n            val_loss = criterion(outputs.squeeze(), labels.float())\n            total_val_loss += val_loss.item()\n\n            # Calculate accuracy\n            predictions = torch.round(torch.sigmoid(outputs))\n            correct_val += (predictions == labels.unsqueeze(1)).sum().item()\n            total_val += labels.size(0)\n\n    val_loss = total_val_loss / len(validate_loader)\n    val_acc = correct_val / total_val\n\n    # Log metrics to wandb\n    wandb.log({\"Train Loss\": train_loss, \"Train Acc\": train_acc, \"Val Loss\": val_loss, \"Val Acc\": val_acc})\n\n    print(f\"Epoch {epoch + 1}/{epochs} => \"\n          f\"Train Loss: {train_loss:.4f}, Train Acc: {train_acc:.4f} | \"\n          f\"Val Loss: {val_loss:.4f}, Val Acc: {val_acc:.4f}\")\n\n    # Check for improvement in validation accuracy\n    if val_acc > best_val_acc:\n        best_val_acc = val_acc\n        early_stopping_counter = 0\n        # Save the model\n        torch.save(model.state_dict(), f'model_checkpoint.pth')\n    else:\n        early_stopping_counter += 1\n\n    # Adjust learning rate using scheduler\n    scheduler.step(val_acc)\n\n    # Early stopping check\n    if early_stopping_counter >= es_patience:\n        print(\"Early stopping. No improvement in validation accuracy.\")\n        break\n\n# Finish wandb run\nwandb.finish()\n","metadata":{"execution":{"iopub.status.busy":"2024-01-30T10:42:34.222515Z","iopub.execute_input":"2024-01-30T10:42:34.222867Z","iopub.status.idle":"2024-01-30T10:42:35.937033Z","shell.execute_reply.started":"2024-01-30T10:42:34.222841Z","shell.execute_reply":"2024-01-30T10:42:35.935538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n#from workspace_utils import active_session \n# this can be used so that the session remains on and not disconnect\n\n  \nloss_history=[]  \ntrain_acc_history=[]  \nval_loss_history=[]  \nval_acc_history=[] \nval_auc_history=[]\n\n    \npatience = es_patience\nTotal_start_time = time.time()  \nmodel.to(device)\n\nfor e in range(epochs):\n    \n    start_time = time.time()\n    correct = 0\n    running_loss = 0\n    model.train()\n    \n    for images, labels in train_loader:\n        \n        \n        images, labels = images.to(device), labels.to(device)\n            \n        \n        optimizer.zero_grad()\n        \n        output = model(images) \n        loss = criterion(output, labels.view(-1,1))  \n        loss.backward()\n        optimizer.step()\n        \n        # Training loss\n        running_loss += loss.item()\n\n        # Number of correct training predictions and training accuracy\n        train_preds = torch.round(torch.sigmoid(output))\n            \n        correct += (train_preds.cpu() == labels.cpu().unsqueeze(1)).sum().item()\n                        \n    train_acc = correct / len(train_df)\n        \n        \n    #switching to validation:        \n    model.eval()\n    preds=[]            \n    # Turning off gradients for validation, saves memory and computations\n    with torch.no_grad():\n        \n        val_loss = 0\n        val_correct = 0\n    \n        for val_images, val_labels in validate_loader:\n         \n        \n            val_images, val_labels = val_images.to(device), val_labels.to(device)\n\n        \n            val_output = model(val_images)\n            val_loss += (criterion(val_output, val_labels.view(-1,1))).item() \n            val_pred = torch.sigmoid(val_output)\n            \n            preds.append(val_pred.cpu())\n        pred=np.vstack(preds).ravel()\n           \n        #val_accuracy = accuracy_score(train_df['target'].values, torch.round(pred2))\n        val_auc_score = roc_auc_score(validation_df['target'].values, pred)\n            \n        training_time = str(datetime.timedelta(seconds=time.time() - start_time))[:7]\n            \n        print(\"Epoch: {}/{}.. \".format(e+1, epochs),\n              \"Training Loss: {:.3f}.. \".format(running_loss/len(train_loader)),\n              \"Training Accuracy: {:.3f}..\".format(train_acc),\n              \"Validation Loss: {:.3f}.. \".format(val_loss/len(validate_loader)),\n              #\"Validation Accuracy: {:.3f}\".format(val_accuracy),\n              \"Validation AUC Score: {:.3f}\".format(val_auc_score),\n              \"Training Time: {}\".format( training_time))\n            \n          \n        scheduler.step(val_auc_score)\n                \n        if val_auc_score >= best_val:\n            best_val = val_auc_score\n            patience = es_patience  # Resetting patience since we have new best validation accuracy\n            torch.save(model, model_path)  # Saving current best model\n        else:\n            patience -= 1\n            if patience == 0:\n                print('Early stopping. Best Val roc_auc: {:.3f}'.format(best_val))\n                break\n        \n    loss_history.append(running_loss)  \n    train_acc_history.append(train_acc)    \n    val_loss_history.append(val_loss)  \n    #val_acc_history.append(val_accuracy)\n    val_auc_history.append(val_auc_score)\n    \n\ntotal_training_time = str(datetime.timedelta(seconds=time.time() - Total_start_time  ))[:7]                  \nprint(\"Total Training Time: {}\".format(total_training_time))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}