{"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":{"trusted":true},"cell_type":"code","source":"import cv2\nfrom fastai.vision import *\nfrom tqdm import tqdm_notebook as tqdm\nimport torch\nimport torch.nn as nn\nimport torchvision","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"class MyRn34(nn.Module):\n    def __init__(self):\n        super(MyRn34, self).__init__()\n        self.model_resnet = torchvision.models.resnet34()\n        num_ftrs = self.model_resnet.fc.in_features\n        self.model_resnet.fc = nn.Identity()\n        self.fc_graph = nn.Linear(num_ftrs, 168)\n        self.fc_vowel = nn.Linear(num_ftrs, 11)\n        self.fc_conso = nn.Linear(num_ftrs, 7)\n\n    def forward(self, x):\n        x = self.model_resnet(x)\n        out1 = self.fc_graph(x)\n        out2 = self.fc_vowel(x)\n        out3 = self.fc_conso(x)\n        return out1, out2, out3\n\nmy_rn34=MyRn34()\nmy_rn34;","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=my_rn34\nweighties = torch.load('/kaggle/input/bengali-grapheme-first-try/model_1.pth',\n                      map_location=torch.device('cpu'))\nmodel.load_state_dict(weighties['state_dict'])\nmodel.eval();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"nworkers = 2\nPATH = '/kaggle/input/bengaliai-cv19/'\nTEST = [PATH+'test_image_data_0.parquet',\n        PATH+'test_image_data_1.parquet',\n        PATH+'test_image_data_2.parquet',\n        PATH+'test_image_data_3.parquet']\n\ndf_test = pd.read_csv(PATH+'test.csv')\ndf_test.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"HEIGHT = 137\nWIDTH = 236\nSIZE = 128\n\ndef bbox(img):\n    rows = np.any(img, axis=1)\n    cols = np.any(img, axis=0)\n    rmin, rmax = np.where(rows)[0][[0, -1]]\n    cmin, cmax = np.where(cols)[0][[0, -1]]\n    return rmin, rmax, cmin, cmax\n\ndef crop_resize(img0, size=SIZE, pad=16):\n    #crop a box around pixels large than the threshold \n    #some images contain line at the sides\n    ymin,ymax,xmin,xmax = bbox(img0[5:-5,5:-5] > 80)\n    #cropping may cut too much, so we need to add it back\n    xmin = xmin - 13 if (xmin > 13) else 0\n    ymin = ymin - 10 if (ymin > 10) else 0\n    xmax = xmax + 13 if (xmax < WIDTH - 13) else WIDTH\n    ymax = ymax + 10 if (ymax < HEIGHT - 10) else HEIGHT\n    img = img0[ymin:ymax,xmin:xmax]\n    #remove lo intensity pixels as noise\n    img[img < 28] = 0\n    lx, ly = xmax-xmin,ymax-ymin\n    l = max(lx,ly) + pad\n    #make sure that the aspect ratio is kept in rescaling\n    img = np.pad(img, [((l-ly)//2,), ((l-lx)//2,)], mode='constant')\n    return cv2.resize(img,(size,size))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class GraphemeDataset(Dataset):\n    def __init__(self, fname):\n        self.df = pd.read_parquet(fname)\n        self.data = 255 - self.df.iloc[:, 1:].values.reshape(-1, HEIGHT, WIDTH).astype(np.uint8)\n\n    def __len__(self):\n        return len(self.data)\n\n    def __getitem__(self, idx):\n        name = self.df.iloc[idx,0]\n        #normalize each image by its max val\n        img = (self.data[idx]*(255.0/self.data[idx].max())).astype(np.uint8)\n        img = crop_resize(img)\n        img = (img.astype(np.float32)/255.0 - imagenet_stats[0][0])/imagenet_stats[1][0]\n        return img, name","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"row_id,target,bs = [],[],128\n\nfor fname in TEST:\n    ds = GraphemeDataset(fname)\n    dl = DataLoader(ds, batch_size=bs, num_workers=nworkers, shuffle=False)\n    with torch.no_grad():\n        for x,y in tqdm(dl):\n            x = x.unsqueeze(1)\n            x = x.repeat(1,3,1,1)\n            p1,p2,p3 = model(x)\n            p1 = p1.argmax(-1).view(-1).cpu()\n            p2 = p2.argmax(-1).view(-1).cpu()\n            p3 = p3.argmax(-1).view(-1).cpu()\n            for idx,name in enumerate(y):\n                row_id += [f'{name}_grapheme_root',f'{name}_vowel_diacritic',\n                           f'{name}_consonant_diacritic']\n                target += [p1[idx].item(),p2[idx].item(),p3[idx].item()]\n                \nsub_df = pd.DataFrame({'row_id': row_id, 'target': target})\nsub_df.to_csv('submission.csv', index=False)\nsub_df","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":1}