{"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":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport torch\nimport os\nimport torch.nn as nn\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset,DataLoader\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):\n    return nn.Conv2d(in_planes, out_planes, kernel_size=3,\n                     stride=stride,padding=dilation,groups=groups,bias=False,\n                     dilation=dilation)\n\n\ndef conv1x1(in_planes, out_planes, stride=1):\n    return  nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False)\n\n\nclass BasicBlock(nn.Module):\n    expansion = 1\n\n    def __init__(self, inplanes, planes, stride=1, downsample=None,\n                 group=1,base_width=64,dilation=1,norm_layer=None):\n\n        super(BasicBlock, self).__init__()\n\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d()\n\n        if group != 1 or base_width != 64:\n            raise ValueError('BasicBlock only supports groups=1 and base_width=64')\n        if dilation > 1:\n            raise NotImplementedError(\"Dilation > 1 not supported in BasicBlock\")\n\n\n        self.conv1 = conv3x3(inplanes, planes, stride)\n        self.bn1 = norm_layer(planes)\n        self.relu = nn.ReLU(inplace=1)\n\n        self.conv2 = conv3x3(planes, planes)\n        self.bn2 = norm_layer(planes)\n        self.downsample = downsample\n        self.stride = stride\n\n\n    def forward(self, x):\n        identity = x\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n\n        if self.downsample is not None:\n            identity = self.downsample(x)\n\n        out += identity\n        out = self.relu(out)\n\n        return  out\n\n\nclass Bottleneck(nn.Module):\n    expansion = 4\n    def __init__(self,inplanes, planes, stride=1, downsample=None,groups=1,\n                 base_width=64, deliation=1,norm_layer=None):\n        super(Bottleneck,self).__init__()\n\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d()\n\n        width = int(planes*(base_width/64.0))*groups\n\n        self.conv1 = conv1x1(inplanes,width)\n        self.bn1 = norm_layer(width)\n        self.conv2 = conv3x3(width,width,stride,groups, deliation)\n        self.bn2 = norm_layer(width)\n        self.conv3 = conv1x1(width,planes*self.expansion)\n        self.bn3 = norm_layer(planes*self.expansion)\n\n        self.relu = nn.ReLU(inplace=1)\n        self.downsample = downsample\n        self.stride = stride\n\n\n    def forward(self, x):\n        idendity = x\n\n        out = self.conv1(x)\n        out = self.bn1(out)\n        out = self.relu(out)\n\n        out = self.conv2(out)\n        out = self.bn2(out)\n        out = self.relu(out)\n\n        out = self.conv3(out)\n        out = self.bn3(out)\n        out = self.relu(out)\n\n        if self.downsample is not None:\n            idendity = self.downsample(x)\n\n        out += idendity\n        out = self.relu(out)\n\n        return out\n\n\n\nclass ResNet(nn.Module):\n    def __init__(self, block, layers, num_classes_info, zero_init_residual=False,\n                 groups=1, width_per_group=64, replace_stride_with_dilation=None,\n                 norm_layer=None):\n\n        super(ResNet, self).__init__()\n\n        if norm_layer is None:\n            norm_layer = nn.BatchNorm2d\n        self._norm_layer = norm_layer\n\n        self.inplanes = 64\n        self.dilation = 1\n\n        if replace_stride_with_dilation is None:\n            replace_stride_with_dilation = [False, False, False]\n        if len(replace_stride_with_dilation) != 3:\n            raise ValueError(\"replace_stride_with_dilation should be None \"\n                             \"or a 3-element tuple, got {}\".format(replace_stride_with_dilation))\n\n\n        #-----------每个resnet的第一层都是有7*7的conv开始-------------------------------\n        self.groups = groups\n        self.base_width = width_per_group\n        self.conv1 = nn.Conv2d(1, self.inplanes, kernel_size=7, stride=2, padding=3,\n                               bias=False)\n        self.bn1 = norm_layer(self.inplanes)\n        self.relu = nn.ReLU(inplace=True)\n        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n        #----------------------------------------------------------------------------\n\n        #----------------之后有4层网络块构成------------------------------\n        self.layer1 = self._make_layer(block, 64, layers[0])\n        self.layer2 = self._make_layer(block, 128, layers[1], stride=2,\n                                       dilate=replace_stride_with_dilation[0])\n        self.layer3 = self._make_layer(block, 256, layers[2], stride=2,\n                                       dilate=replace_stride_with_dilation[1])\n        self.layer4 = self._make_layer(block, 512, layers[3], stride=2,\n                                       dilate=replace_stride_with_dilation[2])\n        #-----------------------------------------------------------------\n\n        self.avgpool = nn.AdaptiveAvgPool2d((1, 1))\n        self.fc_grapheme_root = nn.Linear(512 * block.expansion, num_classes_info['grapheme_root'])\n        self.fc_vowel = nn.Linear(512*block.expansion,num_classes_info['vowel'])\n        self.fc_consonant = nn.Linear(512*block.expansion,num_classes_info['consonant'])\n\n        for m in self.modules():\n            if isinstance(m, nn.Conv2d):\n                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')\n            elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)):\n                nn.init.constant_(m.weight, 1)\n                nn.init.constant_(m.bias, 0)\n\n        if zero_init_residual:\n            for m in self.modules():\n                if isinstance(m, Bottleneck):\n                    nn.init.constant_(m.bn3.weight, 0)\n                elif isinstance(m, BasicBlock):\n                    nn.init.constant_(m.bn2.weight, 0)\n\n    def _make_layer(self, block, planes, blocks, stride=1, dilate=False):\n        \"\"\"\n        每个layer包含 n 个 block,（resnet n=2）每个block由2层卷积组成\n        “”“\n        :param self:\n        :param block:\n        :param planes:\n        :param blocks:\n        :param stride:\n        :param dilate:\n        :return:\n        \"\"\"\n        norm_layer = self._norm_layer\n        downsample = None\n        previous_dilation = self.dilation\n\n        if dilate:\n            self.dilation *= stride\n            stride = 1\n\n        if stride != 1 or self.inplanes != planes * block.expansion:\n            downsample = nn.Sequential(\n                conv1x1(self.inplanes, planes * block.expansion, stride),\n                norm_layer(planes * block.expansion),\n            )\n\n        layers = []\n        layers.append(block(self.inplanes, planes, stride, downsample, self.groups,\n                            self.base_width, previous_dilation, norm_layer))\n\n        self.inplanes = planes * block.expansion\n\n        for _ in range(1, blocks):\n            layers.append(block(self.inplanes, planes, group=self.groups,\n                                base_width=self.base_width, dilation=self.dilation,\n                                norm_layer=norm_layer))\n\n        return nn.Sequential(*layers)\n\n    def forward(self, x):\n        x = self.conv1(x)\n        x = self.bn1(x)\n        x = self.relu(x)\n        x = self.maxpool(x)\n\n        x = self.layer1(x)\n        x = self.layer2(x)\n        x = self.layer3(x)\n        x = self.layer4(x)\n\n        x = self.avgpool(x)\n        x = x.reshape(x.size(0), -1)\n        grapheme_root  = self.fc_grapheme_root(x)\n        vowel = self.fc_vowel(x)\n        constant = self.fc_consonant(x)\n        \n        return grapheme_root,vowel,constant\n\n\ndef _resnet(arch, block, layers, num_classes,pretrained, progress, **kwargs):\n    model = ResNet(block, layers, num_classes, **kwargs)\n    return model\n\n\n\ndef resnet34(pretrained=False,progress=True, **kwargs):\n    return _resnet('resnet34', BasicBlock, [3, 4, 6, 3], num_classes_info,pretrained, progress,\n                   **kwargs)\n\ndef resnet18(pretrained=False,progress=True, **kwargs):\n    return _resnet('resnet18', BasicBlock, [2, 2, 2, 2], num_classes_info,pretrained, progress,\n                   **kwargs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"num_classes_info = {'grapheme_root':168,'vowel':11,'consonant':7}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class GraphemeDataset(Dataset):\n    def __init__(self,images,label,_type='train'):\n        self.images = images\n        self.label = label\n    def __len__(self):\n        return len(self.images)\n    def __getitem__(self,idx):\n        label_grapheme_root = self.label.grapheme_root.values[idx]\n        label_vowel = self.label.vowel_diacritic.values[idx]\n        label_consonant = self.label.consonant_diacritic.values[idx]\n        image = self.images[idx].reshape(64,64).astype(np.uint8)\n\n        return torch.tensor(image),label_grapheme_root,label_vowel,label_consonant","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"root_path = './data'\nlabels = pd.read_csv(os.path.join(root_path,'train.csv'))\nimages =np.load('./processed/train_imgs_64x64.npy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image = GraphemeDataset(images,labels)\nloader = torch.utils.data.DataLoader(image,batch_size=15,shuffle=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = resnet34().to(device)\noptimizer = torch.optim.Adam(model.parameters(),lr=8e-2)\nscheduler = torch.optim.lr_scheduler.ExponentialLR(optimizer, 0.999, last_epoch=-1)\ncriterion = nn.CrossEntropyLoss()\nbatch_size=32","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs = 50\nmodel.train()\nlosses = []\naccs = []\n\ntrain = labels\ndata_full = images\n\nfor epoch in range(epochs):\n    reduced_index =train.groupby(['grapheme_root', 'vowel_diacritic', 'consonant_diacritic'])\\\n    .apply(lambda x: x.sample(5)).image_id.values\n    \n    reduced_train = train.loc[train.image_id.isin(reduced_index)]\n    reduced_data = data_full[train.image_id.isin(reduced_index)]\n    train_image = GraphemeDataset(reduced_data,reduced_train)\n    train_loader = torch.utils.data.DataLoader(train_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\ntorch.save(model.state_dict(), 'saved_weights.pth')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_namess = np.load('./processed/test_names.npy')\ntest_imgs = np.load('./processed/test_imgs.npy')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class GraphemeDatasetFortest(Dataset):\n    def __init__(self,images):\n        self.images = images\n    def __len__(self):\n        return len(self.images)\n    def __getitem__(self,idx):\n        image = self.images[idx].reshape(128,128).astype(np.float)\n        \n        return image\n    \ntest_image = GraphemeDatasetFortest(test_imgs)\ntest_loader = torch.utils.data.DataLoader(test_image,batch_size=1,shuffle=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":1}