{"cells":[{"metadata":{},"cell_type":"markdown","source":"The model(BornoNet) is cited from <br>\nthis article : https://www.researchgate.net/publication/329048432_BornoNet_Bangla_Handwritten_Characters_Recognition_Using_Convolutional_Neural_Network\nThis paper seems to use image size 28x28 as usual MNIST dataset but mine is 64x64, so customized the architecture not only fitted to the image size that I am using but also to achieve good accuracy.\n\nThere are some architectrues studied according to this post you can try for fun ;-)<br>\nhttps://www.kaggle.com/c/bengaliai-cv19/discussion/122604"},{"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\n'''\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n'''\n\n# Any results you write to the current directory are saved as output.\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import Dataset,DataLoader\nfrom torchvision import transforms,models\nfrom tqdm import tqdm_notebook as tqdm\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/bengaliai-cv19/train.csv')\ndata0 = pd.read_feather('/kaggle/usr/lib/resize_and_load_with_feather_format_much_faster/train_data_0.feather')\ndata1 = pd.read_feather('/kaggle/usr/lib/resize_and_load_with_feather_format_much_faster/train_data_1.feather')\ndata2 = pd.read_feather('/kaggle/usr/lib/resize_and_load_with_feather_format_much_faster/train_data_2.feather')\ndata3 = pd.read_feather('/kaggle/usr/lib/resize_and_load_with_feather_format_much_faster/train_data_3.feather')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_full = pd.concat([data0,data1,data2,data3],ignore_index=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class GraphemeDataset(Dataset):\n    def __init__(self,df,label,_type='train'):\n        self.df = df\n        self.label = label\n    def __len__(self):\n        return len(self.df)\n    def __getitem__(self,idx):\n        label1 = self.label.consonant_diacritic.values[idx]\n        label2 = self.label.grapheme_root.values[idx]\n        label3 = self.label.vowel_diacritic.values[idx]\n        image = self.df.iloc[idx][1:].values.reshape(64,64).astype(np.uint8)\n\n        return torch.tensor(image/255.0),label1,label2,label3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = GraphemeDataset(data_full,train)\nloader = torch.utils.data.DataLoader(image,batch_size=15,shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,ax = plt.subplots(3,5,figsize=(25,25))\nax = ax.flatten()\na = next(iter(loader))\nfor i in range(15):\n    ax[i].imshow(a[0][i],cmap='gray')\n    ax[i].set_title([int(a[1][i]),int(a[2][i]),int(a[3][i])])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class BornoBranch(nn.Module):\n    def __init__(self,in_channels,out_channels):\n        super().__init__()\n        self.branch1 = nn.Sequential(\n            nn.Conv2d(in_channels,out_channels,kernel_size=5),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True),\n            nn.Conv2d(out_channels,out_channels,kernel_size=3),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True)\n            \n        )\n        self.branch2 = nn.Sequential(\n            nn.Conv2d(in_channels,out_channels,kernel_size=5),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True),\n            nn.Conv2d(out_channels,out_channels,kernel_size=3),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True)\n        )\n        \n    def forward(self,x):\n        x1 = self.branch1(x)\n        x2 = self.branch2(x)\n        \n        return x1+x2","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"class BornoNet(nn.Module):\n    \n    def __init__(self):\n        super().__init__()\n        self.conv = nn.Sequential(\n            nn.Conv2d(1,32,kernel_size=2,padding=2),\n            nn.BatchNorm2d(32),\n            nn.ReLU(True),\n            nn.Conv2d(32,32,kernel_size=2,padding=2),\n            nn.BatchNorm2d(32),\n            nn.ReLU(True),\n        )\n        self.branches1 = BornoBranch(32,64)\n        self.branches2 = BornoBranch(64,64)\n        self.maxpool = nn.MaxPool2d(3)\n        self.fc1 = nn.Linear(1600,7)\n        self.fc2 = nn.Linear(1600,168)\n        self.fc3 = nn.Linear(1600,11)\n    def forward(self,x):\n        x = F.dropout(self.conv(x),0.25)\n        x = self.branches1(x)\n        x = F.dropout(self.maxpool(x),0.25)\n        x = self.branches2(x)\n        x = F.dropout(self.maxpool(x),0.25)\n        x = x.view(x.size(0),-1)\n        x1 = self.fc1(x)\n        x2 = self.fc2(x)\n        x3 = self.fc3(x)\n        #Skip Softmax ;-)\n        return x1,x2,x3\n        ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install torchsummary\nfrom torchsummary import summary\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel = BornoNet().to(device)\nsummary(model, (1, 64, 64))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\nmodel = BornoNet().to(device)\noptimizer = optimizer = torch.optim.Adam(model.parameters(), lr=2e-2)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 2, gamma=0.9)\ncriterion = nn.CrossEntropyLoss()\nbatch_size=32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50\nmodel.train()\nlosses = []\naccs = []\nval_losses = []\nval_accs = []\nfor epoch in range(epochs):\n    train_index =train.groupby(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']).apply(lambda x: x.sample(5)).image_id.values\n    reduced_train = train.loc[train.image_id.isin(train_index)]\n    train_data = data_full.loc[data_full.image_id.isin(train_index)]\n    \n    train_image = GraphemeDataset(train_data,reduced_train)\n    train_loader = torch.utils.data.DataLoader(train_image,batch_size=batch_size,shuffle=True)\n    \n    test_index =train.groupby(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic']).apply(lambda x: x.sample(1)).image_id.values\n    reduced_test = train.loc[train.image_id.isin(test_index)]\n    test_data = data_full.loc[data_full.image_id.isin(test_index)]\n    \n    test_image = GraphemeDataset(test_data,reduced_test)\n    test_loader = torch.utils.data.DataLoader(test_image,batch_size=batch_size,shuffle=True)\n    \n    print('epochs {}/{} '.format(epoch+1,epochs))\n    running_loss = 0.0\n    running_acc = 0.0\n    for idx, (inputs,labels1,labels2,labels3) in tqdm(enumerate(train_loader),total=len(train_loader)):\n        inputs = inputs.to(device)\n        labels1 = labels1.to(device)\n        labels2 = labels2.to(device)\n        labels3 = labels3.to(device)\n        \n        optimizer.zero_grad()\n        outputs1,outputs2,outputs3 = model(inputs.unsqueeze(1).float())\n        loss1 = criterion(outputs1,labels1)\n        loss2 = criterion(outputs2,labels2)\n        loss3 = criterion(outputs3,labels3)\n        running_loss += loss1+loss2+loss3\n        running_acc += (outputs1.argmax(1)==labels1).float().mean()\n        running_acc += (outputs2.argmax(1)==labels2).float().mean()\n        running_acc += (outputs3.argmax(1)==labels3).float().mean()\n        (loss1+loss2+loss3).backward()\n        optimizer.step()\n    scheduler.step()\n    losses.append(running_loss/len(train_loader))\n    accs.append(running_acc/(len(train_loader)*3))\n    print('acc : {:.2f}%'.format(running_acc/(len(train_loader)*3)))\n    print('loss : {:.4f}'.format(running_loss/len(train_loader)))\n    \n    with torch.no_grad():\n        running_loss = 0.0\n        running_acc = 0.0\n        for idx, (inputs,labels1,labels2,labels3) in tqdm(enumerate(test_loader),total=len(test_loader)):\n            \n            inputs = inputs.to(device)\n            labels1 = labels1.to(device)\n            labels2 = labels2.to(device)\n            labels3 = labels3.to(device)\n            \n            outputs1,outputs2,outputs3 = model(inputs.unsqueeze(1).float())\n            \n            loss1 = criterion(outputs1,labels1)\n            loss2 = criterion(outputs2,labels2)\n            loss3 = criterion(outputs3,labels3)\n            running_loss += loss1+loss2+loss3\n            running_acc += (outputs1.argmax(1)==labels1).float().mean()\n            running_acc += (outputs2.argmax(1)==labels2).float().mean()\n            running_acc += (outputs3.argmax(1)==labels3).float().mean()\n            \n        \n        val_losses.append(running_loss/len(test_loader))\n        val_accs.append(running_acc/(len(test_loader)*3))\n        print('val_acc : {:.2f}%'.format(running_acc/(len(test_loader)*3)))\n        print('va_loss : {:.4f}'.format(running_loss/len(test_loader)))\n            \ntorch.save(model.state_dict(), 'saved_weights.pth')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig,ax = plt.subplots(1,2,figsize=(15,5))\nax[0].plot(losses,label='train')\nax[0].plot(val_losses,label='valid')\nax[0].set_title('loss')\nax[0].legend()\nax[1].plot(accs,label='train')\nax[1].plot(val_accs,label='valid')\nax[1].set_title('acc')\nax[0].legend()","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}