{"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":"markdown","source":"This is training notebook for a vanilla approach to the problem: take raw images and run them through a simple network. \nThe inference can be found here: https://www.kaggle.com/konradb/umnist-model-infer\n\n\nPotential improvements:\n- proper k-fold\n- more fancy model architecture ;-)","metadata":{}},{"cell_type":"code","source":"!pip install tez\n!pip install timm","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:07.317868Z","iopub.execute_input":"2022-03-21T13:39:07.320597Z","iopub.status.idle":"2022-03-21T13:39:25.515571Z","shell.execute_reply.started":"2022-03-21T13:39:07.320476Z","shell.execute_reply":"2022-03-21T13:39:25.514783Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport albumentations as A\nimport pandas as pd\nimport numpy as np\n\n\nimport tez\nfrom tez.datasets import ImageDataset\nfrom tez.callbacks import EarlyStopping\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\n\nfrom sklearn import metrics, model_selection, preprocessing\nimport timm\n\nfrom sklearn.model_selection import KFold\n\n# ignoring warnings\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nimport os, cv2, json\nfrom PIL import Image\n\nimport random","metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_kg_hide-input":true,"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","papermill":{"duration":5.732608,"end_time":"2021-12-20T22:53:39.01515","exception":false,"start_time":"2021-12-20T22:53:33.282542","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-03-21T13:39:25.517561Z","iopub.execute_input":"2022-03-21T13:39:25.517781Z","iopub.status.idle":"2022-03-21T13:39:30.357792Z","shell.execute_reply.started":"2022-03-21T13:39:25.517753Z","shell.execute_reply":"2022-03-21T13:39:30.356968Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG:    \n    # config\n    work_dir = '../input/ultra-mnist/'\n    img_folder = '../input/ultramnist-resized-512/'\n    batch_size = 16\n    epochs = 5\n    img_size = 512\n    seed = 42\n    target_size = 28\n    model = 'efficientnet_b1'\n    lr = 0.002\n    patience = 4 \n    nfolds = 5","metadata":{"papermill":{"duration":0.026232,"end_time":"2021-12-20T22:53:39.0593","exception":false,"start_time":"2021-12-20T22:53:39.033068","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-03-21T13:39:30.359468Z","iopub.execute_input":"2022-03-21T13:39:30.35971Z","iopub.status.idle":"2022-03-21T13:39:30.364624Z","shell.execute_reply.started":"2022-03-21T13:39:30.359673Z","shell.execute_reply":"2022-03-21T13:39:30.363981Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed: int = 42) -> None:\n    random.seed(seed)\n    np.random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    \nseed_everything(CFG.seed)","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:30.366798Z","iopub.execute_input":"2022-03-21T13:39:30.367172Z","iopub.status.idle":"2022-03-21T13:39:30.376431Z","shell.execute_reply.started":"2022-03-21T13:39:30.367139Z","shell.execute_reply":"2022-03-21T13:39:30.37572Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Functions","metadata":{"papermill":{"duration":0.016944,"end_time":"2021-12-20T22:53:39.093163","exception":false,"start_time":"2021-12-20T22:53:39.076219","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class UModel(tez.Model):\n    def __init__(self, model_name, num_classes, learning_rate, n_train_steps\n#                 , warmup_ratio\n                ):\n        super().__init__()\n\n        self.learning_rate = learning_rate\n        self.n_train_steps = n_train_steps\n#        self.warmup_ratio = warmup_ratio\n        self.model = timm.create_model(model_name, pretrained=True, in_chans=3, num_classes=num_classes)\n        self.step_scheduler_after = \"batch\"\n    \n    def monitor_metrics(self, outputs, targets):\n        if targets is None:\n            return {}\n        outputs = torch.argmax(outputs, dim=1).cpu().detach().numpy()\n        targets = targets.cpu().detach().numpy()\n        accuracy = metrics.accuracy_score(targets, outputs)\n        return {\"accuracy\": accuracy}\n    \n    \n    def fetch_optimizer(self):\n        opt = torch.optim.Adam(self.parameters(), lr=3e-4)\n        return opt\n    \n    def fetch_scheduler(self):\n        sch = torch.optim.lr_scheduler.CosineAnnealingWarmRestarts(\n            self.optimizer, T_0=10, T_mult=1, eta_min=1e-6, last_epoch=-1\n        )\n        return sch\n\n    def forward(self, image, targets=None):\n        x = self.model(image)\n        if targets is not None:\n            loss = nn.CrossEntropyLoss()(x, targets)\n            metrics = self.monitor_metrics(x, targets)\n            return x, loss, metrics\n        return x, 0, {}","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:30.377541Z","iopub.execute_input":"2022-03-21T13:39:30.377947Z","iopub.status.idle":"2022-03-21T13:39:30.389236Z","shell.execute_reply.started":"2022-03-21T13:39:30.377914Z","shell.execute_reply":"2022-03-21T13:39:30.388558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"aug = A.Compose([\n            A.Normalize(\n                mean=[0.5, 0.5, 0.5],\n                std=[0.5, 0.5, 0.5],\n                max_pixel_value=255.0, \n                p=1.0\n            ) ], p=1.)","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:30.39033Z","iopub.execute_input":"2022-03-21T13:39:30.390722Z","iopub.status.idle":"2022-03-21T13:39:30.400234Z","shell.execute_reply.started":"2022-03-21T13:39:30.390688Z","shell.execute_reply":"2022-03-21T13:39:30.399581Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data\n","metadata":{"papermill":{"duration":0.017345,"end_time":"2021-12-20T22:53:39.269462","exception":false,"start_time":"2021-12-20T22:53:39.252117","status":"completed"},"tags":[]}},{"cell_type":"code","source":"dfx = pd.read_csv(CFG.work_dir + \"train.csv\")\ndfx.rename(columns={\"id\": \"image_id\", \"digit_sum\": \"label\"}, inplace = True)   \ndfx['image_id'] = dfx['image_id'] + '.jpeg'\n\n\n# split into folds\nkf = KFold(n_splits = 5, random_state = 42, shuffle = True)\nfold_id = np.zeros((len(dfx),1))\n\nfor (ii, (train_index, test_index)) in enumerate(kf.split(dfx)):\n    fold_id[test_index] = ii\n    \ndfx['fold'] = fold_id.astype(int)\n\n\ndfx.head()\n","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:30.401464Z","iopub.execute_input":"2022-03-21T13:39:30.401862Z","iopub.status.idle":"2022-03-21T13:39:30.465991Z","shell.execute_reply.started":"2022-03-21T13:39:30.401826Z","shell.execute_reply":"2022-03-21T13:39:30.465238Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"for fold in range(0,CFG.nfolds):\n    \n    # split\n    trn_idx = dfx[dfx['fold'] != fold].index\n    val_idx = dfx[dfx['fold'] == fold].index\n    df_train = dfx.loc[trn_idx].reset_index(drop=True)\n    df_valid = dfx.loc[val_idx].reset_index(drop=True)\n    image_path = CFG.img_folder + 'train_img/'\n    train_image_paths = [os.path.join(image_path, x) for x in df_train.image_id.values]\n    valid_image_paths = [os.path.join(image_path, x) for x in df_valid.image_id.values]\n    train_targets = df_train.label.values\n    valid_targets = df_valid.label.values\n\n    # prepare datasets\n    train_dataset = ImageDataset(\n        image_paths=train_image_paths, targets=train_targets, \n        augmentations=aug)\n\n    valid_dataset = ImageDataset(\n        image_paths=valid_image_paths, targets=valid_targets,\n        augmentations=aug)\n    \n    n_train_steps = int(len(train_image_paths) / CFG.batch_size * CFG.epochs)\n    # fit model for this fold\n    model = UModel(model_name = CFG.model, num_classes = CFG.target_size,\n                  learning_rate = CFG.lr, n_train_steps = n_train_steps) \n    es = EarlyStopping(\n      monitor=\"valid_loss\", model_path = str(CFG.model) + 'model_es_s' + str(CFG.img_size) + '_f' +str(fold) + '.bin', \n          patience = CFG.patience, mode=\"min\")\n\n          \n    model.fit(\n      train_dataset,\n      valid_dataset=valid_dataset,\n      train_bs= CFG.batch_size,\n      valid_bs = 16,\n      device=\"cuda\",\n      epochs = CFG.epochs ,\n      callbacks=[es],\n      fp16=True,\n      )\n    model.save(str(CFG.model) + 'model_s' + str(CFG.img_size) + '_f' +str(fold) + '.bin')\n    ","metadata":{"execution":{"iopub.status.busy":"2022-03-21T13:39:30.467288Z","iopub.execute_input":"2022-03-21T13:39:30.467536Z","iopub.status.idle":"2022-03-21T17:09:12.782147Z","shell.execute_reply.started":"2022-03-21T13:39:30.467501Z","shell.execute_reply":"2022-03-21T17:09:12.781337Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"str(CFG.model) + 'model_s' + str(CFG.img_size) + '_f' +str(fold) + '.bin'","metadata":{"execution":{"iopub.status.busy":"2022-03-21T17:09:12.783723Z","iopub.execute_input":"2022-03-21T17:09:12.784092Z","iopub.status.idle":"2022-03-21T17:09:12.790478Z","shell.execute_reply.started":"2022-03-21T17:09:12.784049Z","shell.execute_reply":"2022-03-21T17:09:12.789796Z"},"trusted":true},"execution_count":null,"outputs":[]}]}