{"cells":[{"metadata":{},"cell_type":"markdown","source":"# EfficientNet Regression Model\n\nIn this Kernel I am taking the approach of an EfficientNet Architecture.\nThere are some concepts included from iafoss' tiles. However, they are then aggregated to a single picture and fed through the network.\n\nAfterwards I use an optimized threshold to turn the regression into a classification again.","execution_count":null},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline\n\nimport fastai\nfrom fastai.vision import *\nfrom fastai.callbacks import SaveModelCallback\nimport os\n#from sklearn.model_selection import KFold\nfrom radam import *\nfrom csvlogger import *\nfrom mish_activation import *\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.metrics import cohen_kappa_score,confusion_matrix\nimport warnings\nimport scipy as sp\nimport skimage.io\nimport cv2\n\nwarnings.filterwarnings(\"ignore\")\n\n# remove this cell if run locally\n!mkdir 'cache'\n!mkdir 'cache/torch'\n!mkdir 'cache/torch/checkpoints'\ntorch.hub.DEFAULT_CACHE_DIR = 'cache'\n\n# EfficientNet imports\nimport sys\npackage_path = '../input/efficientnet-pytorch/EfficientNet-PyTorch/EfficientNet-PyTorch-master'\nsys.path.append(package_path)\nfrom efficientnet_pytorch import EfficientNet\n\nfrom albumentations import Compose, Normalize, HorizontalFlip, VerticalFlip\nfrom albumentations.pytorch import ToTensorV2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs = 4\nn_epochs = 16\ntile_sz = 132\nnfolds = 5\nN = 16\n\nLABELS = '../input/prostate-cancer-grade-assessment/train.csv'","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True\n    torch.backends.cudnn.benchmark = True\n\nSEED = 42\nseed_everything(SEED)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Preparation and Cleaning\nData cleaning is based on this Kernel: https://www.kaggle.com/tanulsingh077/prostate-cancer-in-depth-understanding-eda-model\nThank you a lot for your EDA!","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"df = pd.read_csv(LABELS).set_index('image_id')\n\n# Wrongly labeled data\nwrong_label = df[(df['isup_grade'] == 2) & (df['gleason_score'] == '4+3')]\ndisplay(wrong_label)\ndf.drop([wrong_label.index[0]],inplace=True)\ndf = df.reset_index()\n\n# incosistency with \"0\" and \"negative\"\ndf['gleason_score'] = df['gleason_score'].apply(lambda x: \"0+0\" if x==\"negative\" else x)\n\nsplits = StratifiedKFold(n_splits=nfolds, random_state=SEED, shuffle=True)\nsplits = list(splits.split(df,df.isup_grade))\nfolds_splits = np.zeros(len(df)).astype(np.int)\n\nfor i in range(nfolds):\n    if i == nfolds-1:\n        folds_splits[splits[i][1]] = 0\n    else:    \n        folds_splits[splits[i][1]] = 1\n    \ndf['split'] = folds_splits\ndf.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df['isup_grade'].hist()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Datasets","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def tile(img, sz=128, N=16):\n    \"\"\" Subdivide large image in tiles and return most significant squares\n    \n    Params:\n    img: large input image\n    sz: size of tiles\n    N: number of most important tiles\n    \n    Returns: list of N most significant tiles\n    \"\"\"\n    shape = img.shape\n    pad0,pad1 = (sz - shape[0]%sz)%sz, (sz - shape[1]%sz)%sz\n    \n    img = np.pad(img,[[pad0//2,pad0-pad0//2],[pad1//2,pad1-pad1//2],[0,0]],constant_values=255)\n    img = img.reshape(img.shape[0]//sz,sz,img.shape[1]//sz,sz,3)\n    img = img.transpose(0,2,1,3,4).reshape(-1,sz,sz,3)\n    \n    if len(img) < N:\n        img = np.pad(img,[[0,N-len(img)],[0,0],[0,0],[0,0]],constant_values=255)\n        \n    idxs = np.argsort(img.reshape(img.shape[0],-1).sum(-1))[:N]\n    img = img[idxs]\n    return img","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class TrainDataset(Dataset):\n    def __init__(self, df, labels, transform=None):\n        self.df = df\n        self.labels = labels\n        self.transform = transform\n        \n    def __len__(self):\n        return len(self.df)\n\n    def __getitem__(self, idx):\n        file_name = self.df['image_id'].values[idx]\n        file_path = f'../input/prostate-cancer-grade-assessment/train_images/{file_name}.tiff'\n        image = skimage.io.MultiImage(file_path)[-1]\n        image = tile(image, sz=tile_sz, N=N)\n        image = cv2.hconcat([cv2.vconcat([image[0], image[1], image[2], image[3]]), \n                             cv2.vconcat([image[4], image[5], image[6], image[7]]), \n                             cv2.vconcat([image[8], image[9], image[10], image[11]]), \n                             cv2.vconcat([image[12], image[13], image[14], image[15]])])\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        \n        if self.transform:\n            augmented = self.transform(image=image)\n            image = augmented['image']\n            \n        label = torch.tensor(self.labels[idx]).float()\n        \n        return image, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_transforms(*, data):\n    \"\"\"\n    Get image transformation of data\n    \"\"\"\n    assert data in ('train', 'valid')\n    \n    if data == 'train':\n        return Compose([\n            HorizontalFlip(p=0.5),\n            VerticalFlip(p=0.5),\n            Normalize(\n                mean=[0.485, 0.456, 0.406],\n                std=[0.229, 0.224, 0.225],\n            ),\n            ToTensorV2(),\n        ])\n    \n    elif data == 'valid':\n        return Compose([\n            Normalize(\n                mean=[0.485, 0.456, 0.406],\n                std=[0.229, 0.224, 0.225],\n            ),\n            ToTensorV2(),\n        ])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = TrainDataset(df, df[\"isup_grade\"], transform=get_transforms(data='train'))\ntrain_loader = DataLoader(train_dataset, batch_size=bs, shuffle=False)\n\nfor image, label in train_loader:\n    print(image[0].shape)\n    plt.imshow(image[0].permute(1,2,0))\n    plt.show()  \n    break","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"I use an image size of 528x528, as it is the optimal resolution for EffcientNetB6 and its compound factor. Therefore, my tile size is also 132 instead of 128","execution_count":null},{"metadata":{},"cell_type":"markdown","source":"# Model","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"class Model(nn.Module):\n    def __init__(self, pre=True):\n        super().__init__()\n        \n        # Load model backbone\n        model = EfficientNet.from_name('efficientnet-b6')\n        \n        # Get preloaded model\n        if pre:\n            model.load_state_dict(torch.load('../input/efficientnet-pytorch/efficientnet-b6-c76e70fd.pth'))\n        \n        # Encoder, runs through the pretrained efficientnet\n        self.enc = model\n        \n        # Neural network head. After running through the neural network, this is the transfer\n        nc = list(model.children())[-1].in_features\n        self.head = nn.Sequential(AdaptiveConcatPool2d(),\n                                  Flatten(),\n                                  nn.Linear(2*nc,512), \n                                  Mish(),\n                                  nn.BatchNorm1d(512), \n                                  nn.Dropout(0.5),\n                                  nn.Linear(512,1))\n        \n        \n    def forward(self, x):\n        # Extract features\n        x = self.enc.extract_features(x)\n    \n        # Regression\n        x = self.head(x)\n        \n        return x","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Regression to Classification conversion using the OptimizedRounder","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# inspired by https://www.kaggle.com/tanlikesmath/intro-aptos-diabetic-retinopathy-eda-starter\nclass KappaOptimizer(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.coef = [0.5, 1.5, 2.5, 3.5, 4.5]\n        # define score function:\n        self.func = self.quad_kappa\n    \n    \n    def predict(self, preds):\n        return self._predict(self.coef, preds)\n\n    \n    @classmethod\n    def _predict(cls, coef, preds):\n        if type(preds).__name__ == 'Tensor':\n            y_hat = preds.clone().view(-1)\n        else:\n            y_hat = torch.FloatTensor(preds).view(-1)\n\n        for i,pred in enumerate(y_hat):\n            if   pred < coef[0]: y_hat[i] = 0\n            elif pred < coef[1]: y_hat[i] = 1\n            elif pred < coef[2]: y_hat[i] = 2\n            elif pred < coef[3]: y_hat[i] = 3\n            elif pred < coef[4]: y_hat[i] = 4\n            else:                y_hat[i] = 5\n        return y_hat.int()\n    \n    \n    def quad_kappa(self, preds, y):\n        return self._quad_kappa(self.coef, preds, y)\n\n    \n    @classmethod\n    def _quad_kappa(cls, coef, preds, y):\n        y_hat = cls._predict(coef, preds)\n        \n        if type(preds).__name__ == 'Tensor':\n            return cohen_kappa_score(y.cpu(), y_hat.cpu(), weights='quadratic')\n        else:\n            return cohen_kappa_score(y, y_hat, weights='quadratic')\n\n    \n    def fit(self, preds, y):\n        ''' maximize quad_kappa '''\n        neg_kappa = lambda coef: -self._quad_kappa(coef, preds, y)\n        opt_res = sp.optimize.minimize(neg_kappa, x0=self.coef, method='nelder-mead',\n                                       options={'maxiter':150, 'fatol':1e-10, 'xatol':1e-10})\n        self.coef = opt_res.x\n\n        \n    def forward(self, preds, y):\n        ''' the pytorch loss function '''\n        return torch.tensor(self.quad_kappa(preds, y))\n\nkappa_opt = KappaOptimizer()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# Prepare databunch\nfold =  0\ntrain_idx = df[df['split'] != fold].index\nval_idx = df[df['split'] == fold].index\n\ntrain_dataset = TrainDataset(df.loc[train_idx].reset_index(drop=True), \n                             df.loc[train_idx].reset_index(drop=True)[\"isup_grade\"], \n                             transform=get_transforms(data='train'))\nvalid_dataset = TrainDataset(df.loc[val_idx].reset_index(drop=True), \n                             df.loc[val_idx].reset_index(drop=True)[\"isup_grade\"], \n                             transform=get_transforms(data='valid'))\n\ntrain_loader = DataLoader(train_dataset, batch_size=bs, shuffle=True, num_workers=4)\nvalid_loader = DataLoader(valid_dataset, batch_size=bs, shuffle=False, num_workers=4)\n\n\ndata = DataBunch(train_dl = train_loader, valid_dl = valid_loader)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fname = 'EFFNETB0_REGRESSION'\nmodel = Model()\n\nlearn = Learner(data, \n                model, \n                loss_func=MSELossFlat(),\n                opt_func=Over9000, \n                metrics=[kappa_opt])\n\nlogger = CSVLogger(learn, f'log_{fname}_{fold}')\n\nlearn.clip_grad = 1.0\nlearn.split([model.head])\nlearn.unfreeze()\n\n# Fit for n_epochs cycles\nlearn.fit_one_cycle(n_epochs, \n                    max_lr=1e-3, \n                    div_factor=100, \n                    pct_start=0.0, \n                    callbacks = [SaveModelCallback(learn,\n                                                   name=f'model',\n                                                   mode='min',\n                                                   monitor='valid_loss')])\n\n# Save model\ntorch.save(learn.model.state_dict(), f'{fname}_{fold}.pth')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.recorder.plot_losses()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Evaluation","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"train_pred,train_target, pred, target = [],[],[],[]\nlearn.model.eval()\nwith torch.no_grad():\n    for step, (x, y) in progress_bar(enumerate(data.dl(DatasetType.Train)),total=len(data.dl(DatasetType.Train))):\n        p = learn.model(x)\n        p = p.float().cpu()\n        train_pred.append(p)\n        train_target.append(y.cpu())\n        \n    for step, (x, y) in progress_bar(enumerate(data.dl(DatasetType.Valid)),total=len(data.dl(DatasetType.Valid))):\n        p = learn.model(x)\n        p = p.float().cpu()\n        pred.append(p)\n        target.append(y.cpu())","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"p = torch.cat(pred)\nt = torch.cat(target)\np = kappa_opt.predict(p)\nprint(cohen_kappa_score(t,p,weights='quadratic'), \"\\n\")\nprint(confusion_matrix(t,p), \"\\n\")\nprint(kappa_opt.coef)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"p_train = torch.cat(train_pred)\nt_train = torch.cat(train_target)\nkappa_opt.fit(p_train,t_train)\n\np = kappa_opt.predict(p)\nprint(cohen_kappa_score(t,p,weights='quadratic'), \"\\n\")\nprint(confusion_matrix(t,p), \"\\n\")\nprint(kappa_opt.coef)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"!rm -r 'cache'","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}