{"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\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 read-only \"../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\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nfrom matplotlib import pyplot as plt\nfrom PIL import Image\nfrom torchvision import transforms as tsf\nimport csv\n%pylab inline","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"BAM"},{"metadata":{"trusted":true},"cell_type":"code","source":"import math\n\nclass Flatten(nn.Module):\n    def forward(self, x):\n        return x.view(x.size(0), -1)\nclass ChannelGate(nn.Module):\n    def __init__(self, gate_channel, reduction_ratio=16, num_layers=1):\n        super(ChannelGate, self).__init__()\n        #self.gate_activation = gate_activation\n        self.gate_c = nn.Sequential()\n        self.gate_c.add_module( 'flatten', Flatten() )\n        gate_channels = [gate_channel]\n        gate_channels += [gate_channel // reduction_ratio] * num_layers\n        gate_channels += [gate_channel]\n        for i in range( len(gate_channels) - 2 ):\n            self.gate_c.add_module( 'gate_c_fc_%d'%i, nn.Linear(gate_channels[i], gate_channels[i+1]) )\n            self.gate_c.add_module( 'gate_c_bn_%d'%(i+1), nn.BatchNorm1d(gate_channels[i+1]) )\n            self.gate_c.add_module( 'gate_c_relu_%d'%(i+1), nn.ReLU() )\n        self.gate_c.add_module( 'gate_c_fc_final', nn.Linear(gate_channels[-2], gate_channels[-1]) )\n    def forward(self, in_tensor):\n        avg_pool = F.avg_pool2d( in_tensor, in_tensor.size(2), stride=in_tensor.size(2) )\n        return self.gate_c( avg_pool ).unsqueeze(2).unsqueeze(3).expand_as(in_tensor)\n\nclass SpatialGate(nn.Module):\n    def __init__(self, gate_channel, reduction_ratio=16, dilation_conv_num=2, dilation_val=4):\n        super(SpatialGate, self).__init__()\n        self.gate_s = nn.Sequential()\n        self.gate_s.add_module( 'gate_s_conv_reduce0', nn.Conv2d(gate_channel, gate_channel//reduction_ratio, kernel_size=1))\n        self.gate_s.add_module( 'gate_s_bn_reduce0',\tnn.BatchNorm2d(gate_channel//reduction_ratio) )\n        self.gate_s.add_module( 'gate_s_relu_reduce0',nn.ReLU() )\n        for i in range( dilation_conv_num ):\n            self.gate_s.add_module( 'gate_s_conv_di_%d'%i, nn.Conv2d(gate_channel//reduction_ratio, gate_channel//reduction_ratio, kernel_size=3, \\\n\t\t\t\t\t\tpadding=dilation_val, dilation=dilation_val) )\n            self.gate_s.add_module( 'gate_s_bn_di_%d'%i, nn.BatchNorm2d(gate_channel//reduction_ratio) )\n            self.gate_s.add_module( 'gate_s_relu_di_%d'%i, nn.ReLU() )\n        self.gate_s.add_module( 'gate_s_conv_final', nn.Conv2d(gate_channel//reduction_ratio, 1, kernel_size=1) )\n    def forward(self, in_tensor):\n        return self.gate_s( in_tensor ).expand_as(in_tensor)\nclass BAM(nn.Module):\n    def __init__(self, gate_channel):\n        super(BAM, self).__init__()\n        self.channel_att = ChannelGate(gate_channel)\n        self.spatial_att = SpatialGate(gate_channel)\n    def forward(self,in_tensor):\n        att = 1 + F.sigmoid( self.channel_att(in_tensor) * self.spatial_att(in_tensor) )\n        return att * in_tensor\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"CBAM"},{"metadata":{"trusted":true},"cell_type":"code","source":"class BasicConv(nn.Module):\n    def __init__(self, in_planes, out_planes, kernel_size, stride=1, padding=0, dilation=1, groups=1, relu=True, bn=True, bias=False):\n        super(BasicConv, self).__init__()\n        self.out_channels = out_planes\n        self.conv = nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation, groups=groups, bias=bias)\n        self.bn = nn.BatchNorm2d(out_planes,eps=1e-5, momentum=0.01, affine=True) if bn else None\n        self.relu = nn.ReLU() if relu else None\n\n    def forward(self, x):\n        x = self.conv(x)\n        if self.bn is not None:\n            x = self.bn(x)\n        if self.relu is not None:\n            x = self.relu(x)\n        return x\n\nclass CFlatten(nn.Module):\n    def forward(self, x):\n        return x.view(x.size(0), -1)\n\nclass CChannelGate(nn.Module):\n    def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max']):\n        super(CChannelGate, self).__init__()\n        self.gate_channels = gate_channels\n        self.mlp = nn.Sequential(\n            Flatten(),\n            nn.Linear(gate_channels, gate_channels // reduction_ratio),\n            nn.ReLU(),\n            nn.Linear(gate_channels // reduction_ratio, gate_channels)\n            )\n        self.pool_types = pool_types\n    def forward(self, x):\n        channel_att_sum = None\n        for pool_type in self.pool_types:\n            if pool_type=='avg':\n                avg_pool = F.avg_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n                channel_att_raw = self.mlp( avg_pool )\n            elif pool_type=='max':\n                max_pool = F.max_pool2d( x, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n                channel_att_raw = self.mlp( max_pool )\n            elif pool_type=='lp':\n                lp_pool = F.lp_pool2d( x, 2, (x.size(2), x.size(3)), stride=(x.size(2), x.size(3)))\n                channel_att_raw = self.mlp( lp_pool )\n            elif pool_type=='lse':\n                # LSE pool only\n                lse_pool = logsumexp_2d(x)\n                channel_att_raw = self.mlp( lse_pool )\n\n            if channel_att_sum is None:\n                channel_att_sum = channel_att_raw\n            else:\n                channel_att_sum = channel_att_sum + channel_att_raw\n\n        scale = F.sigmoid( channel_att_sum ).unsqueeze(2).unsqueeze(3).expand_as(x)\n        return x * scale\n\ndef logsumexp_2d(tensor):\n    tensor_flatten = tensor.view(tensor.size(0), tensor.size(1), -1)\n    s, _ = torch.max(tensor_flatten, dim=2, keepdim=True)\n    outputs = s + (tensor_flatten - s).exp().sum(dim=2, keepdim=True).log()\n    return outputs\n\nclass ChannelPool(nn.Module):\n    def forward(self, x):\n        return torch.cat( (torch.max(x,1)[0].unsqueeze(1), torch.mean(x,1).unsqueeze(1)), dim=1 )\n\nclass CSpatialGate(nn.Module):\n    def __init__(self):\n        super(CSpatialGate, self).__init__()\n        kernel_size = 7\n        self.compress = ChannelPool()\n        self.spatial = BasicConv(2, 1, kernel_size, stride=1, padding=(kernel_size-1) // 2, relu=False)\n    def forward(self, x):\n        x_compress = self.compress(x)\n        x_out = self.spatial(x_compress)\n        scale = F.sigmoid(x_out) # broadcasting\n        return x * scale\n\nclass CBAM(nn.Module):\n    def __init__(self, gate_channels, reduction_ratio=16, pool_types=['avg', 'max'], no_spatial=False):\n        super(CBAM, self).__init__()\n        self.CChannelGate = CChannelGate(gate_channels, reduction_ratio, pool_types)\n        self.no_spatial=no_spatial\n        if not no_spatial:\n            self.CSpatialGate = CSpatialGate()\n    def forward(self, x):\n        x_out = self.CChannelGate(x)\n        if not self.no_spatial:\n            x_out = self.CSpatialGate(x_out)\n        return x_out","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import os\nimport numpy as np\n#获取到数据集中的图像路径\ndef csv_reader(path):\n    with open(path, \"r\") as f:\n        breast = list(csv.reader(f))\n    return breast\ndef get_datas(image_dir,suffix=\".png\"):\n    '''\n    image_dir:包含图像的文件夹\n    suffix:图像的后缀\n    '''\n    image_paths = []\n    labels = []\n    train=csv_reader(\"../input/aptos2019-blindness-detection/train.csv\")\n    for i in train[1:]:\n        #y_this=[0.0,0.0,0.0,0.0,0.0]\n        #y_this[int(i[1])]=1.0\n        image_paths.append(image_dir+'/'+i[0]+'.png')\n        if int(i[1])==0:\n            labels.append(int(i[1]))\n        else:\n            labels.append(1)\n    return image_paths,labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img_dir = os.path.abspath('../input/aptos2019-blindness-detection/train_images')\nshuffix = \".png\"\nimg_paths, labels = get_datas(img_dir, suffix=shuffix) #获取到数据集中图像路径和图像的标签","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"unit"},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"utils.py - Helper functions for building the model and for loading model parameters.\n   These helper functions are built to mirror those in the official TensorFlow implementation.\n\"\"\"\n\n# Author: lukemelas (github username)\n# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch\n# With adjustments and added comments by workingcoder (github username).\n\nimport re\nimport math\nimport collections\nfrom functools import partial\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\nfrom torch.utils import model_zoo\n\n\n################################################################################\n### Help functions for model architecture\n################################################################################\n\n# GlobalParams and BlockArgs: Two namedtuples\n# Swish and MemoryEfficientSwish: Two implementations of the method\n# round_filters and round_repeats:\n#     Functions to calculate params for scaling model width and depth ! ! !\n# get_width_and_height_from_size and calculate_output_image_size\n# drop_connect: A structural design\n# get_same_padding_conv2d:\n#     Conv2dDynamicSamePadding\n#     Conv2dStaticSamePadding\n# get_same_padding_maxPool2d:\n#     MaxPool2dDynamicSamePadding\n#     MaxPool2dStaticSamePadding\n#     It's an additional function, not used in EfficientNet,\n#     but can be used in other model (such as EfficientDet).\n\n# Parameters for the entire model (stem, all blocks, and head)\nGlobalParams = collections.namedtuple('GlobalParams', [\n    'width_coefficient', 'depth_coefficient', 'image_size', 'dropout_rate',\n    'num_classes', 'batch_norm_momentum', 'batch_norm_epsilon',\n    'drop_connect_rate', 'depth_divisor', 'min_depth', 'include_top'])\n\n# Parameters for an individual model block\nBlockArgs = collections.namedtuple('BlockArgs', [\n    'num_repeat', 'kernel_size', 'stride', 'expand_ratio',\n    'input_filters', 'output_filters', 'se_ratio', 'id_skip'])\n\n# Set GlobalParams and BlockArgs's defaults\nGlobalParams.__new__.__defaults__ = (None,) * len(GlobalParams._fields)\nBlockArgs.__new__.__defaults__ = (None,) * len(BlockArgs._fields)\n\n\n# An ordinary implementation of Swish function\nclass Swish(nn.Module):\n    def forward(self, x):\n        return x * torch.sigmoid(x)\n\n\n# A memory-efficient implementation of Swish function\nclass SwishImplementation(torch.autograd.Function):\n    @staticmethod\n    def forward(ctx, i):\n        result = i * torch.sigmoid(i)\n        ctx.save_for_backward(i)\n        return result\n\n    @staticmethod\n    def backward(ctx, grad_output):\n        i = ctx.saved_tensors[0]\n        sigmoid_i = torch.sigmoid(i)\n        return grad_output * (sigmoid_i * (1 + i * (1 - sigmoid_i)))\n\nclass MemoryEfficientSwish(nn.Module):\n    def forward(self, x):\n        return SwishImplementation.apply(x)\n\n\ndef round_filters(filters, global_params):\n    \"\"\"Calculate and round number of filters based on width multiplier.\n       Use width_coefficient, depth_divisor and min_depth of global_params.\n\n    Args:\n        filters (int): Filters number to be calculated.\n        global_params (namedtuple): Global params of the model.\n\n    Returns:\n        new_filters: New filters number after calculating.\n    \"\"\"\n    multiplier = global_params.width_coefficient\n    if not multiplier:\n        return filters\n    # TODO: modify the params names.\n    #       maybe the names (width_divisor,min_width)\n    #       are more suitable than (depth_divisor,min_depth).\n    divisor = global_params.depth_divisor\n    min_depth = global_params.min_depth\n    filters *= multiplier\n    min_depth = min_depth or divisor # pay attention to this line when using min_depth\n    # follow the formula transferred from official TensorFlow implementation\n    new_filters = max(min_depth, int(filters + divisor / 2) // divisor * divisor)\n    if new_filters < 0.9 * filters: # prevent rounding by more than 10%\n        new_filters += divisor\n    return int(new_filters)\n\n\ndef round_repeats(repeats, global_params):\n    \"\"\"Calculate module's repeat number of a block based on depth multiplier.\n       Use depth_coefficient of global_params.\n\n    Args:\n        repeats (int): num_repeat to be calculated.\n        global_params (namedtuple): Global params of the model.\n\n    Returns:\n        new repeat: New repeat number after calculating.\n    \"\"\"\n    multiplier = global_params.depth_coefficient\n    if not multiplier:\n        return repeats\n    # follow the formula transferred from official TensorFlow implementation\n    return int(math.ceil(multiplier * repeats))\n\n\ndef drop_connect(inputs, p, training):\n    \"\"\"Drop connect.\n\n    Args:\n        input (tensor: BCWH): Input of this structure.\n        p (float: 0.0~1.0): Probability of drop connection.\n        training (bool): The running mode.\n\n    Returns:\n        output: Output after drop connection.\n    \"\"\"\n    assert 0 <= p <= 1, 'p must be in range of [0,1]'\n\n    if not training:\n        return inputs\n\n    batch_size = inputs.shape[0]\n    keep_prob = 1 - p\n\n    # generate binary_tensor mask according to probability (p for 0, 1-p for 1)\n    random_tensor = keep_prob\n    random_tensor += torch.rand([batch_size, 1, 1, 1], dtype=inputs.dtype, device=inputs.device)\n    binary_tensor = torch.floor(random_tensor)\n\n    output = inputs / keep_prob * binary_tensor\n    return output\n\n\ndef get_width_and_height_from_size(x):\n    \"\"\"Obtain height and width from x.\n\n    Args:\n        x (int, tuple or list): Data size.\n\n    Returns:\n        size: A tuple or list (H,W).\n    \"\"\"\n    if isinstance(x, int):\n        return x, x\n    if isinstance(x, list) or isinstance(x, tuple):\n        return x\n    else:\n        raise TypeError()\n\n\ndef calculate_output_image_size(input_image_size, stride):\n    \"\"\"Calculates the output image size when using Conv2dSamePadding with a stride.\n       Necessary for static padding. Thanks to mannatsingh for pointing this out.\n\n    Args:\n        input_image_size (int, tuple or list): Size of input image.\n        stride (int, tuple or list): Conv2d operation's stride.\n\n    Returns:\n        output_image_size: A list [H,W].\n    \"\"\"\n    if input_image_size is None:\n        return None\n    image_height, image_width = get_width_and_height_from_size(input_image_size)\n    stride = stride if isinstance(stride, int) else stride[0]\n    image_height = int(math.ceil(image_height / stride))\n    image_width = int(math.ceil(image_width / stride))\n    return [image_height, image_width]\n\n\n# Note:\n# The following 'SamePadding' functions make output size equal ceil(input size/stride).\n# Only when stride equals 1, can the output size be the same as input size.\n# Don't be confused by their function names ! ! !\n\ndef get_same_padding_conv2d(image_size=None):\n    \"\"\"Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n       Static padding is necessary for ONNX exporting of models.\n\n    Args:\n        image_size (int or tuple): Size of the image.\n\n    Returns:\n        Conv2dDynamicSamePadding or Conv2dStaticSamePadding.\n    \"\"\"\n    if image_size is None:\n        return Conv2dDynamicSamePadding\n    else:\n        return partial(Conv2dStaticSamePadding, image_size=image_size)\n\n\nclass Conv2dDynamicSamePadding(nn.Conv2d):\n    \"\"\"2D Convolutions like TensorFlow, for a dynamic image size.\n       The padding is operated in forward function by calculating dynamically.\n    \"\"\"\n\n    # Tips for 'SAME' mode padding.\n    #     Given the following:\n    #         i: width or height\n    #         s: stride\n    #         k: kernel size\n    #         d: dilation\n    #         p: padding\n    #     Output after Conv2d:\n    #         o = floor((i+p-((k-1)*d+1))/s+1)\n    # If o equals i, i = floor((i+p-((k-1)*d+1))/s+1),\n    # => p = (i-1)*s+((k-1)*d+1)-i\n\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, dilation=1, groups=1, bias=True):\n        super().__init__(in_channels, out_channels, kernel_size, stride, 0, dilation, groups, bias)\n        self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]] * 2\n\n    def forward(self, x):\n        ih, iw = x.size()[-2:]\n        kh, kw = self.weight.size()[-2:]\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih / sh), math.ceil(iw / sw) # change the output size according to stride ! ! !\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2])\n        return F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n\n\nclass Conv2dStaticSamePadding(nn.Conv2d):\n    \"\"\"2D Convolutions like TensorFlow's 'SAME' mode, with the given input image size.\n       The padding mudule is calculated in construction function, then used in forward.\n    \"\"\"\n\n    # With the same calculation as Conv2dDynamicSamePadding\n\n    def __init__(self, in_channels, out_channels, kernel_size, stride=1, image_size=None, **kwargs):\n        super().__init__(in_channels, out_channels, kernel_size, stride, **kwargs)\n        self.stride = self.stride if len(self.stride) == 2 else [self.stride[0]] * 2\n\n        # Calculate padding based on image size and save it\n        assert image_size is not None\n        ih, iw = (image_size, image_size) if isinstance(image_size, int) else image_size\n        kh, kw = self.weight.size()[-2:]\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            self.static_padding = nn.ZeroPad2d((pad_w - pad_w // 2, pad_w - pad_w // 2,\n                                                pad_h - pad_h // 2, pad_h - pad_h // 2))\n        else:\n            self.static_padding = nn.Identity()\n\n    def forward(self, x):\n        x = self.static_padding(x)\n        x = F.conv2d(x, self.weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n        return x\n\n\ndef get_same_padding_maxPool2d(image_size=None):\n    \"\"\"Chooses static padding if you have specified an image size, and dynamic padding otherwise.\n       Static padding is necessary for ONNX exporting of models.\n\n    Args:\n        image_size (int or tuple): Size of the image.\n\n    Returns:\n        MaxPool2dDynamicSamePadding or MaxPool2dStaticSamePadding.\n    \"\"\"\n    if image_size is None:\n        return MaxPool2dDynamicSamePadding\n    else:\n        return partial(MaxPool2dStaticSamePadding, image_size=image_size)\n\n\nclass MaxPool2dDynamicSamePadding(nn.MaxPool2d):\n    \"\"\"2D MaxPooling like TensorFlow's 'SAME' mode, with a dynamic image size.\n       The padding is operated in forward function by calculating dynamically.\n    \"\"\"\n\n    def __init__(self, kernel_size, stride, padding=0, dilation=1, return_indices=False, ceil_mode=False):\n        super().__init__(kernel_size, stride, padding, dilation, return_indices, ceil_mode)\n        self.stride = [self.stride] * 2 if isinstance(self.stride, int) else self.stride\n        self.kernel_size = [self.kernel_size] * 2 if isinstance(self.kernel_size, int) else self.kernel_size\n        self.dilation = [self.dilation] * 2 if isinstance(self.dilation, int) else self.dilation\n\n    def forward(self, x):\n        ih, iw = x.size()[-2:]\n        kh, kw = self.kernel_size\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            x = F.pad(x, [pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2])\n        return F.max_pool2d(x, self.kernel_size, self.stride, self.padding,\n                            self.dilation, self.ceil_mode, self.return_indices)\n\nclass MaxPool2dStaticSamePadding(nn.MaxPool2d):\n    \"\"\"2D MaxPooling like TensorFlow's 'SAME' mode, with the given input image size.\n       The padding mudule is calculated in construction function, then used in forward.\n    \"\"\"\n\n    def __init__(self, kernel_size, stride, image_size=None, **kwargs):\n        super().__init__(kernel_size, stride, **kwargs)\n        self.stride = [self.stride] * 2 if isinstance(self.stride, int) else self.stride\n        self.kernel_size = [self.kernel_size] * 2 if isinstance(self.kernel_size, int) else self.kernel_size\n        self.dilation = [self.dilation] * 2 if isinstance(self.dilation, int) else self.dilation\n\n        # Calculate padding based on image size and save it\n        assert image_size is not None\n        ih, iw = (image_size, image_size) if isinstance(image_size, int) else image_size\n        kh, kw = self.kernel_size\n        sh, sw = self.stride\n        oh, ow = math.ceil(ih / sh), math.ceil(iw / sw)\n        pad_h = max((oh - 1) * self.stride[0] + (kh - 1) * self.dilation[0] + 1 - ih, 0)\n        pad_w = max((ow - 1) * self.stride[1] + (kw - 1) * self.dilation[1] + 1 - iw, 0)\n        if pad_h > 0 or pad_w > 0:\n            self.static_padding = nn.ZeroPad2d((pad_w // 2, pad_w - pad_w // 2, pad_h // 2, pad_h - pad_h // 2))\n        else:\n            self.static_padding = nn.Identity()\n\n    def forward(self, x):\n        x = self.static_padding(x)\n        x = F.max_pool2d(x, self.kernel_size, self.stride, self.padding,\n                         self.dilation, self.ceil_mode, self.return_indices)\n        return x\n\n\n################################################################################\n### Helper functions for loading model params\n################################################################################\n\n# BlockDecoder: A Class for encoding and decoding BlockArgs\n# efficientnet_params: A function to query compound coefficient\n# get_model_params and efficientnet:\n#     Functions to get BlockArgs and GlobalParams for efficientnet\n# url_map and url_map_advprop: Dicts of url_map for pretrained weights\n# load_pretrained_weights: A function to load pretrained weights\n\nclass BlockDecoder(object):\n    \"\"\"Block Decoder for readability,\n       straight from the official TensorFlow repository.\n    \"\"\"\n\n    @staticmethod\n    def _decode_block_string(block_string):\n        \"\"\"Get a block through a string notation of arguments.\n\n        Args:\n            block_string (str): A string notation of arguments.\n                                Examples: 'r1_k3_s11_e1_i32_o16_se0.25_noskip'.\n\n        Returns:\n            BlockArgs: The namedtuple defined at the top of this file.\n        \"\"\"\n        assert isinstance(block_string, str)\n\n        ops = block_string.split('_')\n        options = {}\n        for op in ops:\n            splits = re.split(r'(\\d.*)', op)\n            if len(splits) >= 2:\n                key, value = splits[:2]\n                options[key] = value\n\n        # Check stride\n        assert (('s' in options and len(options['s']) == 1) or\n                (len(options['s']) == 2 and options['s'][0] == options['s'][1]))\n\n        return BlockArgs(\n            num_repeat=int(options['r']),\n            kernel_size=int(options['k']),\n            stride=[int(options['s'][0])],\n            expand_ratio=int(options['e']),\n            input_filters=int(options['i']),\n            output_filters=int(options['o']),\n            se_ratio=float(options['se']) if 'se' in options else None,\n            id_skip=('noskip' not in block_string))\n\n    @staticmethod\n    def _encode_block_string(block):\n        \"\"\"Encode a block to a string.\n\n        Args:\n            block (namedtuple): A BlockArgs type argument.\n\n        Returns:\n            block_string: A String form of BlockArgs.\n        \"\"\"\n        args = [\n            'r%d' % block.num_repeat,\n            'k%d' % block.kernel_size,\n            's%d%d' % (block.strides[0], block.strides[1]),\n            'e%s' % block.expand_ratio,\n            'i%d' % block.input_filters,\n            'o%d' % block.output_filters\n        ]\n        if 0 < block.se_ratio <= 1:\n            args.append('se%s' % block.se_ratio)\n        if block.id_skip is False:\n            args.append('noskip')\n        return '_'.join(args)\n\n    @staticmethod\n    def decode(string_list):\n        \"\"\"Decode a list of string notations to specify blocks inside the network.\n\n        Args:\n            string_list (list[str]): A list of strings, each string is a notation of block.\n\n        Returns:\n            blocks_args: A list of BlockArgs namedtuples of block args.\n        \"\"\"\n        assert isinstance(string_list, list)\n        blocks_args = []\n        for block_string in string_list:\n            blocks_args.append(BlockDecoder._decode_block_string(block_string))\n        return blocks_args\n\n    @staticmethod\n    def encode(blocks_args):\n        \"\"\"Encode a list of BlockArgs to a list of strings.\n\n        Args:\n            blocks_args (list[namedtuples]): A list of BlockArgs namedtuples of block args.\n\n        Returns:\n            block_strings: A list of strings, each string is a notation of block.\n        \"\"\"\n        block_strings = []\n        for block in blocks_args:\n            block_strings.append(BlockDecoder._encode_block_string(block))\n        return block_strings\n\n\ndef efficientnet_params(model_name):\n    \"\"\"Map EfficientNet model name to parameter coefficients.\n\n    Args:\n        model_name (str): Model name to be queried.\n\n    Returns:\n        params_dict[model_name]: A (width,depth,res,dropout) tuple.\n    \"\"\"\n    params_dict = {\n        # Coefficients:   width,depth,res,dropout\n        'efficientnet-b0': (1.0, 1.0, 224, 0.2),\n        'efficientnet-b1': (1.0, 1.1, 240, 0.2),\n        'efficientnet-b2': (1.1, 1.2, 260, 0.3),\n        'efficientnet-b3': (1.2, 1.4, 300, 0.3),\n        'efficientnet-b4': (1.4, 1.8, 380, 0.4),\n        'efficientnet-b5': (1.6, 2.2, 456, 0.4),\n        'efficientnet-b6': (1.8, 2.6, 528, 0.5),\n        'efficientnet-b7': (2.0, 3.1, 600, 0.5),\n        'efficientnet-b8': (2.2, 3.6, 672, 0.5),\n        'efficientnet-l2': (4.3, 5.3, 800, 0.5),\n    }\n    return params_dict[model_name]\n\n\ndef efficientnet(width_coefficient=None, depth_coefficient=None, image_size=None,\n                 dropout_rate=0.2, drop_connect_rate=0.2, num_classes=1000, include_top=True):\n    \"\"\"Create BlockArgs and GlobalParams for efficientnet model.\n\n    Args:\n        width_coefficient (float)\n        depth_coefficient (float)\n        image_size (int)\n        dropout_rate (float)\n        drop_connect_rate (float)\n        num_classes (int)\n\n        Meaning as the name suggests.\n\n    Returns:\n        blocks_args, global_params.\n    \"\"\"\n\n    # Blocks args for the whole model(efficientnet-b0 by default)\n    # It will be modified in the construction of EfficientNet Class according to model\n    blocks_args = [\n        'r1_k3_s11_e1_i32_o16_se0.25',\n        'r2_k3_s22_e6_i16_o24_se0.25',\n        'r2_k5_s22_e6_i24_o40_se0.25',\n        'r3_k3_s22_e6_i40_o80_se0.25',\n        'r3_k5_s11_e6_i80_o112_se0.25',\n        'r4_k5_s22_e6_i112_o192_se0.25',\n        'r1_k3_s11_e6_i192_o320_se0.25',\n    ]\n    blocks_args = BlockDecoder.decode(blocks_args)\n\n    global_params = GlobalParams(\n        width_coefficient=width_coefficient,\n        depth_coefficient=depth_coefficient,\n        image_size=image_size,\n        dropout_rate=dropout_rate,\n\n        num_classes=num_classes,\n        batch_norm_momentum=0.99,\n        batch_norm_epsilon=1e-3,\n        drop_connect_rate=drop_connect_rate,\n        depth_divisor=8,\n        min_depth=None,\n        include_top=include_top,\n    )\n\n    return blocks_args, global_params\n\n\ndef get_model_params(model_name, override_params):\n    \"\"\"Get the block args and global params for a given model name.\n\n    Args:\n        model_name (str): Model's name.\n        override_params (dict): A dict to modify global_params.\n\n    Returns:\n        blocks_args, global_params\n    \"\"\"\n    if model_name.startswith('efficientnet'):\n        w, d, s, p = efficientnet_params(model_name)\n        # note: all models have drop connect rate = 0.2\n        blocks_args, global_params = efficientnet(\n            width_coefficient=w, depth_coefficient=d, dropout_rate=p, image_size=s)\n    else:\n        raise NotImplementedError('model name is not pre-defined: {}'.format(model_name))\n    if override_params:\n        # ValueError will be raised here if override_params has fields not included in global_params.\n        global_params = global_params._replace(**override_params)\n    return blocks_args, global_params\n\n\n# train with Standard methods\n# check more details in paper(EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks)\nurl_map = {\n    'efficientnet-b0': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth',\n    'efficientnet-b1': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b1-f1951068.pth',\n    'efficientnet-b2': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b2-8bb594d6.pth',\n    'efficientnet-b3': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b3-5fb5a3c3.pth',\n    'efficientnet-b4': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b4-6ed6700e.pth',\n    'efficientnet-b5': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b5-b6417697.pth',\n    'efficientnet-b6': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b6-c76e70fd.pth',\n    'efficientnet-b7': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b7-dcc49843.pth',\n}\n\n# train with Adversarial Examples(AdvProp)\n# check more details in paper(Adversarial Examples Improve Image Recognition)\nurl_map_advprop = {\n    'efficientnet-b0': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b0-b64d5a18.pth',\n    'efficientnet-b1': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b1-0f3ce85a.pth',\n    'efficientnet-b2': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b2-6e9d97e5.pth',\n    'efficientnet-b3': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b3-cdd7c0f4.pth',\n    'efficientnet-b4': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b4-44fb3a87.pth',\n    'efficientnet-b5': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b5-86493f6b.pth',\n    'efficientnet-b6': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b6-ac80338e.pth',\n    'efficientnet-b7': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b7-4652b6dd.pth',\n    'efficientnet-b8': 'https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/adv-efficientnet-b8-22a8fe65.pth',\n}\n\n# TODO: add the petrained weights url map of 'efficientnet-l2'\n\n\ndef load_pretrained_weights(model, model_name, weights_path=None, load_fc=True, advprop=False):\n    \"\"\"Loads pretrained weights from weights path or download using url.\n\n    Args:\n        model (Module): The whole model of efficientnet.\n        model_name (str): Model name of efficientnet.\n        weights_path (None or str):\n            str: path to pretrained weights file on the local disk.\n            None: use pretrained weights downloaded from the Internet.\n        load_fc (bool): Whether to load pretrained weights for fc layer at the end of the model.\n        advprop (bool): Whether to load pretrained weights\n                        trained with advprop (valid when weights_path is None).\n    \"\"\"\n    if isinstance(weights_path, str):\n        save_model = torch.load(weights_path)\n        model_dict =  model.state_dict()\n        state_dict = {k:v for k,v in save_model.items() if k in model_dict.keys()}\n    else:\n        # AutoAugment or Advprop (different preprocessing)\n        url_map_ = url_map_advprop if advprop else url_map\n        save_model = model_zoo.load_url(url_map_[model_name])\n        model_dict =  model.state_dict()\n        state_dict = {k:v for k,v in save_model.items() if k in model_dict.keys()}\n    model_dict.update(state_dict)\n    if load_fc:\n        ret = model.load_state_dict(model_dict, strict=False)\n        assert not ret.missing_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys)\n    else:\n        state_dict.pop('_fc.weight')\n        state_dict.pop('_fc.bias')\n        ret = model.load_state_dict(model_dict, strict=False)\n        assert set(ret.missing_keys) == set(\n            ['_fc.weight', '_fc.bias']), 'Missing keys when loading pretrained weights: {}'.format(ret.missing_keys)\n    assert not ret.unexpected_keys, 'Missing keys when loading pretrained weights: {}'.format(ret.unexpected_keys)\n\n    print('Loaded pretrained weights for {}'.format(model_name))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"model"},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"model.py - Model and module class for EfficientNet.\n   They are built to mirror those in the official TensorFlow implementation.\n\"\"\"\n\n# Author: lukemelas (github username)\n# Github repo: https://github.com/lukemelas/EfficientNet-PyTorch\n# With adjustments and added comments by workingcoder (github username).\n\nimport torch\nfrom torch import nn\nfrom torch.nn import functional as F\n\nVALID_MODELS = (\n    'efficientnet-b0', 'efficientnet-b1', 'efficientnet-b2', 'efficientnet-b3',\n    'efficientnet-b4', 'efficientnet-b5', 'efficientnet-b6', 'efficientnet-b7',\n    'efficientnet-b8',\n\n    # Support the construction of 'efficientnet-l2' without pretrained weights\n    'efficientnet-l2'\n)\n\n\nclass MBConvBlock(nn.Module):\n    \"\"\"Mobile Inverted Residual Bottleneck Block.\n\n    Args:\n        block_args (namedtuple): BlockArgs, defined in utils.py.\n        global_params (namedtuple): GlobalParam, defined in utils.py.\n        image_size (tuple or list): [image_height, image_width].\n\n    References:\n        [1] https://arxiv.org/abs/1704.04861 (MobileNet v1)\n        [2] https://arxiv.org/abs/1801.04381 (MobileNet v2)\n        [3] https://arxiv.org/abs/1905.02244 (MobileNet v3)\n    \"\"\"\n\n    def __init__(self, block_args, global_params, image_size=None):\n        super().__init__()\n        self._block_args = block_args\n        self._bn_mom = 1 - global_params.batch_norm_momentum # pytorch's difference from tensorflow\n        self._bn_eps = global_params.batch_norm_epsilon\n        self.has_se = (self._block_args.se_ratio is not None) and (0 < self._block_args.se_ratio <= 1)\n        self.id_skip = block_args.id_skip  # whether to use skip connection and drop connect\n\n        # Expansion phase (Inverted Bottleneck)\n        inp = self._block_args.input_filters  # number of input channels\n        oup = self._block_args.input_filters * self._block_args.expand_ratio  # number of output channels\n        if self._block_args.expand_ratio != 1:\n            Conv2d = get_same_padding_conv2d(image_size=image_size)\n            self._expand_conv = Conv2d(in_channels=inp, out_channels=oup, kernel_size=1, bias=False)\n            self._bn0 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n            # image_size = calculate_output_image_size(image_size, 1) <-- this wouldn't modify image_size\n\n        # Depthwise convolution phase\n        k = self._block_args.kernel_size\n        s = self._block_args.stride\n        Conv2d = get_same_padding_conv2d(image_size=image_size)\n        self._depthwise_conv = Conv2d(\n            in_channels=oup, out_channels=oup, groups=oup,  # groups makes it depthwise\n            kernel_size=k, stride=s, bias=False)\n        self._bn1 = nn.BatchNorm2d(num_features=oup, momentum=self._bn_mom, eps=self._bn_eps)\n        image_size = calculate_output_image_size(image_size, s)\n\n        # Squeeze and Excitation layer, if desired\n        if self.has_se:\n            Conv2d = get_same_padding_conv2d(image_size=(1, 1))\n            num_squeezed_channels = max(1, int(self._block_args.input_filters * self._block_args.se_ratio))\n            self._se_reduce = Conv2d(in_channels=oup, out_channels=num_squeezed_channels, kernel_size=1)\n            self._se_expand = Conv2d(in_channels=num_squeezed_channels, out_channels=oup, kernel_size=1)\n\n        # Pointwise convolution phase\n        final_oup = self._block_args.output_filters\n        Conv2d = get_same_padding_conv2d(image_size=image_size)\n        self._project_conv = Conv2d(in_channels=oup, out_channels=final_oup, kernel_size=1, bias=False)\n        self._bn2 = nn.BatchNorm2d(num_features=final_oup, momentum=self._bn_mom, eps=self._bn_eps)\n        self._swish = MemoryEfficientSwish()\n\n    def forward(self, inputs, drop_connect_rate=None):\n        \"\"\"MBConvBlock's forward function.\n\n        Args:\n            inputs (tensor): Input tensor.\n            drop_connect_rate (bool): Drop connect rate (float, between 0 and 1).\n\n        Returns:\n            Output of this block after processing.\n        \"\"\"\n\n        # Expansion and Depthwise Convolution\n        x = inputs\n        if self._block_args.expand_ratio != 1:\n            x = self._expand_conv(inputs)\n            x = self._bn0(x)\n            x = self._swish(x)\n\n        x = self._depthwise_conv(x)\n        x = self._bn1(x)\n        x = self._swish(x)\n\n        # Squeeze and Excitation\n        if self.has_se:\n            x_squeezed = F.adaptive_avg_pool2d(x, 1)\n            x_squeezed = self._se_reduce(x_squeezed)\n            x_squeezed = self._swish(x_squeezed)\n            x_squeezed = self._se_expand(x_squeezed)\n            x = torch.sigmoid(x_squeezed) * x\n\n        # Pointwise Convolution\n        x = self._project_conv(x)\n        x = self._bn2(x)\n\n        # Skip connection and drop connect\n        input_filters, output_filters = self._block_args.input_filters, self._block_args.output_filters\n        if self.id_skip and self._block_args.stride == 1 and input_filters == output_filters:\n            # The combination of skip connection and drop connect brings about stochastic depth.\n            if drop_connect_rate:\n                x = drop_connect(x, p=drop_connect_rate, training=self.training)\n            x = x + inputs  # skip connection\n        return x\n\n    def set_swish(self, memory_efficient=True):\n        \"\"\"Sets swish function as memory efficient (for training) or standard (for export).\n\n        Args:\n            memory_efficient (bool): Whether to use memory-efficient version of swish.\n        \"\"\"\n        self._swish = MemoryEfficientSwish() if memory_efficient else Swish()\n\n\nclass EfficientNet(nn.Module):\n    \"\"\"EfficientNet model.\n       Most easily loaded with the .from_name or .from_pretrained methods.\n\n    Args:\n        blocks_args (list[namedtuple]): A list of BlockArgs to construct blocks.\n        global_params (namedtuple): A set of GlobalParams shared between blocks.\n\n    References:\n        [1] https://arxiv.org/abs/1905.11946 (EfficientNet)\n\n    Example:\n        \n        \n        import torch\n        >>> from efficientnet.model import EfficientNet\n        >>> inputs = torch.rand(1, 3, 224, 224)\n        >>> model = EfficientNet.from_pretrained('efficientnet-b0')\n        >>> model.eval()\n        >>> outputs = model(inputs)\n    \"\"\"\n\n    def __init__(self, blocks_args=None, global_params=None):\n        super().__init__()\n        assert isinstance(blocks_args, list), 'blocks_args should be a list'\n        assert len(blocks_args) > 0, 'block args must be greater than 0'\n        self._global_params = global_params\n        self._blocks_args = blocks_args\n\n        # Batch norm parameters\n        bn_mom = 1 - self._global_params.batch_norm_momentum\n        bn_eps = self._global_params.batch_norm_epsilon\n\n        # Get stem static or dynamic convolution depending on image size\n        image_size = global_params.image_size\n        Conv2d = get_same_padding_conv2d(image_size=image_size)\n\n        # Stem\n        in_channels = 3  # rgb\n        out_channels = round_filters(32, self._global_params)  # number of output channels\n        self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)\n        self._bn0 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n        image_size = calculate_output_image_size(image_size, 2)\n\n        # Build blocks\n        self._blocks = nn.ModuleList([])\n        for block_args in self._blocks_args:\n\n            # Update block input and output filters based on depth multiplier.\n            block_args = block_args._replace(\n                input_filters=round_filters(block_args.input_filters, self._global_params),\n                output_filters=round_filters(block_args.output_filters, self._global_params),\n                num_repeat=round_repeats(block_args.num_repeat, self._global_params)\n            )\n\n            # The first block needs to take care of stride and filter size increase.\n            self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size))\n            image_size = calculate_output_image_size(image_size, block_args.stride)\n            if block_args.num_repeat > 1: # modify block_args to keep same output size\n                block_args = block_args._replace(input_filters=block_args.output_filters, stride=1)\n            for _ in range(block_args.num_repeat - 1):\n                self._blocks.append(MBConvBlock(block_args, self._global_params, image_size=image_size))\n                # image_size = calculate_output_image_size(image_size, block_args.stride)  # stride = 1\n\n        # Head\n        in_channels = block_args.output_filters  # output of final block\n        out_channels = round_filters(1280, self._global_params)\n        Conv2d = get_same_padding_conv2d(image_size=image_size)\n        self._conv_head = Conv2d(in_channels, out_channels, kernel_size=1, bias=False)\n        self._bn1 = nn.BatchNorm2d(num_features=out_channels, momentum=bn_mom, eps=bn_eps)\n\n        # Final linear layer\n        self._avg_pooling = nn.AdaptiveAvgPool2d(1)\n        self._dropout = nn.Dropout(self._global_params.dropout_rate)\n        self._fc = nn.Linear(out_channels, self._global_params.num_classes)\n        self._swish = MemoryEfficientSwish()\n\n    def set_swish(self, memory_efficient=True):\n        \"\"\"Sets swish function as memory efficient (for training) or standard (for export).\n\n        Args:\n            memory_efficient (bool): Whether to use memory-efficient version of swish.\n\n        \"\"\"\n        self._swish = MemoryEfficientSwish() if memory_efficient else Swish()\n        for block in self._blocks:\n            block.set_swish(memory_efficient)\n\n    def extract_endpoints(self, inputs):\n        \"\"\"Use convolution layer to extract features\n        from reduction levels i in [1, 2, 3, 4, 5].\n\n        Args:\n            inputs (tensor): Input tensor.\n\n        Returns:\n            Dictionary of last intermediate features\n            with reduction levels i in [1, 2, 3, 4, 5].\n            Example:\n                >>> import torch\n                >>> from efficientnet.model import EfficientNet\n                >>> inputs = torch.rand(1, 3, 224, 224)\n                >>> model = EfficientNet.from_pretrained('efficientnet-b0')\n                >>> endpoints = model.extract_endpoints(inputs)\n                >>> print(endpoints['reduction_1'].shape)  # torch.Size([1, 16, 112, 112])\n                >>> print(endpoints['reduction_2'].shape)  # torch.Size([1, 24, 56, 56])\n                >>> print(endpoints['reduction_3'].shape)  # torch.Size([1, 40, 28, 28])\n                >>> print(endpoints['reduction_4'].shape)  # torch.Size([1, 112, 14, 14])\n                >>> print(endpoints['reduction_5'].shape)  # torch.Size([1, 1280, 7, 7])\n        \"\"\"\n        endpoints = dict()\n\n        # Stem\n        x = self._swish(self._bn0(self._conv_stem(inputs)))\n        prev_x = x\n\n        # Blocks\n        for idx, block in enumerate(self._blocks):\n            drop_connect_rate = self._global_params.drop_connect_rate\n            if drop_connect_rate:\n                drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate\n            x = block(x, drop_connect_rate=drop_connect_rate)\n            if prev_x.size(2) > x.size(2):\n                endpoints['reduction_{}'.format(len(endpoints)+1)] = prev_x\n            prev_x = x\n\n        # Head\n        x = self._swish(self._bn1(self._conv_head(x)))\n        endpoints['reduction_{}'.format(len(endpoints)+1)] = x\n\n        return endpoints\n\n    def extract_features(self, inputs):\n        \"\"\"use convolution layer to extract feature .\n\n        Args:\n            inputs (tensor): Input tensor.\n\n        Returns:\n            Output of the final convolution\n            layer in the efficientnet model.\n        \"\"\"\n        # Stem\n        x = self._swish(self._bn0(self._conv_stem(inputs)))\n\n        # Blocks\n        for idx, block in enumerate(self._blocks):\n            drop_connect_rate = self._global_params.drop_connect_rate\n            if drop_connect_rate:\n                drop_connect_rate *= float(idx) / len(self._blocks) # scale drop connect_rate\n            x = block(x, drop_connect_rate=drop_connect_rate)\n\n        # Head\n        x = self._swish(self._bn1(self._conv_head(x)))\n\n        return x\n\n    def forward(self, inputs):\n        \"\"\"EfficientNet's forward function.\n           Calls extract_features to extract features, applies final linear layer, and returns logits.\n\n        Args:\n            inputs (tensor): Input tensor.\n\n        Returns:\n            Output of this model after processing.\n        \"\"\"\n        # Convolution layers\n        x = self.extract_features(inputs)\n        # Pooling and final linear layer\n        x = self._avg_pooling(x)\n        if self._global_params.include_top:\n            x = x.flatten(start_dim=1)\n            x = self._dropout(x)\n            x = self._fc(x)\n        return x\n\n    @classmethod\n    def from_name(cls, model_name, in_channels=3, **override_params):\n        \"\"\"create an efficientnet model according to name.\n\n        Args:\n            model_name (str): Name for efficientnet.\n            in_channels (int): Input data's channel number.\n            override_params (other key word params):\n                Params to override model's global_params.\n                Optional key:\n                    'width_coefficient', 'depth_coefficient',\n                    'image_size', 'dropout_rate',\n                    'num_classes', 'batch_norm_momentum',\n                    'batch_norm_epsilon', 'drop_connect_rate',\n                    'depth_divisor', 'min_depth'\n\n        Returns:\n            An efficientnet model.\n        \"\"\"\n        cls._check_model_name_is_valid(model_name)\n        blocks_args, global_params = get_model_params(model_name, override_params)\n        model = cls(blocks_args, global_params)\n        model._change_in_channels(in_channels)\n        return model\n\n    @classmethod\n    def from_pretrained(cls, model_name, weights_path=None, advprop=False,\n                        in_channels=3, num_classes=1000, **override_params):\n        \"\"\"create an efficientnet model according to name.\n\n        Args:\n            model_name (str): Name for efficientnet.\n            weights_path (None or str):\n                str: path to pretrained weights file on the local disk.\n                None: use pretrained weights downloaded from the Internet.\n            advprop (bool):\n                Whether to load pretrained weights\n                trained with advprop (valid when weights_path is None).\n            in_channels (int): Input data's channel number.\n            num_classes (int):\n                Number of categories for classification.\n                It controls the output size for final linear layer.\n            override_params (other key word params):\n                Params to override model's global_params.\n                Optional key:\n                    'width_coefficient', 'depth_coefficient',\n                    'image_size', 'dropout_rate',\n                    'batch_norm_momentum',\n                    'batch_norm_epsilon', 'drop_connect_rate',\n                    'depth_divisor', 'min_depth'\n\n        Returns:\n            A pretrained efficientnet model.\n        \"\"\"\n        model = cls.from_name(model_name, num_classes=num_classes, **override_params)\n        load_pretrained_weights(model, model_name, weights_path=weights_path, load_fc=(num_classes == 1000), advprop=advprop)\n        model._change_in_channels(in_channels)\n        return model\n\n    @classmethod\n    def get_image_size(cls, model_name):\n        \"\"\"Get the input image size for a given efficientnet model.\n\n        Args:\n            model_name (str): Name for efficientnet.\n\n        Returns:\n            Input image size (resolution).\n        \"\"\"\n        cls._check_model_name_is_valid(model_name)\n        _, _, res, _ = efficientnet_params(model_name)\n        return res\n\n    @classmethod\n    def _check_model_name_is_valid(cls, model_name):\n        \"\"\"Validates model name.\n\n        Args:\n            model_name (str): Name for efficientnet.\n\n        Returns:\n            bool: Is a valid name or not.\n        \"\"\"\n        if model_name not in VALID_MODELS:\n            raise ValueError('model_name should be one of: ' + ', '.join(VALID_MODELS))\n\n    def _change_in_channels(self, in_channels):\n        \"\"\"Adjust model's first convolution layer to in_channels, if in_channels not equals 3.\n\n        Args:\n            in_channels (int): Input data's channel number.\n        \"\"\"\n        if in_channels != 3:\n            Conv2d = get_same_padding_conv2d(image_size=self._global_params.image_size)\n            out_channels = round_filters(32, self._global_params)\n            self._conv_stem = Conv2d(in_channels, out_channels, kernel_size=3, stride=2, bias=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from torch.utils.data import Dataset\n\nclass EyeDataset(Dataset):\n    def __init__(self, img_paths, labels, gray=False, transform=None):\n        super(EyeDataset, self).__init__()\n        self.img_paths = img_paths\n        self.labels = labels\n        self.gray = gray\n        self.transform = transform\n        self.length = len(img_paths)\n    \n    def __len__(self):\n        return self.length\n    \n    def __getitem__(self, index):\n        img_path = self.img_paths[index]\n        label = self.labels[index]\n        img = Image.open(img_path)\n        if self.gray:\n            img.convert(\"L\")\n        else:\n            img.convert(\"RGB\")\n        \n        if self.transform is not None:\n            img = self.transform(img)\n        \n        return img, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#划分验证集和训练集\nfrom torch.utils.data.sampler import WeightedRandomSampler\nfrom sklearn.model_selection import train_test_split\ntrain_paths, val_paths, train_labels, val_labels = train_test_split(img_paths, labels, test_size=0.3, random_state=0, stratify=labels)\n#定义训练数据集对象和验证数据集对象\nimg_size = 224\ntrain_transform = tsf.Compose([\n    tsf.Resize((img_size, img_size)),\n    tsf.RandomHorizontalFlip(),\n    tsf.RandomVerticalFlip(),\n    tsf.ToTensor(),\n    tsf.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\nval_transform = tsf.Compose([\n    tsf.Resize((img_size, img_size)),\n    tsf.ToTensor(),\n    tsf.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])\n])\ntrain_dataset =EyeDataset(train_paths, torch.tensor(train_labels), transform=train_transform)\nval_dataset = EyeDataset(val_paths, torch.tensor(val_labels), transform=val_transform)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#定义训练集和测试集的加载器\nfrom torch.utils.data import DataLoader\nwights=[]\ntrain_time=[1,5,2,9,6]\nfor i in train_labels:\n    wights.append(train_time[int(i)])\nsampler = WeightedRandomSampler(wights, len(wights),replacement=True)\ntrain_loader = DataLoader(train_dataset, shuffle=False, batch_size=8, num_workers=4, sampler=sampler) #备注：在windows系统中多线程可能存在问题，所以设置num_workers为0\nval_loader = DataLoader(val_dataset, shuffle=False, batch_size=1, num_workers=4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def train_for(x,label,opt,model,losses,total,number,count):\n    for _ in range(number):\n        x = x.to(device, dtype=torch.float32)\n        label = label.to(device, dtype=torch.long)\n        batch = x.size(0)\n        total += batch\n        opt.zero_grad() #清除累积的梯度\n        pred = model(x)\n        loss = criterion(pred, label)\n        loss.backward()\n        pred = torch.max(pred, dim=1)[1]\n        for i in range(len(pred)):\n            if int(pred[i])==int(label[i]):\n                count+=1\n        if total%128==0:\n            print(loss)\n            print(total)\n            print(\"acc: \"+str(count/128))\n            count=0\n        opt.step() #更新权重\n        losses += loss.item() * batch\n    return opt,model,losses,total,count","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import random\nmodel = EfficientNet.from_pretrained('efficientnet-b7')\nfeature = model._fc.in_features\nmodel._fc = nn.Linear(in_features=feature,out_features=2,bias=True)\nopt = torch.optim.SGD(model.parameters(),lr=0.004, momentum=0.9, nesterov=True)\nscheduler = torch.optim.lr_scheduler.StepLR(opt, step_size = 5, gamma = 0.1, last_epoch=-1)\ncriterion = nn.CrossEntropyLoss()\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\nmodel.to(device)\nfor __ in range(1):\n    for epoch in range(30):\n        losses = 0.0\n        total = 0\n        count=0\n        corrects = 0\n        model.train()\n        for x, label in train_loader:\n            opt,model,losses,total,count=train_for(x,label,opt,model,losses,total,1,count)\n        print(\"avg loss: \"+str(losses))\n        scheduler.step()\n        #在验证集上验证模型的效果\ntorch.save(model,\"./model.pkl\")\ntorch.save(model.state_dict(),\"model.pth\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.eval()\nwith torch.no_grad():\n    losses = 0.0\n    total = 0\n    corrects = 0\n    tbie=[0,0,0,0,0]\n    bie=[0,0,0,0,0]\n    pre=[0,0,0,0,0]\n    count=0\n    for x, label in val_loader:\n        x = x.to(device, dtype=torch.float32)          \n        label = label.to(device, dtype=torch.long)\n        batch = x.size(0)\n        total += batch\n        pred = model(x)\n        pred = torch.max(pred, dim=1)[1]\n        for i in range(len(pred)):\n            if int(pred[i])==int(label[i]):\n                count+=1\n        if total%128==0:\n            print(total)\n            print(\"acc: \"+str(count))\n            count=0\n        for i in range(len(pred)):\n            cc=pred[i]\n            cd=label[i]\n            tbie[int(cd)]+=1\n            if int(cc)==int(cd):\n                corrects=corrects+1\n                bie[int(cc)]+=1\n    print(\"correct: \"+str(corrects/total))\n    for z in range(5):\n        print(\"class \"+str(z)+\" correct \"+str(bie[z]/tbie[z]))\n    print(bie)","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}