{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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 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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Part 1: build dataset and visualize"},{"metadata":{"trusted":true},"cell_type":"code","source":"import sys\nimport time\nimport math\nimport gc\nimport cv2\n\nimport torch\nimport torch.nn as nn\nfrom torch.optim import lr_scheduler\nfrom torch.utils.data import Dataset, DataLoader\n\nimport torchvision\nimport torchvision.transforms as T \nimport torchvision.models as models\n\nimport matplotlib.pyplot as plt\n\ndef timeSince(since):\n    now = time.time()\n    s = now - since\n    m = math.floor(s / 60)\n    s -= m * 60\n    return '%dm %ds' % (m, s)\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nprint(device)\n\nroot_test = '/kaggle/input/bengaliai-cv19'\nmodel_path = '/kaggle/input/trained-model/new_resnet34.pth'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class graphemeDataset(Dataset):\n    def __init__(self, img_arrs, target_file = None):\n        self.img_arrs = img_arrs\n        self.target_file = target_file\n        \n        if target_file is None:\n            self.transforms = T.Compose([T.ToPILImage(), T.CenterCrop(150), T.Resize((128,128)),T.ToTensor()])\n        else:\n            self.transforms = T.Compose([T.ToPILImage(),T.RandomAffine(90),T.CenterCrop(150), T.Resize((128,128)),T.ToTensor()])\n            # add targets for training\n            target_df = pd.read_csv(target_file)\n            self.grapheme = target_df['grapheme_root'].values\n            self.vowel = target_df['vowel_diacritic'].values\n            self.consonant = target_df['consonant_diacritic'].values\n            del target_df\n            gc.collect()\n               \n    def __getitem__(self, idx):\n        img_arr = 255 - self.img_arrs[idx] # flip black and white, so the default padding value (0) could match\n        new_tensor = self.transforms(img_arr.reshape(137, 236, 1))\n        \n        if self.target_file is None:\n            return new_tensor\n        else:\n            grapheme_tensor = torch.tensor(self.grapheme[idx], dtype=torch.long)\n            vowel_tensor = torch.tensor(self.vowel[idx], dtype=torch.long)\n            consonant_tensor = torch.tensor(self.consonant[idx], dtype=torch.long)\n            return new_tensor, grapheme_tensor, vowel_tensor, consonant_tensor\n    \n    def __len__(self):\n        return len(self.img_arrs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class modified_resnet34(nn.Module):\n    def __init__(self):\n        super(modified_resnet34, self).__init__()\n        \n        resnet34 = models.resnet34()\n        resnet34.conv1 =  nn.Conv2d(1, 64, kernel_size = 5, stride = 1, padding = 2, bias = False)\n        layers = list(resnet34.children())[:-1] + [nn.Flatten()]\n        self.features= nn.Sequential(*layers)\n        \n        self.grapheme_classifier = nn.Sequential(\n            nn.Linear(512, 168),\n            nn.LogSoftmax(dim=1)\n        )\n\n        self.vowel_classifier = nn.Sequential(\n            nn.Linear(512, 11),\n            nn.LogSoftmax(dim=1)\n        )\n        \n        self.consonant_classifier = nn.Sequential(\n            nn.Linear(512, 7),\n            nn.LogSoftmax(dim=1)\n        )\n        \n    def forward(self, x):\n        x = self.features(x)\n        c1 = self.grapheme_classifier(x)\n        c2 = self.vowel_classifier(x)\n        c3 = self.consonant_classifier(x)\n        return c1, c2, c3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = modified_resnet34()\nmodel.load_state_dict(torch.load(model_path))\nmodel.to(device)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"row_id = [];\ntarget = [];\nfor i in range(4):\n    # load testing data\n    start = time.time()\n    img_df = pd.read_parquet(os.path.join(root_test,'test_image_data_' + str(i) + '.parquet'))\n    print(timeSince(start))\n    \n    img_id = []\n    img_id.extend(img_df.image_id.tolist())\n    img_arrs = img_df.iloc[:,1:].values\n    dataset = graphemeDataset(img_arrs)\n    print(dataset.__len__())\n    loader = DataLoader(dataset, batch_size = 128, shuffle = False)\n    \n    # make predictions\n    grapheme_pred = []; vowel_pred = []; consonant_pred = []\n    with torch.no_grad():\n        for img_tensor in loader:\n            img_tensor = img_tensor.to(device)\n            c1, c2, c3 = model(img_tensor)\n            grapheme_pred.extend(c1.argmax(1).cpu().tolist())\n            vowel_pred.extend(c2.argmax(1).cpu().tolist())\n            consonant_pred.extend(c3.argmax(1).cpu().tolist())\n    \n    # format the results\n    for idx, g, v, c in zip(img_id, grapheme_pred, vowel_pred, consonant_pred):\n        row_id.append(idx + '_grapheme_root')\n        row_id.append(idx + '_vowel_diacritic')\n        row_id.append(idx + '_consonant_diacritic')\n        target.append(g)\n        target.append(v)\n        target.append(c)\n        \n    # clean up \n    del img_arrs, img_df\n    gc.collect()\n        \npred = pd.DataFrame({'row_id' : row_id,'target':target})\npred.head()   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred.to_csv('submission.csv',index=False)","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}