{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is continuing of\n\nhttps://www.kaggle.com/hanjoonchoe/grapheme-resnet-18-naive-learning<br>\nhttps://www.kaggle.com/hanjoonchoe/grapheme-resnet-18-naive-learning-2<br>\nhttps://www.kaggle.com/hanjoonchoe/grapheme-resnet-18-naive-learning-3<br>"},{"metadata":{},"cell_type":"markdown","source":"Update \n> * add Test-Valid split"},{"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\nfrom torch.utils.data import Dataset,DataLoader\nfrom torchvision import transforms,models\nfrom tqdm import tqdm_notebook as tqdm\nimport matplotlib.pyplot as plt\nfrom imgaug import augmenters as iaa\nimport imgaug.augmenters as iaa","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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.vowel_diacritic.values[idx]\n        label2 = self.label.grapheme_root.values[idx]\n        label3 = self.label.consonant_diacritic.values[idx]\n        image = self.df.iloc[idx][1:].values.reshape(64,64).astype(np.uint8)\n\n        return torch.tensor(image),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 ResidualBlock(nn.Module):\n    def __init__(self,in_channels,out_channels,stride=1,kernel_size=3,padding=1,bias=False):\n        super(ResidualBlock,self).__init__()\n        self.cnn1 =nn.Sequential(\n            nn.Conv2d(in_channels,out_channels,kernel_size,stride,padding,bias=False),\n            nn.BatchNorm2d(out_channels),\n            nn.ReLU(True)\n        )\n        self.cnn2 = nn.Sequential(\n            nn.Conv2d(out_channels,out_channels,kernel_size,1,padding,bias=False),\n            nn.BatchNorm2d(out_channels)\n        )\n        if stride != 1 or in_channels != out_channels:\n            self.shortcut = nn.Sequential(\n                nn.Conv2d(in_channels,out_channels,kernel_size=1,stride=stride,bias=False),\n                nn.BatchNorm2d(out_channels)\n            )\n        else:\n            self.shortcut = nn.Sequential()\n            \n    def forward(self,x):\n        residual = x\n        x = self.cnn1(x)\n        x = self.cnn2(x)\n        x += self.shortcut(residual)\n        x = nn.ReLU(True)(x)\n        return x","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class ResNet18(nn.Module):\n    def __init__(self):\n        super(ResNet18,self).__init__()\n        \n        self.block1 = nn.Sequential(\n            nn.Conv2d(1,64,kernel_size=2,stride=2,padding=3,bias=False),\n            nn.BatchNorm2d(64),\n            nn.ReLU(True)\n        )\n        \n        self.block2 = nn.Sequential(\n            nn.MaxPool2d(1,1),\n            ResidualBlock(64,64),\n            ResidualBlock(64,64,2)\n        )\n        \n        self.block3 = nn.Sequential(\n            ResidualBlock(64,128),\n            ResidualBlock(128,128,2)\n        )\n        \n        self.block4 = nn.Sequential(\n            ResidualBlock(128,256),\n            ResidualBlock(256,256,2)\n        )\n        self.block5 = nn.Sequential(\n            ResidualBlock(256,512),\n            ResidualBlock(512,512,2)\n        )\n        \n        self.avgpool = nn.AvgPool2d(2)\n        # vowel_diacritic\n        self.fc1 = nn.Linear(512,11)\n        # grapheme_root\n        self.fc2 = nn.Linear(512,168)\n        # consonant_diacritic\n        self.fc3 = nn.Linear(512,7)\n        \n    def forward(self,x):\n        x = self.block1(x)\n        x = self.block2(x)\n        x = self.block3(x)\n        x = self.block4(x)\n        x = self.block5(x)\n        x = self.avgpool(x)\n        x = x.view(x.size(0),-1)\n        x1 = self.fc1(x)\n        x2 = self.fc2(x)\n        x3 = self.fc3(x)\n        return x1,x2,x3","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 = ResNet18().to(device)\nsummary(model, (1, 64, 64))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = ResNet18().to(device)\nmodel.load_state_dict(torch.load('/kaggle/input/grapheme-resnet-18-naive-learning-3/saved_weights.pth'))\noptimizer = optimizer = torch.optim.Adam(model.parameters(), lr=2e-5)\nscheduler = torch.optim.lr_scheduler.StepLR(optimizer, 2, gamma=0.99)\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}