{"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":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-03-30T07:34:33.815828Z","iopub.execute_input":"2022-03-30T07:34:33.81617Z","iopub.status.idle":"2022-03-30T07:37:07.918815Z","shell.execute_reply.started":"2022-03-30T07:34:33.816084Z","shell.execute_reply":"2022-03-30T07:37:07.918052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install tez==0.2.0","metadata":{"execution":{"iopub.status.busy":"2022-04-29T04:31:54.326516Z","iopub.execute_input":"2022-04-29T04:31:54.32725Z","iopub.status.idle":"2022-04-29T04:32:04.98908Z","shell.execute_reply.started":"2022-04-29T04:31:54.327148Z","shell.execute_reply":"2022-04-29T04:32:04.988262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install timm","metadata":{"execution":{"iopub.status.busy":"2022-04-29T04:32:07.323652Z","iopub.execute_input":"2022-04-29T04:32:07.323926Z","iopub.status.idle":"2022-04-29T04:32:17.296984Z","shell.execute_reply.started":"2022-04-29T04:32:07.323893Z","shell.execute_reply":"2022-04-29T04:32:17.296141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport albumentations\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nimport tez\nfrom tez.datasets import ImageDataset\nfrom tez.callbacks import EarlyStopping\n\n\nimport timm\n\nfrom tqdm import tqdm\nimport torch\nimport torch.nn as nn\n\nimport torchvision\n\nfrom sklearn import metrics, model_selection\n%matplotlib inline","metadata":{"execution":{"iopub.status.busy":"2022-04-29T04:32:19.135541Z","iopub.execute_input":"2022-04-29T04:32:19.135831Z","iopub.status.idle":"2022-04-29T04:32:24.005484Z","shell.execute_reply.started":"2022-04-29T04:32:19.135799Z","shell.execute_reply":"2022-04-29T04:32:24.004556Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('../input/ultra-mnist/train.csv')","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.640812Z","iopub.execute_input":"2022-03-30T07:37:31.641088Z","iopub.status.idle":"2022-03-30T07:37:31.676855Z","shell.execute_reply.started":"2022-03-30T07:37:31.64105Z","shell.execute_reply":"2022-03-30T07:37:31.676092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.digit_sum.value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.677963Z","iopub.execute_input":"2022-03-30T07:37:31.678217Z","iopub.status.idle":"2022-03-30T07:37:31.694877Z","shell.execute_reply.started":"2022-03-30T07:37:31.678182Z","shell.execute_reply":"2022-03-30T07:37:31.694217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv(\"../input/ultra-mnist/train.csv\")\ndf[\"kfold\"] = -1    \ndf = df.sample(frac=1).reset_index(drop=True)\ny = df.digit_sum.values\nkf = model_selection.KFold(n_splits=5)\n\nfor f, (t_, v_) in enumerate(kf.split(X=df)):\n    df.loc[v_, 'kfold'] = f\n\ndf.to_csv(\"train_folds.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.696138Z","iopub.execute_input":"2022-03-30T07:37:31.696955Z","iopub.status.idle":"2022-03-30T07:37:31.789367Z","shell.execute_reply.started":"2022-03-30T07:37:31.696913Z","shell.execute_reply":"2022-03-30T07:37:31.788548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.790658Z","iopub.execute_input":"2022-03-30T07:37:31.791013Z","iopub.status.idle":"2022-03-30T07:37:31.804976Z","shell.execute_reply.started":"2022-03-30T07:37:31.790971Z","shell.execute_reply":"2022-03-30T07:37:31.804195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"torchvision.models.","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class UmnistModel(tez.Model):\n    def __init__(self, num_classes):\n        super().__init__()\n        \n        self.convnet = torchvision.models.resnet18(pretrained=True)\n        self.convnet.fc = nn.Linear(512, num_classes)\n        self.step_scheduler_after = \"epoch\"\n        \n    def loss(self, outputs, targets):\n        if targets is None:\n            return None\n        return nn.CrossEntropyLoss()(outputs, targets)\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 {\n            \"accuracy\": accuracy\n        }\n    \n    def fetch_optimizer(self):\n        opt = torch.optim.Adam(self.parameters(), lr=1e-3)\n        return opt\n    \n    def fetch_scheduler(self):\n        sch = torch.optim.lr_scheduler.StepLR(self.optimizer, step_size=0.7)\n        return sch\n    \n    def forward(self, image, targets=None):\n        batch_size, _, _, _ = image.shape\n        \n        outputs = self.convnet(image)\n        if targets is not None:\n            loss = self.loss(outputs, targets)\n            mon_metrics = self.monitor_metrics(outputs, targets)\n            return outputs, loss, mon_metrics\n        return outputs, None, None\n    ","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.806534Z","iopub.execute_input":"2022-03-30T07:37:31.807049Z","iopub.status.idle":"2022-03-30T07:37:31.818647Z","shell.execute_reply.started":"2022-03-30T07:37:31.807007Z","shell.execute_reply":"2022-03-30T07:37:31.817767Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = UmnistModel(num_classes=28)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:31.821898Z","iopub.execute_input":"2022-03-30T07:37:31.822246Z","iopub.status.idle":"2022-03-30T07:37:33.680691Z","shell.execute_reply.started":"2022-03-30T07:37:31.822206Z","shell.execute_reply":"2022-03-30T07:37:33.679928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train(fold):\n    training_image_path = \"../input/resized-ultramnist-512-akash/ultra-mnist_512/train/\"\n    df = pd.read_csv('./train_folds.csv')\n    \n    df_train = df[df.kfold != fold].reset_index(drop=True)\n    df_valid = df[df.kfold == fold].reset_index(drop=True)\n    \n    train_images = df_train.id.values.tolist()\n    train_images = [os.path.join(training_image_path, i + \".jpeg\") for i in train_images]\n    train_targets = df_train.digit_sum.values\n\n    valid_images = df_valid.id.values.tolist()\n    valid_images = [os.path.join(training_image_path, i + \".jpeg\") for i in valid_images]\n    valid_targets = df_valid.digit_sum.values\n    \n    train_aug = albumentations.Compose(\n        [\n           albumentations.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255.0, always_apply=True),\n        ]\n    )\n\n    valid_aug = albumentations.Compose(\n        [\n           albumentations.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], max_pixel_value=255.0, always_apply=True),\n        ]\n    )\n\n    \n    train_dataset = ImageDataset(\n        image_paths = train_images,\n        targets = train_targets,\n        augmentations = train_aug\n    )\n\n    valid_dataset = ImageDataset(\n        image_paths = valid_images,\n        targets = valid_targets,\n        augmentations = valid_aug\n    )\n    \n    es = EarlyStopping(monitor=\"valid_accuracy\", model_path=\"model.bin\", patience=2, mode=\"max\")\n    model.fit(\n        train_dataset, \n        valid_dataset=valid_dataset,\n        train_bs=32,\n        valid_bs=64,\n        device=\"cuda\",\n        callbacks=[es],\n        fp16=True,\n        epochs=50\n    )","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:33.68182Z","iopub.execute_input":"2022-03-30T07:37:33.68215Z","iopub.status.idle":"2022-03-30T07:37:33.696559Z","shell.execute_reply.started":"2022-03-30T07:37:33.682105Z","shell.execute_reply":"2022-03-30T07:37:33.695667Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train(0)\ntrain(1)\ntrain(2)\ntrain(3)\ntrain(4)","metadata":{"execution":{"iopub.status.busy":"2022-03-30T07:37:33.697617Z","iopub.execute_input":"2022-03-30T07:37:33.697819Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def predict(fold):\n    df_test = pd.read_csv(\"../input/ultra-mnist/sample_submission.csv\")\n    image_path = \"../input/resized-ultramnist-512-akash/ultra-mnist_512/test\"\n    \n    test_image_paths = df_test.id.values.tolist()\n    test_image_paths = [os.path.join(image_path, x + \".jpeg\") for x in df_test.id.values]\n    test_targets = df_test.digit_sum.values\n    \n    test_aug = albumentations.Compose(\n        [\n            albumentations.Normalize(mean=[0.5,0.5,0.5], std=[0.5,0.5,0.5], max_pixel_value = 255.0, always_apply=True)\n        ]\n    )\n    \n    test_dataset = ImageDataset(\n        image_paths=test_image_paths,\n        targets=test_targets,\n        augmentations=test_aug,\n    )\n    \n    preds = model.predict(test_dataset, batch_size=32, n_jobs=-1)\n    final_preds = None\n    for p in preds:\n        if final_preds is None:\n            final_preds = p\n        else:\n            final_preds = np.vstack((final_preds, p))\n    final_preds = final_preds.argmax(axis=1)\n    \n    return final_preds","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"p1 = predict(0)\np2 = predict(1)\np3 = predict(2)\np4 = predict(3)\np5 = predict(4)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = (p1 + p2 + p3 + p4 + p5) / 5\nss = pd.read_csv('../input/ultra-mnist/sample_submission.csv')\nss['digit_sum'] = predictions.astype(int)\nss.to_csv('submission.csv', index=False)\nss.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kaggle competitions submit -c ultra-mnist -f submission.csv -m \"Message\"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}