{"cells":[{"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","trusted":true},"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 in \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 \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"%reload_ext autoreload\n%autoreload 2\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai import *\nfrom fastai.vision import *\nimport pandas as pd\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"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\nSEED = 999\nseed_everything(SEED)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Make sure cuda is installed:', torch.cuda.is_available())\nprint('Make sure cudnn is enabled:', torch.backends.cudnn.enabled)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import cohen_kappa_score\ndef quadratic_kappa(y_hat, y):\n    return torch.tensor(cohen_kappa_score(y_hat.argmax(dim=-1), y, weights='quadratic'),device='cuda:0')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bs = 64 #smaller batch size is better for training, but may take longer\nsz=256","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_image_dir = os.path.join('..', 'input/aptos2019-blindness-detection/')\ntrain_dir = os.path.join(base_image_dir,'train_images/')\ndf = pd.read_csv(os.path.join(base_image_dir, 'train.csv'))\ndf['path'] = df['id_code'].map(lambda x: os.path.join(train_dir,'{}.png'.format(x)))\ndf = df.drop(columns=['id_code'])\ndf = df.sample(frac=1).reset_index(drop=True) #shuffle dataframe\ndf.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\ndef open_aptos2019_image(fn, convert_mode, after_open,tol=7)->Image:\n    img = cv2.imread(fn)\n    if img.ndim ==2:\n        mask = img>tol\n        return img[np.ix_(mask.any(1),mask.any(0))]\n    elif img.ndim==3:\n        gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)\n        mask = gray_img>tol\n        check_shape = img[:,:,0][np.ix_(mask.any(1),mask.any(0))].shape[0]\n        if (check_shape == 0): # image is too dark so that we crop out everything,\n            return img # return original image\n        else:\n            img1=img[:,:,0][np.ix_(mask.any(1),mask.any(0))]\n            img2=img[:,:,1][np.ix_(mask.any(1),mask.any(0))]\n            img3=img[:,:,2][np.ix_(mask.any(1),mask.any(0))]\n    #         print(img1.shape,img2.shape,img3.shape)\n            img = np.stack([img3,img2,img1],axis=-1)\n    #         print(img.shape)\n        return Image(pil2tensor(img, np.float32).div_(255))\n    \n\n    \n\nvision.data.open_image = open_aptos2019_image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import KFold\nn_fold = 5\nseed = 42\nfolds = KFold(n_splits=n_fold, shuffle=True, random_state=seed)   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import itertools as it\n\n\n\nclass Ranger(torch.optim.Optimizer):\n\n    def __init__(self, params, lr=1e-3, alpha=0.5, k=6, N_sma_threshhold=5, betas=(.95,0.999), eps=1e-5, weight_decay=0):\n        #parameter checks\n        if not 0.0 <= alpha <= 1.0:\n            raise ValueError(f'Invalid slow update rate: {alpha}')\n        if not 1 <= k:\n            raise ValueError(f'Invalid lookahead steps: {k}')\n        if not lr > 0:\n            raise ValueError(f'Invalid Learning Rate: {lr}')\n        if not eps > 0:\n            raise ValueError(f'Invalid eps: {eps}')\n\n        #parameter comments:\n        # beta1 (momentum) of .95 seems to work better than .90...\n        #N_sma_threshold of 5 seems better in testing than 4.\n        #In both cases, worth testing on your dataset (.90 vs .95, 4 vs 5) to make sure which works best for you.\n\n        #prep defaults and init torch.optim base\n        defaults = dict(lr=lr, alpha=alpha, k=k, step_counter=0, betas=betas, N_sma_threshhold=N_sma_threshhold, eps=eps, weight_decay=weight_decay)\n        super().__init__(params,defaults)\n\n        #adjustable threshold\n        self.N_sma_threshhold = N_sma_threshhold\n\n        #now we can get to work...\n        #removed as we now use step from RAdam...no need for duplicate step counting\n        #for group in self.param_groups:\n        #    group[\"step_counter\"] = 0\n            #print(\"group step counter init\")\n\n        #look ahead params\n        self.alpha = alpha\n        self.k = k \n\n        #radam buffer for state\n        self.radam_buffer = [[None,None,None] for ind in range(10)]\n\n        #self.first_run_check=0\n\n        #lookahead weights\n        #9/2/19 - lookahead param tensors have been moved to state storage.  \n        #This should resolve issues with load/save where weights were left in GPU memory from first load, slowing down future runs.\n\n        #self.slow_weights = [[p.clone().detach() for p in group['params']]\n        #                     for group in self.param_groups]\n\n        #don't use grad for lookahead weights\n        #for w in it.chain(*self.slow_weights):\n        #    w.requires_grad = False\n\n    def __setstate__(self, state):\n        print(\"set state called\")\n        super(Ranger, self).__setstate__(state)\n\n\n    def step(self, closure=None):\n        loss = None\n        #note - below is commented out b/c I have other work that passes back the loss as a float, and thus not a callable closure.  \n        #Uncomment if you need to use the actual closure...\n\n        #if closure is not None:\n            #loss = closure()\n\n        #Evaluate averages and grad, update param tensors\n        for group in self.param_groups:\n\n            for p in group['params']:\n                if p.grad is None:\n                    continue\n                grad = p.grad.data.float()\n                if grad.is_sparse:\n                    raise RuntimeError('Ranger optimizer does not support sparse gradients')\n\n                p_data_fp32 = p.data.float()\n\n                state = self.state[p]  #get state dict for this param\n\n                if len(state) == 0:   #if first time to run...init dictionary with our desired entries\n                    #if self.first_run_check==0:\n                        #self.first_run_check=1\n                        #print(\"Initializing slow buffer...should not see this at load from saved model!\")\n                    state['step'] = 0\n                    state['exp_avg'] = torch.zeros_like(p_data_fp32)\n                    state['exp_avg_sq'] = torch.zeros_like(p_data_fp32)\n\n                    #look ahead weight storage now in state dict \n                    state['slow_buffer'] = torch.empty_like(p.data)\n                    state['slow_buffer'].copy_(p.data)\n\n                else:\n                    state['exp_avg'] = state['exp_avg'].type_as(p_data_fp32)\n                    state['exp_avg_sq'] = state['exp_avg_sq'].type_as(p_data_fp32)\n\n                #begin computations \n                exp_avg, exp_avg_sq = state['exp_avg'], state['exp_avg_sq']\n                beta1, beta2 = group['betas']\n\n                #compute variance mov avg\n                exp_avg_sq.mul_(beta2).addcmul_(1 - beta2, grad, grad)\n                #compute mean moving avg\n                exp_avg.mul_(beta1).add_(1 - beta1, grad)\n\n                state['step'] += 1\n\n\n                buffered = self.radam_buffer[int(state['step'] % 10)]\n                if state['step'] == buffered[0]:\n                    N_sma, step_size = buffered[1], buffered[2]\n                else:\n                    buffered[0] = state['step']\n                    beta2_t = beta2 ** state['step']\n                    N_sma_max = 2 / (1 - beta2) - 1\n                    N_sma = N_sma_max - 2 * state['step'] * beta2_t / (1 - beta2_t)\n                    buffered[1] = N_sma\n                    if N_sma > self.N_sma_threshhold:\n                        step_size = math.sqrt((1 - beta2_t) * (N_sma - 4) / (N_sma_max - 4) * (N_sma - 2) / N_sma * N_sma_max / (N_sma_max - 2)) / (1 - beta1 ** state['step'])\n                    else:\n                        step_size = 1.0 / (1 - beta1 ** state['step'])\n                    buffered[2] = step_size\n\n                if group['weight_decay'] != 0:\n                    p_data_fp32.add_(-group['weight_decay'] * group['lr'], p_data_fp32)\n\n                if N_sma > self.N_sma_threshhold:\n                    denom = exp_avg_sq.sqrt().add_(group['eps'])\n                    p_data_fp32.addcdiv_(-step_size * group['lr'], exp_avg, denom)\n                else:\n                    p_data_fp32.add_(-step_size * group['lr'], exp_avg)\n\n                p.data.copy_(p_data_fp32)\n\n                #integrated look ahead...\n                #we do it at the param level instead of group level\n                if state['step'] % group['k'] == 0:\n                    slow_p = state['slow_buffer'] #get access to slow param tensor\n                    slow_p.add_(self.alpha, p.data - slow_p)  #(fast weights - slow weights) * alpha\n                    p.data.copy_(slow_p)  #copy interpolated weights to RAdam param tensor\n\n        return loss","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"opt_func = partial(Ranger, betas=(0.95, 0.999),eps=1e-5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for fold_, (trn_idx, val_idx) in enumerate(folds.split(df['path'],df['diagnosis'])):\n    if fold_ != 1:\n        continue\n    tfms = get_transforms(do_flip=True,flip_vert=True,max_rotate=360,max_warp=0,max_zoom=1.1,max_lighting=0.1,p_lighting=0.5)\n    src = (ImageList.from_df(df=df,path='./',cols='path') #get dataset from dataset\n        .split_by_idx(val_idx) #Splitting the dataset\n        .label_from_df(cols='diagnosis') #obtain labels from the level column\n      )\n    data= (src.transform(tfms,size=sz,resize_method=ResizeMethod.SQUISH,padding_mode='zeros') #Data augmentation\n        .databunch(bs=bs,num_workers=4) #DataBunch\n        .normalize(imagenet_stats) #Normalize     \n       )\n    from fastai.callbacks import *\n    learn = cnn_learner(data, base_arch=models.resnet50, opt_func = opt_func, wd=1e-2, metrics = [quadratic_kappa],pretrained=False,callback_fns=[partial(SaveModelCallback, every='improvement',monitor='valid_loss')])\n    prev_dir = learn.model_dir\n    learn.model_dir = Path('.')\n    learn.load('../input/dr-resnet50-model/stage-2-512')\n    learn.model_dir = prev_dir\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#learn.unfreeze()\nlearn.lr_find()\nlearn.recorder.plot(suggestion=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from fastai.callbacks import *\nfrom fastai.train import *\ndef flattenAnneal(learn:Learner, lr:float, n_epochs:int, start_pct:float):\n    lr = learn.lr_range(lr)\n    n = len(learn.data.train_dl)\n    anneal_start = int(n*n_epochs*start_pct)\n    anneal_end = int(n*n_epochs) - anneal_start\n    phases = [TrainingPhase(anneal_start).schedule_hp('lr', lr),\n           TrainingPhase(anneal_end).schedule_hp('lr', lr, anneal=annealing_cos)]\n    sched = GeneralScheduler(learn, phases)\n    learn.callbacks.append(sched)\n    learn.fit(n_epochs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"flattenAnneal(learn,slice(1e-2),30,0.15)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.export('APTOS-previous-1')\nvalidate = learn.validate()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(validate[1].cpu().numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"learn.recorder.plot_losses()\nlearn.recorder.plot_metrics()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.6.6"}},"nbformat":4,"nbformat_minor":1}