{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import sys\npt_models = \"../input/pretrained-models/pretrained-models.pytorch-master/\"\npt_models\nsys.path.insert(0,pt_models)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import pretrainedmodels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport numpy as np \nimport pandas as pd\nimport ast\nimport torch\nfrom tqdm import tqdm\nimport torch.nn as nn\nimport joblib\nimport albumentations\nfrom PIL import Image\nimport glob\nfrom torch.nn import functional as F","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMG_HEIGHT = 137\nIMG_WIDTH = 236\nTEST_BATCH_SIZE = 16\nMODEL_MEAN = (0.485, 0.456, 0.406)\nMODEL_STD = (0.229, 0.224, 0.225)\nDEVICE = \"cuda\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class Resnet34(nn.Module):\n    def __init__(self, pretrained):\n        super(Resnet34, self).__init__()\n        if pretrained is True:\n            self.model = pretrainedmodels.__dict__['resnet34'](pretrained = \"imagenet\")\n        else:\n            self.model = pretrainedmodels.__dict__['resnet34'](pretrained = None)\n\n        self.l0 = nn.Linear(512,168)\n        self.l1 = nn.Linear(512,11)\n        self.l2 = nn.Linear(512,7)\n\n    def forward(self, x):\n        bs, _,_,_ = x.shape\n        x = self.model.features(x)\n        x = F.adaptive_avg_pool2d(x,1).reshape(bs, -1)\n        l0 = self.l0(x)\n        l1 = self.l1(x)\n        l2 = self.l2(x)\n        return l0, l1, l2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class BengaliDatasetTrain:\n    def __init__(self, df, img_height, img_width, mean, std):\n        \n        self.image_ids = df.image_id.values\n        self.img_arr = df.iloc[:, 1:].values\n        \n        self.aug = albumentations.Compose([\n            albumentations.Resize(img_height, img_width, always_apply=True),\n            albumentations.Normalize(mean, std, always_apply = True)\n        ])\n    def __len__(self):\n        return len(self.image_ids)\n    \n    def __getitem__(self, item):\n        image = self.img_arr[item, :]\n        img_id = self.image_ids[item]\n        image = image.reshape(137,236).astype(float)\n        image = Image.fromarray(image).convert(\"RGB\")\n        image = self.aug(image = np.array(image))['image']\n        image = np.transpose(image, (2,0,1)).astype(np.float32)\n        return{\n            'image': torch.tensor(image, dtype=torch.float),\n            \"image_id\":img_id\n        }\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Resnet34(pretrained=False)\nmodel.load_state_dict(torch.load(\"../input/bengali-train-model/resnet34_4_weighted.pth\", map_location=torch.device('cpu')))\nmodel.eval()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions = []\nfor file_idx in range(4):\n    df = pd.read_parquet(f\"../input/bengaliai-cv19/test_image_data_{file_idx}.parquet\")\n    dataset = BengaliDatasetTrain(df = df, \n                                  img_height=IMG_HEIGHT,\n                                  img_width=IMG_WIDTH,\n                                  mean = MODEL_MEAN,\n                                  std=MODEL_STD)\n    data_loader = torch.utils.data.DataLoader(dataset,\n                                              batch_size=TEST_BATCH_SIZE,\n                                              shuffle=False,\n                                              num_workers=4)\n    with torch.no_grad():\n        for bi, d in enumerate(data_loader):\n            image = d['image']\n            img_id = d['image_id']\n            g, v, c = model(image)\n            g = np.argmax(g, axis=1)\n            v = np.argmax(v, axis=1)\n            c = np.argmax(c, axis=1)\n            for ii, imid in enumerate(img_id):\n                predictions.append((f\"{imid}_grapheme_root\", int(g[ii])))\n                predictions.append((f\"{imid}_vowel_diacritic\", int(v[ii])))\n                predictions.append((f\"{imid}_consonant_diacritic\", int(c[ii])))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub = pd.DataFrame(predictions, columns = ['row_id', 'target'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv('submission.csv', index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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}