{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        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","execution":{"iopub.status.busy":"2022-12-10T15:29:28.555254Z","iopub.execute_input":"2022-12-10T15:29:28.556166Z","iopub.status.idle":"2022-12-10T15:29:34.944048Z","shell.execute_reply.started":"2022-12-10T15:29:28.556062Z","shell.execute_reply":"2022-12-10T15:29:34.942432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport matplotlib.pyplot as plt\nfrom os.path import isfile\nimport torch.nn.init as init\nimport torch\nimport torch.nn as nn\nimport numpy as np\nimport pandas as pd \nimport os\nimport scipy as sp\nfrom PIL import Image, ImageFilter\nfrom sklearn.model_selection import train_test_split, StratifiedKFold\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\nfrom torch.optim import Adam, SGD, RMSprop\nimport time\nfrom torch.autograd import Variable\nimport torch.functional as F\nfrom tqdm import tqdm\nfrom sklearn import metrics\nimport urllib\nimport pickle\nimport torch.nn.functional as F\nfrom torchvision import models\nimport random\nimport sys\nfrom functools import partial\nfrom torch.utils.data import DataLoader\nfrom torch.autograd import Variable\n\nprint('Ready, set, go....')","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:34.947087Z","iopub.execute_input":"2022-12-10T15:29:34.947305Z","iopub.status.idle":"2022-12-10T15:29:37.199778Z","shell.execute_reply.started":"2022-12-10T15:29:34.947281Z","shell.execute_reply":"2022-12-10T15:29:37.199040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!git clone https://github.com/quangphammessi/kaggle_aptos","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:37.200968Z","iopub.execute_input":"2022-12-10T15:29:37.201217Z","iopub.status.idle":"2022-12-10T15:29:39.200382Z","shell.execute_reply.started":"2022-12-10T15:29:37.201188Z","shell.execute_reply":"2022-12-10T15:29:39.199522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# !git clone https://github.com/NVIDIA/apex","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:59.909834Z","iopub.execute_input":"2022-12-10T15:29:59.910302Z","iopub.status.idle":"2022-12-10T15:29:59.914720Z","shell.execute_reply.started":"2022-12-10T15:29:59.910268Z","shell.execute_reply":"2022-12-10T15:29:59.913668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cd apex","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:30:07.177451Z","iopub.execute_input":"2022-12-10T15:30:07.177998Z","iopub.status.idle":"2022-12-10T15:30:07.185507Z","shell.execute_reply.started":"2022-12-10T15:30:07.177940Z","shell.execute_reply":"2022-12-10T15:30:07.184578Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# NVIDIA_apex_path = './repository/NVIDIA-apex-39e153a'\nWARMUP_LR = './pytorch-gradual-warmup-lr/'\n# sys.path.append(NVIDIA_apex_path)\nsys.path.append(WARMUP_LR)\nsys.path.append('/kaggle/input/efficient-net/EfficientNet-PyTorch/EfficientNet-PyTorch-master')\nfrom efficientnet_pytorch import EfficientNet\nfrom apex import amp","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:30:07.877201Z","iopub.execute_input":"2022-12-10T15:30:07.877508Z","iopub.status.idle":"2022-12-10T15:30:07.897244Z","shell.execute_reply.started":"2022-12-10T15:30:07.877479Z","shell.execute_reply":"2022-12-10T15:30:07.895838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.393590Z","iopub.status.idle":"2022-12-10T15:29:39.393934Z","shell.execute_reply.started":"2022-12-10T15:29:39.393757Z","shell.execute_reply":"2022-12-10T15:29:39.393773Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"n_epochs    = 30\nnum_classes = 1\nseed_everything(1234)\nlr          = 1e-3\nIMG_SIZE    = 380\ncoef = [0.5, 1.5, 2.5, 3.5]","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.395218Z","iopub.status.idle":"2022-12-10T15:29:39.395556Z","shell.execute_reply.started":"2022-12-10T15:29:39.395387Z","shell.execute_reply":"2022-12-10T15:29:39.395403Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv = pd.read_csv('/kaggle/input/aptos2019-blindness-detection/train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.397014Z","iopub.status.idle":"2022-12-10T15:29:39.397353Z","shell.execute_reply.started":"2022-12-10T15:29:39.397171Z","shell.execute_reply":"2022-12-10T15:29:39.397187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv.head()","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.398663Z","iopub.status.idle":"2022-12-10T15:29:39.399427Z","shell.execute_reply.started":"2022-12-10T15:29:39.399094Z","shell.execute_reply":"2022-12-10T15:29:39.399126Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv.shape","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.400890Z","iopub.status.idle":"2022-12-10T15:29:39.401393Z","shell.execute_reply.started":"2022-12-10T15:29:39.401108Z","shell.execute_reply":"2022-12-10T15:29:39.401132Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_df, val_df = train_test_split(train_csv, test_size = 0.1, random_state = 42, stratify=train_csv.diagnosis)\ntrain_df.reset_index(drop=True, inplace=True)\nval_df.reset_index(drop=True, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.402731Z","iopub.status.idle":"2022-12-10T15:29:39.403116Z","shell.execute_reply.started":"2022-12-10T15:29:39.402922Z","shell.execute_reply":"2022-12-10T15:29:39.402941Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = '/kaggle/input/aptos2019-blindness-detection/train_images/'","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.404328Z","iopub.status.idle":"2022-12-10T15:29:39.404728Z","shell.execute_reply.started":"2022-12-10T15:29:39.404531Z","shell.execute_reply":"2022-12-10T15:29:39.404549Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def expand_path(p):\n    p = str(p)\n    if isfile(train + p + \".png\"):\n        return train + (p + \".png\")\n    return p\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.406305Z","iopub.status.idle":"2022-12-10T15:29:39.406941Z","shell.execute_reply.started":"2022-12-10T15:29:39.406672Z","shell.execute_reply":"2022-12-10T15:29:39.406699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def p_show(imgs, label_name=None, per_row=3):\n    n = len(imgs)\n    rows = (n + per_row - 1)//per_row\n    cols = min(per_row, n)\n    fig, axes = plt.subplots(rows,cols, figsize=(15,15))\n    for ax in axes.flatten(): ax.axis('off')\n    for i,(p, ax) in enumerate(zip(imgs, axes.flatten())): \n        img = Image.open(expand_path(p))\n        ax.imshow(img)\n        ax.set_title(train_df[train_df.id_code == p].diagnosis.values)\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.408660Z","iopub.status.idle":"2022-12-10T15:29:39.409136Z","shell.execute_reply.started":"2022-12-10T15:29:39.408876Z","shell.execute_reply":"2022-12-10T15:29:39.408899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"p_show(['/kaggle/input/aptos2019-blindness-detection/train_images/00cc2b75cddd.png',\n        '/kaggle/input/aptos2019-blindness-detection/train_images/00cb6555d108.png',\n        '/kaggle/input/aptos2019-blindness-detection/train_images/0151781fe50b.png'])","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.410229Z","iopub.status.idle":"2022-12-10T15:29:39.410715Z","shell.execute_reply.started":"2022-12-10T15:29:39.410464Z","shell.execute_reply":"2022-12-10T15:29:39.410489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def crop_image1(img,tol=7):\n    # img is image data\n    # tol  is tolerance\n        \n    mask = img>tol\n    return img[np.ix_(mask.any(1),mask.any(0))]\n\ndef crop_image_from_gray(img,tol=7):\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        \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([img1,img2,img3],axis=-1)\n#             print(img.shape)\n        return img","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.413830Z","iopub.status.idle":"2022-12-10T15:29:39.415352Z","shell.execute_reply.started":"2022-12-10T15:29:39.415033Z","shell.execute_reply":"2022-12-10T15:29:39.415061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a = np.array([[1,2,10,10,10,10,7,8,1,2],[1,2,13,14,15,16,17,18,1,2]])\na","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.416873Z","iopub.status.idle":"2022-12-10T15:29:39.417733Z","shell.execute_reply.started":"2022-12-10T15:29:39.417453Z","shell.execute_reply":"2022-12-10T15:29:39.417481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"x = a>7","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.419157Z","iopub.status.idle":"2022-12-10T15:29:39.419887Z","shell.execute_reply.started":"2022-12-10T15:29:39.419584Z","shell.execute_reply":"2022-12-10T15:29:39.419636Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"a[np.ix_(x.any(1),x.any(0))]","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.421380Z","iopub.status.idle":"2022-12-10T15:29:39.422432Z","shell.execute_reply.started":"2022-12-10T15:29:39.422140Z","shell.execute_reply":"2022-12-10T15:29:39.422167Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_network(args):\n\n    if args.net == 'vgg16':\n        from models.vgg import vgg16\n        net = vgg16()\n\n    elif args.net == 'vgg11':\n        from models.vgg import vgg11\n        net = vgg11()\n    \n    elif args.net == 'vgg13':\n        from models.vgg import vgg13\n        net = vgg13()\n    \n    elif args.net == 'vgg19':\n        from models.vgg import vgg19\n        net = vgg19()\n\n    return net","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.423962Z","iopub.status.idle":"2022-12-10T15:29:39.424622Z","shell.execute_reply.started":"2022-12-10T15:29:39.424359Z","shell.execute_reply":"2022-12-10T15:29:39.424385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class MyDataset(Dataset):\n    \n    def __init__(self, dataframe, transform=None):\n        self.df = dataframe\n        self.transform = transform\n    \n    def __len__(self):\n        return len(self.df)\n    \n    def __getitem__(self, idx):\n        \n        label = self.df.diagnosis.values[idx]\n        label = np.expand_dims(label, -1)\n        \n        p = self.df.id_code.values[idx]\n        p_path = expand_path(p)\n        image = cv2.imread(p_path)\n        image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n        image = crop_image_from_gray(image)\n        image = cv2.resize(image, (IMG_SIZE, IMG_SIZE))\n        image = cv2.addWeighted ( image,4, cv2.GaussianBlur( image , (0,0) , 30) ,-4 ,128)\n        image = transforms.ToPILImage()(image)\n        \n        if self.transform:\n            image = self.transform(image)\n        \n        return image, label\n\n\n# Data Transformation\ntrain_transform = transforms.Compose([\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomVerticalFlip(),\n    transforms.RandomAffine(degrees=360, scale=(1.05, 1.25)),\n    transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1),\n    transforms.RandomRotation((-120, 120)),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\ntest_transform = transforms.Compose([\n    transforms.RandomHorizontalFlip(),\n    transforms.RandomAffine(degrees=360, scale=(1.05, 1.25)),\n    transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1),\n    transforms.RandomRotation((-120, 120)),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])\n\n\ntrainset     = MyDataset(train_df, transform =train_transform)\ntrain_loader = torch.utils.data.DataLoader(trainset, batch_size=8, shuffle=True, num_workers=4)\nvalset       = MyDataset(val_df, transform  =test_transform)\nval_loader   = torch.utils.data.DataLoader(valset, batch_size=8, shuffle=False, num_workers=4)\n\n\n# Model Architecture\nmodel = EfficientNet.from_name('efficientnet-b4')\nmodel.load_state_dict(torch.load('/kaggle/input/pretrainedefficientnetb4/adv-efficientnet-b4-44fb3a87.pth'))\n\n# # Freeze model weights to warmup learning rate\n# for param in model.parameters():\n#     param.requires_grad = False\n\nin_features = model._fc.in_features\nmodel._fc = nn.Linear(in_features, num_classes)\nmodel.cuda()\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.426769Z","iopub.status.idle":"2022-12-10T15:29:39.427747Z","shell.execute_reply.started":"2022-12-10T15:29:39.427384Z","shell.execute_reply":"2022-12-10T15:29:39.427412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Class weight\nfrom sklearn.utils import class_weight\nclass_weight_ = class_weight.compute_class_weight(\n                                                 class_weight = 'balanced',\n                                                 classes = np.unique(train_df['diagnosis']),\n                                                 y = train_df['diagnosis']\n                                                 )\nclass_weight_ = torch.from_numpy(class_weight_)\n\n\nfrom sklearn.metrics import cohen_kappa_score\ndef quadratic_kappa(y_hat, y):\n    return torch.tensor(cohen_kappa_score(y_hat, y, weights='quadratic')).cuda()\n    # return torch.tensor(cohen_kappa_score(torch.round(y_hat), y, weights='quadratic'),device='cuda:0')","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.429023Z","iopub.status.idle":"2022-12-10T15:29:39.429684Z","shell.execute_reply.started":"2022-12-10T15:29:39.429426Z","shell.execute_reply":"2022-12-10T15:29:39.429451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_label(output_test):\n    label = 0\n    if output_test < coef[0]:\n        label = 0\n    elif output_test >= coef[0] and output_test < coef[1]:\n        label = 1\n    elif output_test >= coef[1] and output_test < coef[2]:\n        label = 2\n    elif output_test >= coef[2] and output_test < coef[3]:\n        label = 3\n    else:\n        label = 4\n\n    return label\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.430893Z","iopub.status.idle":"2022-12-10T15:29:39.431548Z","shell.execute_reply.started":"2022-12-10T15:29:39.431268Z","shell.execute_reply":"2022-12-10T15:29:39.431293Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Optimizer for Kappa score\nclass OptimizedRounder(object):\n    def __init__(self):\n        self.coef_ = 0\n\n    def _kappa_loss(self, coef, X, y):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            X_p[i] = get_label(pred)\n\n        ll = cohen_kappa_score(y, X_p, weights='quadratic')\n        return -ll\n\n    def fit(self, X, y):\n        loss_partial = partial(self._kappa_loss, X=X, y=y)\n        initial_coef = [0.5, 1.5, 2.5, 3.5]\n        self.coef_ = sp.optimize.minimize(loss_partial, initial_coef, method='nelder-mead')\n\n    def predict(self, X, coef):\n        X_p = np.copy(X)\n        for i, pred in enumerate(X_p):\n            X_p[i] = get_label(pred)\n\n        return X_p\n\n    def coefficients(self):\n        return self.coef_['x']\n\n\nclass LogCoshLoss(torch.nn.Module):\n    def __init__(self):\n        super().__init__()\n\n    def forward(self, y_t, y_prime_t):\n        ey_t = y_t - y_prime_t\n        return torch.mean(torch.log(torch.cosh(ey_t + 1e-12)))\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.432824Z","iopub.status.idle":"2022-12-10T15:29:39.433493Z","shell.execute_reply.started":"2022-12-10T15:29:39.433212Z","shell.execute_reply":"2022-12-10T15:29:39.433237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training Config\n\n# Apply no bias decay\n# params = split_weights(model)\noptimizer = torch.optim.Adam(model.parameters(), lr=lr, weight_decay=1e-5)\n\n# criterion = LogCoshLoss()\ncriterion = nn.MSELoss() \nscheduler_step = torch.optim.lr_scheduler.StepLR(optimizer, step_size=5, gamma=0.1)\n# scheduler_warmup = GradualWarmupScheduler(optimizer, multiplier=10, total_epoch=5, after_scheduler=scheduler_step)\nmodel, optimizer = amp.initialize(model, optimizer, opt_level=\"O1\",verbosity=0)\n","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.434735Z","iopub.status.idle":"2022-12-10T15:29:39.435401Z","shell.execute_reply.started":"2022-12-10T15:29:39.435110Z","shell.execute_reply":"2022-12-10T15:29:39.435136Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training\ndef train_model(epoch):\n    model.train()\n        \n    avg_loss = 0.\n    optimizer.zero_grad()\n    for idx, (imgs, labels) in enumerate(train_loader):\n        imgs_train, labels_train = imgs.cuda(), labels.float().cuda()\n        output_train = model(imgs_train)\n        loss = criterion(output_train,labels_train)\n        with amp.scale_loss(loss, optimizer) as scaled_loss:\n            scaled_loss.backward()\n        optimizer.step()\n        optimizer.zero_grad()\n        avg_loss += loss.item() / len(train_loader)\n        \n    return avg_loss\n\ndef test_model():\n    correct = 0\n    total = 0\n    preds = []\n    truth_labels = []\n    \n    avg_val_loss = 0.\n    model.eval()\n    with torch.no_grad():\n        for idx, (imgs, labels) in enumerate(val_loader):\n            imgs_vaild, labels_vaild = imgs.cuda(), labels.float().cuda()\n            output_test = model(imgs_vaild)\n            avg_val_loss += criterion(output_test, labels_vaild).item() / len(val_loader)\n\n            for i in range(len(output_test)):\n                pred_label = get_label(output_test[i][0])\n                correct += (int(pred_label) == int(labels[i][0]))\n                total += 1\n\n                preds.append(int(pred_label))\n                truth_labels.append(int(labels[i][0]))\n            \n    preds = np.array(preds)\n    truth_labels = np.array(truth_labels)\n\n    kappa_score = quadratic_kappa(preds, truth_labels)\n    val_acc = correct * 100.0 / total\n        \n    return avg_val_loss, val_acc, kappa_score\n\n\nbest_avg_loss = 100.0\nbest_val_acc = 0.0\nbest_kappa_score = -100.0\n\nprint('transforms.RandomAffine(degrees=360, translate=(0.05, 0.05), scale=(1, 1.3)), \\\n    transforms.ColorJitter(brightness=0.5, contrast=0.5, saturation=0.5, hue=0.1), \\\n    transforms.RandomRotation((-120, 120))')\nprint('Model: 20190905_data3k_effib4_aug_adjust_clean_testzoom.pt')\n\nprint()\n\n\nprint('Start Training!')\nprint('-' * 10)\nfor epoch in range(n_epochs):\n    \n    print('Epoch {}/{}:' .format(epoch + 1, n_epochs))\n    print('lr:', scheduler_step.get_lr()[0]) \n    start_time   = time.time()\n    avg_loss     = train_model(epoch)\n    avg_val_loss, val_acc, kappa_score = test_model()\n    elapsed_time = time.time() - start_time \n    # print('Epoch {}/{} \\t loss={:.4f} \\t val_loss={:.4f} \\t val_acc={:.4f}% \\t time={:.2f}s'.format(\n    #     epoch + 1, n_epochs, avg_loss, avg_val_loss, val_acc, elapsed_time))\n    \n    print('Train: loss={:.4f}  \\t  Valid: val_loss={:.4f}  \\t  val_acc={:.4f}  \\t  val_kappa={:4f}  \\t  Time={:.2f}' .format(avg_loss, avg_val_loss, val_acc, kappa_score, elapsed_time))\n    print()\n\n    if avg_val_loss < best_avg_loss:\n        best_avg_loss = avg_val_loss\n        torch.save(model.state_dict(), '/kaggle/working/20190905_data3k_effib4_aug_adjust_clean_testzoom.pt')\n        print('Better val_loss. Model saved!')\n\n    # if val_acc > best_val_acc:\n    #     best_val_acc = val_acc\n    #     torch.save(model.state_dict(), './saved_model/20190816_2_data3k_effib4.pt')\n    #     print('Better val_accuracy. Model saved!')\n\n    # if kappa_score > best_kappa_score:\n    #     best_kappa_score = kappa_score\n    #     torch.save(model.state_dict(), './saved_model/20190829_data3k_effib4_aug_huber.pt')\n    #     print('Better kappa_score. Model saved!')\n    \n    scheduler_step.step()\n    print('-' * 10)\n\nprint('Finish Training!')","metadata":{"execution":{"iopub.status.busy":"2022-12-10T15:29:39.436707Z","iopub.status.idle":"2022-12-10T15:29:39.437383Z","shell.execute_reply.started":"2022-12-10T15:29:39.437083Z","shell.execute_reply":"2022-12-10T15:29:39.437120Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}