Dataset Preview Go to dataset viewer
nwo (string)sha (string)path (string)language (string)identifier (string)parameters (string)argument_list (string)return_statement (string)docstring (string)docstring_summary (string)docstring_tokens (json)function (string)function_tokens (json)url (string)
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/nasnet.py
python
nasnetalarge
(num_classes=1001, pretrained='imagenet')
return model
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
def nasnetalarge(num_classes=1001, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetalarge'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetALarge(num_classes=1001) model.load_state_dict(model_zoo.load_url(settings['url'])) if pretrained == 'imagenet': new_last_linear = nn.Linear(model.last_linear.in_features, 1000) new_last_linear.weight.data = model.last_linear.weight.data[1:] new_last_linear.bias.data = model.last_linear.bias.data[1:] model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = NASNetALarge(num_classes=num_classes) return model
[ "def", "nasnetalarge", "(", "num_classes", "=", "1001", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetalarge'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "# both 'imagenet'&'imagenet+background' are loaded from same parameters", "model", "=", "NASNetALarge", "(", "num_classes", "=", "1001", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "if", "pretrained", "==", "'imagenet'", ":", "new_last_linear", "=", "nn", ".", "Linear", "(", "model", ".", "last_linear", ".", "in_features", ",", "1000", ")", "new_last_linear", ".", "weight", ".", "data", "=", "model", ".", "last_linear", ".", "weight", ".", "data", "[", "1", ":", "]", "new_last_linear", ".", "bias", ".", "data", "=", "model", ".", "last_linear", ".", "bias", ".", "data", "[", "1", ":", "]", "model", ".", "last_linear", "=", "new_last_linear", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "else", ":", "model", "=", "NASNetALarge", "(", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/nasnet.py#L608-L635
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/bninception.py
python
bninception
(num_classes=1000, pretrained='imagenet')
return model
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper.
[ "r", "BNInception", "model", "architecture", "from", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1502", ".", "03167", ".", "pdf", ">", "_", "paper", "." ]
def bninception(num_classes=1000, pretrained='imagenet'): r"""BNInception model architecture from <https://arxiv.org/pdf/1502.03167.pdf>`_ paper. """ model = BNInception(num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['bninception'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "def", "bninception", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "BNInception", "(", "num_classes", "=", "num_classes", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'bninception'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/bninception.py#L497-L511
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
alexnet
(num_classes=1000, pretrained='imagenet')
return model
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper.
[ "r", "AlexNet", "model", "architecture", "from", "the", "One", "weird", "trick", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1404", ".", "5997", ">", "_", "paper", "." ]
def alexnet(num_classes=1000, pretrained='imagenet'): r"""AlexNet model architecture from the `"One weird trick..." <https://arxiv.org/abs/1404.5997>`_ paper. """ # https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py model = models.alexnet(pretrained=False) if pretrained is not None: settings = pretrained_settings['alexnet'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_alexnet(model) return model
[ "def", "alexnet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "# https://github.com/pytorch/vision/blob/master/torchvision/models/alexnet.py", "model", "=", "models", ".", "alexnet", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'alexnet'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_alexnet", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L168-L178
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
densenet121
(num_classes=1000, pretrained='imagenet')
return model
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
[ "r", "Densenet", "-", "121", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
def densenet121(num_classes=1000, pretrained='imagenet'): r"""Densenet-121 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet121(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet121'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
[ "def", "densenet121", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet121", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'densenet121'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_densenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L205-L214
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
densenet169
(num_classes=1000, pretrained='imagenet')
return model
r"""Densenet-169 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
r"""Densenet-169 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
[ "r", "Densenet", "-", "169", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
def densenet169(num_classes=1000, pretrained='imagenet'): r"""Densenet-169 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet169(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet169'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
[ "def", "densenet169", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet169", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'densenet169'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_densenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L216-L225
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
densenet201
(num_classes=1000, pretrained='imagenet')
return model
r"""Densenet-201 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
r"""Densenet-201 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
[ "r", "Densenet", "-", "201", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
def densenet201(num_classes=1000, pretrained='imagenet'): r"""Densenet-201 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet201(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet201'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
[ "def", "densenet201", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet201", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'densenet201'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_densenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L227-L236
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
densenet161
(num_classes=1000, pretrained='imagenet')
return model
r"""Densenet-161 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
r"""Densenet-161 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>`
[ "r", "Densenet", "-", "161", "model", "from", "Densely", "Connected", "Convolutional", "Networks", "<https", ":", "//", "arxiv", ".", "org", "/", "pdf", "/", "1608", ".", "06993", ".", "pdf", ">" ]
def densenet161(num_classes=1000, pretrained='imagenet'): r"""Densenet-161 model from `"Densely Connected Convolutional Networks" <https://arxiv.org/pdf/1608.06993.pdf>` """ model = models.densenet161(pretrained=False) if pretrained is not None: settings = pretrained_settings['densenet161'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_densenets(model) return model
[ "def", "densenet161", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "densenet161", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'densenet161'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_densenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L238-L247
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
inceptionv3
(num_classes=1000, pretrained='imagenet')
return model
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.
r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_.
[ "r", "Inception", "v3", "model", "architecture", "from", "Rethinking", "the", "Inception", "Architecture", "for", "Computer", "Vision", "<http", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1512", ".", "00567", ">", "_", "." ]
def inceptionv3(num_classes=1000, pretrained='imagenet'): r"""Inception v3 model architecture from `"Rethinking the Inception Architecture for Computer Vision" <http://arxiv.org/abs/1512.00567>`_. """ model = models.inception_v3(pretrained=False) if pretrained is not None: settings = pretrained_settings['inceptionv3'][pretrained] model = load_pretrained(model, num_classes, settings) # Modify attributs model.last_linear = model.fc del model.fc def features(self, input): # 299 x 299 x 3 x = self.Conv2d_1a_3x3(input) # 149 x 149 x 32 x = self.Conv2d_2a_3x3(x) # 147 x 147 x 32 x = self.Conv2d_2b_3x3(x) # 147 x 147 x 64 x = F.max_pool2d(x, kernel_size=3, stride=2) # 73 x 73 x 64 x = self.Conv2d_3b_1x1(x) # 73 x 73 x 80 x = self.Conv2d_4a_3x3(x) # 71 x 71 x 192 x = F.max_pool2d(x, kernel_size=3, stride=2) # 35 x 35 x 192 x = self.Mixed_5b(x) # 35 x 35 x 256 x = self.Mixed_5c(x) # 35 x 35 x 288 x = self.Mixed_5d(x) # 35 x 35 x 288 x = self.Mixed_6a(x) # 17 x 17 x 768 x = self.Mixed_6b(x) # 17 x 17 x 768 x = self.Mixed_6c(x) # 17 x 17 x 768 x = self.Mixed_6d(x) # 17 x 17 x 768 x = self.Mixed_6e(x) # 17 x 17 x 768 if self.training and self.aux_logits: self._out_aux = self.AuxLogits(x) # 17 x 17 x 768 x = self.Mixed_7a(x) # 8 x 8 x 1280 x = self.Mixed_7b(x) # 8 x 8 x 2048 x = self.Mixed_7c(x) # 8 x 8 x 2048 return x def logits(self, features): x = F.avg_pool2d(features, kernel_size=8) # 1 x 1 x 2048 x = F.dropout(x, training=self.training) # 1 x 1 x 2048 x = x.view(x.size(0), -1) # 2048 x = self.last_linear(x) # 1000 (num_classes) if self.training and self.aux_logits: aux = self._out_aux self._out_aux = None return x, aux return x def forward(self, input): x = self.features(input) x = self.logits(x) return x # Modify methods model.features = types.MethodType(features, model) model.logits = types.MethodType(logits, model) model.forward = types.MethodType(forward, model) return model
[ "def", "inceptionv3", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "inception_v3", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'inceptionv3'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "# Modify attributs", "model", ".", "last_linear", "=", "model", ".", "fc", "del", "model", ".", "fc", "def", "features", "(", "self", ",", "input", ")", ":", "# 299 x 299 x 3", "x", "=", "self", ".", "Conv2d_1a_3x3", "(", "input", ")", "# 149 x 149 x 32", "x", "=", "self", ".", "Conv2d_2a_3x3", "(", "x", ")", "# 147 x 147 x 32", "x", "=", "self", ".", "Conv2d_2b_3x3", "(", "x", ")", "# 147 x 147 x 64", "x", "=", "F", ".", "max_pool2d", "(", "x", ",", "kernel_size", "=", "3", ",", "stride", "=", "2", ")", "# 73 x 73 x 64", "x", "=", "self", ".", "Conv2d_3b_1x1", "(", "x", ")", "# 73 x 73 x 80", "x", "=", "self", ".", "Conv2d_4a_3x3", "(", "x", ")", "# 71 x 71 x 192", "x", "=", "F", ".", "max_pool2d", "(", "x", ",", "kernel_size", "=", "3", ",", "stride", "=", "2", ")", "# 35 x 35 x 192", "x", "=", "self", ".", "Mixed_5b", "(", "x", ")", "# 35 x 35 x 256", "x", "=", "self", ".", "Mixed_5c", "(", "x", ")", "# 35 x 35 x 288", "x", "=", "self", ".", "Mixed_5d", "(", "x", ")", "# 35 x 35 x 288", "x", "=", "self", ".", "Mixed_6a", "(", "x", ")", "# 17 x 17 x 768", "x", "=", "self", ".", "Mixed_6b", "(", "x", ")", "# 17 x 17 x 768", "x", "=", "self", ".", "Mixed_6c", "(", "x", ")", "# 17 x 17 x 768", "x", "=", "self", ".", "Mixed_6d", "(", "x", ")", "# 17 x 17 x 768", "x", "=", "self", ".", "Mixed_6e", "(", "x", ")", "# 17 x 17 x 768", "if", "self", ".", "training", "and", "self", ".", "aux_logits", ":", "self", ".", "_out_aux", "=", "self", ".", "AuxLogits", "(", "x", ")", "# 17 x 17 x 768", "x", "=", "self", ".", "Mixed_7a", "(", "x", ")", "# 8 x 8 x 1280", "x", "=", "self", ".", "Mixed_7b", "(", "x", ")", "# 8 x 8 x 2048", "x", "=", "self", ".", "Mixed_7c", "(", "x", ")", "# 8 x 8 x 2048", "return", "x", "def", "logits", "(", "self", ",", "features", ")", ":", "x", "=", "F", ".", "avg_pool2d", "(", "features", ",", "kernel_size", "=", "8", ")", "# 1 x 1 x 2048", "x", "=", "F", ".", "dropout", "(", "x", ",", "training", "=", "self", ".", "training", ")", "# 1 x 1 x 2048", "x", "=", "x", ".", "view", "(", "x", ".", "size", "(", "0", ")", ",", "-", "1", ")", "# 2048", "x", "=", "self", ".", "last_linear", "(", "x", ")", "# 1000 (num_classes)", "if", "self", ".", "training", "and", "self", ".", "aux_logits", ":", "aux", "=", "self", ".", "_out_aux", "self", ".", "_out_aux", "=", "None", "return", "x", ",", "aux", "return", "x", "def", "forward", "(", "self", ",", "input", ")", ":", "x", "=", "self", ".", "features", "(", "input", ")", "x", "=", "self", ".", "logits", "(", "x", ")", "return", "x", "# Modify methods", "model", ".", "features", "=", "types", ".", "MethodType", "(", "features", ",", "model", ")", "model", ".", "logits", "=", "types", ".", "MethodType", "(", "logits", ",", "model", ")", "model", ".", "forward", "=", "types", ".", "MethodType", "(", "forward", ",", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L252-L309
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
resnet18
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-18 model.
Constructs a ResNet-18 model.
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
def resnet18(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-18 model. """ model = models.resnet18(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet18'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "def", "resnet18", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet18", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'resnet18'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_resnets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L348-L356
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
resnet34
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-34 model.
Constructs a ResNet-34 model.
[ "Constructs", "a", "ResNet", "-", "34", "model", "." ]
def resnet34(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-34 model. """ model = models.resnet34(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet34'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "def", "resnet34", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet34", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'resnet34'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_resnets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L358-L366
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
resnet50
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-50 model.
Constructs a ResNet-50 model.
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
def resnet50(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-50 model. """ model = models.resnet50(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet50'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "def", "resnet50", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet50", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'resnet50'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_resnets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L368-L376
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
resnet101
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-101 model.
Constructs a ResNet-101 model.
[ "Constructs", "a", "ResNet", "-", "101", "model", "." ]
def resnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. """ model = models.resnet101(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet101'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "def", "resnet101", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet101", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'resnet101'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_resnets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L378-L386
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
resnet152
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-152 model.
Constructs a ResNet-152 model.
[ "Constructs", "a", "ResNet", "-", "152", "model", "." ]
def resnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. """ model = models.resnet152(pretrained=False) if pretrained is not None: settings = pretrained_settings['resnet152'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_resnets(model) return model
[ "def", "resnet152", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "resnet152", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'resnet152'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_resnets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L388-L396
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
squeezenet1_0
(num_classes=1000, pretrained='imagenet')
return model
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper.
r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper.
[ "r", "SqueezeNet", "model", "architecture", "from", "the", "SqueezeNet", ":", "AlexNet", "-", "level", "accuracy", "with", "50x", "fewer", "parameters", "and", "<0", ".", "5MB", "model", "size", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07360", ">", "_", "paper", "." ]
def squeezenet1_0(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet model architecture from the `"SqueezeNet: AlexNet-level accuracy with 50x fewer parameters and <0.5MB model size" <https://arxiv.org/abs/1602.07360>`_ paper. """ model = models.squeezenet1_0(pretrained=False) if pretrained is not None: settings = pretrained_settings['squeezenet1_0'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_squeezenets(model) return model
[ "def", "squeezenet1_0", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "squeezenet1_0", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'squeezenet1_0'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_squeezenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L428-L438
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
squeezenet1_1
(num_classes=1000, pretrained='imagenet')
return model
r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy.
r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy.
[ "r", "SqueezeNet", "1", ".", "1", "model", "from", "the", "official", "SqueezeNet", "repo", "<https", ":", "//", "github", ".", "com", "/", "DeepScale", "/", "SqueezeNet", "/", "tree", "/", "master", "/", "SqueezeNet_v1", ".", "1", ">", "_", ".", "SqueezeNet", "1", ".", "1", "has", "2", ".", "4x", "less", "computation", "and", "slightly", "fewer", "parameters", "than", "SqueezeNet", "1", ".", "0", "without", "sacrificing", "accuracy", "." ]
def squeezenet1_1(num_classes=1000, pretrained='imagenet'): r"""SqueezeNet 1.1 model from the `official SqueezeNet repo <https://github.com/DeepScale/SqueezeNet/tree/master/SqueezeNet_v1.1>`_. SqueezeNet 1.1 has 2.4x less computation and slightly fewer parameters than SqueezeNet 1.0, without sacrificing accuracy. """ model = models.squeezenet1_1(pretrained=False) if pretrained is not None: settings = pretrained_settings['squeezenet1_1'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_squeezenets(model) return model
[ "def", "squeezenet1_1", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "squeezenet1_1", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'squeezenet1_1'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_squeezenets", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L440-L451
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg11
(num_classes=1000, pretrained='imagenet')
return model
VGG 11-layer model (configuration "A")
VGG 11-layer model (configuration "A")
[ "VGG", "11", "-", "layer", "model", "(", "configuration", "A", ")" ]
def vgg11(num_classes=1000, pretrained='imagenet'): """VGG 11-layer model (configuration "A") """ model = models.vgg11(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg11", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg11", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg11'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L495-L503
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg11_bn
(num_classes=1000, pretrained='imagenet')
return model
VGG 11-layer model (configuration "A") with batch normalization
VGG 11-layer model (configuration "A") with batch normalization
[ "VGG", "11", "-", "layer", "model", "(", "configuration", "A", ")", "with", "batch", "normalization" ]
def vgg11_bn(num_classes=1000, pretrained='imagenet'): """VGG 11-layer model (configuration "A") with batch normalization """ model = models.vgg11_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg11_bn'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg11_bn", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg11_bn", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg11_bn'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L505-L513
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg13
(num_classes=1000, pretrained='imagenet')
return model
VGG 13-layer model (configuration "B")
VGG 13-layer model (configuration "B")
[ "VGG", "13", "-", "layer", "model", "(", "configuration", "B", ")" ]
def vgg13(num_classes=1000, pretrained='imagenet'): """VGG 13-layer model (configuration "B") """ model = models.vgg13(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg13'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg13", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg13", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg13'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L515-L523
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg13_bn
(num_classes=1000, pretrained='imagenet')
return model
VGG 13-layer model (configuration "B") with batch normalization
VGG 13-layer model (configuration "B") with batch normalization
[ "VGG", "13", "-", "layer", "model", "(", "configuration", "B", ")", "with", "batch", "normalization" ]
def vgg13_bn(num_classes=1000, pretrained='imagenet'): """VGG 13-layer model (configuration "B") with batch normalization """ model = models.vgg13_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg13_bn'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg13_bn", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg13_bn", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg13_bn'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L525-L533
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg16
(num_classes=1000, pretrained='imagenet')
return model
VGG 16-layer model (configuration "D")
VGG 16-layer model (configuration "D")
[ "VGG", "16", "-", "layer", "model", "(", "configuration", "D", ")" ]
def vgg16(num_classes=1000, pretrained='imagenet'): """VGG 16-layer model (configuration "D") """ model = models.vgg16(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg16'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg16", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg16", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg16'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L535-L543
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg16_bn
(num_classes=1000, pretrained='imagenet')
return model
VGG 16-layer model (configuration "D") with batch normalization
VGG 16-layer model (configuration "D") with batch normalization
[ "VGG", "16", "-", "layer", "model", "(", "configuration", "D", ")", "with", "batch", "normalization" ]
def vgg16_bn(num_classes=1000, pretrained='imagenet'): """VGG 16-layer model (configuration "D") with batch normalization """ model = models.vgg16_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg16_bn'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg16_bn", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg16_bn", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg16_bn'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L545-L553
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg19
(num_classes=1000, pretrained='imagenet')
return model
VGG 19-layer model (configuration "E")
VGG 19-layer model (configuration "E")
[ "VGG", "19", "-", "layer", "model", "(", "configuration", "E", ")" ]
def vgg19(num_classes=1000, pretrained='imagenet'): """VGG 19-layer model (configuration "E") """ model = models.vgg19(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg19'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg19", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg19", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg19'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L555-L563
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/torchvision_models.py
python
vgg19_bn
(num_classes=1000, pretrained='imagenet')
return model
VGG 19-layer model (configuration 'E') with batch normalization
VGG 19-layer model (configuration 'E') with batch normalization
[ "VGG", "19", "-", "layer", "model", "(", "configuration", "E", ")", "with", "batch", "normalization" ]
def vgg19_bn(num_classes=1000, pretrained='imagenet'): """VGG 19-layer model (configuration 'E') with batch normalization """ model = models.vgg19_bn(pretrained=False) if pretrained is not None: settings = pretrained_settings['vgg19_bn'][pretrained] model = load_pretrained(model, num_classes, settings) model = modify_vggs(model) return model
[ "def", "vgg19_bn", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "models", ".", "vgg19_bn", "(", "pretrained", "=", "False", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'vgg19_bn'", "]", "[", "pretrained", "]", "model", "=", "load_pretrained", "(", "model", ",", "num_classes", ",", "settings", ")", "model", "=", "modify_vggs", "(", "model", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/torchvision_models.py#L565-L573
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/senet.py
python
SENet.__init__
(self, block, layers, groups, reduction, dropout_p=0.2, inplanes=128, input_3x3=True, downsample_kernel_size=3, downsample_padding=1, num_classes=1000)
Parameters ---------- block (nn.Module): Bottleneck class. - For SENet154: SEBottleneck - For SE-ResNet models: SEResNetBottleneck - For SE-ResNeXt models: SEResNeXtBottleneck layers (list of ints): Number of residual blocks for 4 layers of the network (layer1...layer4). groups (int): Number of groups for the 3x3 convolution in each bottleneck block. - For SENet154: 64 - For SE-ResNet models: 1 - For SE-ResNeXt models: 32 reduction (int): Reduction ratio for Squeeze-and-Excitation modules. - For all models: 16 dropout_p (float or None): Drop probability for the Dropout layer. If `None` the Dropout layer is not used. - For SENet154: 0.2 - For SE-ResNet models: None - For SE-ResNeXt models: None inplanes (int): Number of input channels for layer1. - For SENet154: 128 - For SE-ResNet models: 64 - For SE-ResNeXt models: 64 input_3x3 (bool): If `True`, use three 3x3 convolutions instead of a single 7x7 convolution in layer0. - For SENet154: True - For SE-ResNet models: False - For SE-ResNeXt models: False downsample_kernel_size (int): Kernel size for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 3 - For SE-ResNet models: 1 - For SE-ResNeXt models: 1 downsample_padding (int): Padding for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 1 - For SE-ResNet models: 0 - For SE-ResNeXt models: 0 num_classes (int): Number of outputs in `last_linear` layer. - For all models: 1000
Parameters ---------- block (nn.Module): Bottleneck class. - For SENet154: SEBottleneck - For SE-ResNet models: SEResNetBottleneck - For SE-ResNeXt models: SEResNeXtBottleneck layers (list of ints): Number of residual blocks for 4 layers of the network (layer1...layer4). groups (int): Number of groups for the 3x3 convolution in each bottleneck block. - For SENet154: 64 - For SE-ResNet models: 1 - For SE-ResNeXt models: 32 reduction (int): Reduction ratio for Squeeze-and-Excitation modules. - For all models: 16 dropout_p (float or None): Drop probability for the Dropout layer. If `None` the Dropout layer is not used. - For SENet154: 0.2 - For SE-ResNet models: None - For SE-ResNeXt models: None inplanes (int): Number of input channels for layer1. - For SENet154: 128 - For SE-ResNet models: 64 - For SE-ResNeXt models: 64 input_3x3 (bool): If `True`, use three 3x3 convolutions instead of a single 7x7 convolution in layer0. - For SENet154: True - For SE-ResNet models: False - For SE-ResNeXt models: False downsample_kernel_size (int): Kernel size for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 3 - For SE-ResNet models: 1 - For SE-ResNeXt models: 1 downsample_padding (int): Padding for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 1 - For SE-ResNet models: 0 - For SE-ResNeXt models: 0 num_classes (int): Number of outputs in `last_linear` layer. - For all models: 1000
[ "Parameters", "----------", "block", "(", "nn", ".", "Module", ")", ":", "Bottleneck", "class", ".", "-", "For", "SENet154", ":", "SEBottleneck", "-", "For", "SE", "-", "ResNet", "models", ":", "SEResNetBottleneck", "-", "For", "SE", "-", "ResNeXt", "models", ":", "SEResNeXtBottleneck", "layers", "(", "list", "of", "ints", ")", ":", "Number", "of", "residual", "blocks", "for", "4", "layers", "of", "the", "network", "(", "layer1", "...", "layer4", ")", ".", "groups", "(", "int", ")", ":", "Number", "of", "groups", "for", "the", "3x3", "convolution", "in", "each", "bottleneck", "block", ".", "-", "For", "SENet154", ":", "64", "-", "For", "SE", "-", "ResNet", "models", ":", "1", "-", "For", "SE", "-", "ResNeXt", "models", ":", "32", "reduction", "(", "int", ")", ":", "Reduction", "ratio", "for", "Squeeze", "-", "and", "-", "Excitation", "modules", ".", "-", "For", "all", "models", ":", "16", "dropout_p", "(", "float", "or", "None", ")", ":", "Drop", "probability", "for", "the", "Dropout", "layer", ".", "If", "None", "the", "Dropout", "layer", "is", "not", "used", ".", "-", "For", "SENet154", ":", "0", ".", "2", "-", "For", "SE", "-", "ResNet", "models", ":", "None", "-", "For", "SE", "-", "ResNeXt", "models", ":", "None", "inplanes", "(", "int", ")", ":", "Number", "of", "input", "channels", "for", "layer1", ".", "-", "For", "SENet154", ":", "128", "-", "For", "SE", "-", "ResNet", "models", ":", "64", "-", "For", "SE", "-", "ResNeXt", "models", ":", "64", "input_3x3", "(", "bool", ")", ":", "If", "True", "use", "three", "3x3", "convolutions", "instead", "of", "a", "single", "7x7", "convolution", "in", "layer0", ".", "-", "For", "SENet154", ":", "True", "-", "For", "SE", "-", "ResNet", "models", ":", "False", "-", "For", "SE", "-", "ResNeXt", "models", ":", "False", "downsample_kernel_size", "(", "int", ")", ":", "Kernel", "size", "for", "downsampling", "convolutions", "in", "layer2", "layer3", "and", "layer4", ".", "-", "For", "SENet154", ":", "3", "-", "For", "SE", "-", "ResNet", "models", ":", "1", "-", "For", "SE", "-", "ResNeXt", "models", ":", "1", "downsample_padding", "(", "int", ")", ":", "Padding", "for", "downsampling", "convolutions", "in", "layer2", "layer3", "and", "layer4", ".", "-", "For", "SENet154", ":", "1", "-", "For", "SE", "-", "ResNet", "models", ":", "0", "-", "For", "SE", "-", "ResNeXt", "models", ":", "0", "num_classes", "(", "int", ")", ":", "Number", "of", "outputs", "in", "last_linear", "layer", ".", "-", "For", "all", "models", ":", "1000" ]
def __init__(self, block, layers, groups, reduction, dropout_p=0.2, inplanes=128, input_3x3=True, downsample_kernel_size=3, downsample_padding=1, num_classes=1000): """ Parameters ---------- block (nn.Module): Bottleneck class. - For SENet154: SEBottleneck - For SE-ResNet models: SEResNetBottleneck - For SE-ResNeXt models: SEResNeXtBottleneck layers (list of ints): Number of residual blocks for 4 layers of the network (layer1...layer4). groups (int): Number of groups for the 3x3 convolution in each bottleneck block. - For SENet154: 64 - For SE-ResNet models: 1 - For SE-ResNeXt models: 32 reduction (int): Reduction ratio for Squeeze-and-Excitation modules. - For all models: 16 dropout_p (float or None): Drop probability for the Dropout layer. If `None` the Dropout layer is not used. - For SENet154: 0.2 - For SE-ResNet models: None - For SE-ResNeXt models: None inplanes (int): Number of input channels for layer1. - For SENet154: 128 - For SE-ResNet models: 64 - For SE-ResNeXt models: 64 input_3x3 (bool): If `True`, use three 3x3 convolutions instead of a single 7x7 convolution in layer0. - For SENet154: True - For SE-ResNet models: False - For SE-ResNeXt models: False downsample_kernel_size (int): Kernel size for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 3 - For SE-ResNet models: 1 - For SE-ResNeXt models: 1 downsample_padding (int): Padding for downsampling convolutions in layer2, layer3 and layer4. - For SENet154: 1 - For SE-ResNet models: 0 - For SE-ResNeXt models: 0 num_classes (int): Number of outputs in `last_linear` layer. - For all models: 1000 """ super(SENet, self).__init__() self.inplanes = inplanes if input_3x3: layer0_modules = [ ('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1, bias=False)), ('bn1', nn.BatchNorm2d(64)), ('relu1', nn.ReLU(inplace=True)), ('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1, bias=False)), ('bn2', nn.BatchNorm2d(64)), ('relu2', nn.ReLU(inplace=True)), ('conv3', nn.Conv2d(64, inplanes, 3, stride=1, padding=1, bias=False)), ('bn3', nn.BatchNorm2d(inplanes)), ('relu3', nn.ReLU(inplace=True)), ] else: layer0_modules = [ ('conv1', nn.Conv2d(3, inplanes, kernel_size=7, stride=2, padding=3, bias=False)), ('bn1', nn.BatchNorm2d(inplanes)), ('relu1', nn.ReLU(inplace=True)), ] # To preserve compatibility with Caffe weights `ceil_mode=True` # is used instead of `padding=1`. layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2, ceil_mode=True))) self.layer0 = nn.Sequential(OrderedDict(layer0_modules)) self.layer1 = self._make_layer( block, planes=64, blocks=layers[0], groups=groups, reduction=reduction, downsample_kernel_size=1, downsample_padding=0 ) self.layer2 = self._make_layer( block, planes=128, blocks=layers[1], stride=2, groups=groups, reduction=reduction, downsample_kernel_size=downsample_kernel_size, downsample_padding=downsample_padding ) self.layer3 = self._make_layer( block, planes=256, blocks=layers[2], stride=2, groups=groups, reduction=reduction, downsample_kernel_size=downsample_kernel_size, downsample_padding=downsample_padding ) self.layer4 = self._make_layer( block, planes=512, blocks=layers[3], stride=2, groups=groups, reduction=reduction, downsample_kernel_size=downsample_kernel_size, downsample_padding=downsample_padding ) self.avg_pool = nn.AvgPool2d(7, stride=1) self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None self.last_linear = nn.Linear(512 * block.expansion, num_classes)
[ "def", "__init__", "(", "self", ",", "block", ",", "layers", ",", "groups", ",", "reduction", ",", "dropout_p", "=", "0.2", ",", "inplanes", "=", "128", ",", "input_3x3", "=", "True", ",", "downsample_kernel_size", "=", "3", ",", "downsample_padding", "=", "1", ",", "num_classes", "=", "1000", ")", ":", "super", "(", "SENet", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "inplanes", "=", "inplanes", "if", "input_3x3", ":", "layer0_modules", "=", "[", "(", "'conv1'", ",", "nn", ".", "Conv2d", "(", "3", ",", "64", ",", "3", ",", "stride", "=", "2", ",", "padding", "=", "1", ",", "bias", "=", "False", ")", ")", ",", "(", "'bn1'", ",", "nn", ".", "BatchNorm2d", "(", "64", ")", ")", ",", "(", "'relu1'", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ")", ",", "(", "'conv2'", ",", "nn", ".", "Conv2d", "(", "64", ",", "64", ",", "3", ",", "stride", "=", "1", ",", "padding", "=", "1", ",", "bias", "=", "False", ")", ")", ",", "(", "'bn2'", ",", "nn", ".", "BatchNorm2d", "(", "64", ")", ")", ",", "(", "'relu2'", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ")", ",", "(", "'conv3'", ",", "nn", ".", "Conv2d", "(", "64", ",", "inplanes", ",", "3", ",", "stride", "=", "1", ",", "padding", "=", "1", ",", "bias", "=", "False", ")", ")", ",", "(", "'bn3'", ",", "nn", ".", "BatchNorm2d", "(", "inplanes", ")", ")", ",", "(", "'relu3'", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ")", ",", "]", "else", ":", "layer0_modules", "=", "[", "(", "'conv1'", ",", "nn", ".", "Conv2d", "(", "3", ",", "inplanes", ",", "kernel_size", "=", "7", ",", "stride", "=", "2", ",", "padding", "=", "3", ",", "bias", "=", "False", ")", ")", ",", "(", "'bn1'", ",", "nn", ".", "BatchNorm2d", "(", "inplanes", ")", ")", ",", "(", "'relu1'", ",", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", ")", ",", "]", "# To preserve compatibility with Caffe weights `ceil_mode=True`", "# is used instead of `padding=1`.", "layer0_modules", ".", "append", "(", "(", "'pool'", ",", "nn", ".", "MaxPool2d", "(", "3", ",", "stride", "=", "2", ",", "ceil_mode", "=", "True", ")", ")", ")", "self", ".", "layer0", "=", "nn", ".", "Sequential", "(", "OrderedDict", "(", "layer0_modules", ")", ")", "self", ".", "layer1", "=", "self", ".", "_make_layer", "(", "block", ",", "planes", "=", "64", ",", "blocks", "=", "layers", "[", "0", "]", ",", "groups", "=", "groups", ",", "reduction", "=", "reduction", ",", "downsample_kernel_size", "=", "1", ",", "downsample_padding", "=", "0", ")", "self", ".", "layer2", "=", "self", ".", "_make_layer", "(", "block", ",", "planes", "=", "128", ",", "blocks", "=", "layers", "[", "1", "]", ",", "stride", "=", "2", ",", "groups", "=", "groups", ",", "reduction", "=", "reduction", ",", "downsample_kernel_size", "=", "downsample_kernel_size", ",", "downsample_padding", "=", "downsample_padding", ")", "self", ".", "layer3", "=", "self", ".", "_make_layer", "(", "block", ",", "planes", "=", "256", ",", "blocks", "=", "layers", "[", "2", "]", ",", "stride", "=", "2", ",", "groups", "=", "groups", ",", "reduction", "=", "reduction", ",", "downsample_kernel_size", "=", "downsample_kernel_size", ",", "downsample_padding", "=", "downsample_padding", ")", "self", ".", "layer4", "=", "self", ".", "_make_layer", "(", "block", ",", "planes", "=", "512", ",", "blocks", "=", "layers", "[", "3", "]", ",", "stride", "=", "2", ",", "groups", "=", "groups", ",", "reduction", "=", "reduction", ",", "downsample_kernel_size", "=", "downsample_kernel_size", ",", "downsample_padding", "=", "downsample_padding", ")", "self", ".", "avg_pool", "=", "nn", ".", "AvgPool2d", "(", "7", ",", "stride", "=", "1", ")", "self", ".", "dropout", "=", "nn", ".", "Dropout", "(", "dropout_p", ")", "if", "dropout_p", "is", "not", "None", "else", "None", "self", ".", "last_linear", "=", "nn", ".", "Linear", "(", "512", "*", "block", ".", "expansion", ",", "num_classes", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/senet.py#L209-L325
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/cafferesnet.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=False)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "bias", "=", "False", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/cafferesnet.py#L23-L26
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/cafferesnet.py
python
cafferesnet101
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
[ "Constructs", "a", "ResNet", "-", "101", "model", ".", "Args", ":", "pretrained", "(", "bool", ")", ":", "If", "True", "returns", "a", "model", "pre", "-", "trained", "on", "ImageNet" ]
def cafferesnet101(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['cafferesnet101'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "def", "cafferesnet101", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'cafferesnet101'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/cafferesnet.py#L168-L184
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/nasnet_mobile.py
python
nasnetamobile
(num_classes=1000, pretrained='imagenet')
return model
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper.
[ "r", "NASNetALarge", "model", "architecture", "from", "the", "NASNet", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1707", ".", "07012", ">", "_", "paper", "." ]
def nasnetamobile(num_classes=1000, pretrained='imagenet'): r"""NASNetALarge model architecture from the `"NASNet" <https://arxiv.org/abs/1707.07012>`_ paper. """ if pretrained: settings = pretrained_settings['nasnetamobile'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = NASNetAMobile(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'], map_location=None)) # if pretrained == 'imagenet': # new_last_linear = nn.Linear(model.last_linear.in_features, 1000) # new_last_linear.weight.data = model.last_linear.weight.data[1:] # new_last_linear.bias.data = model.last_linear.bias.data[1:] # model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: settings = pretrained_settings['nasnetamobile']['imagenet'] model = NASNetAMobile(num_classes=num_classes) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "def", "nasnetamobile", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'nasnetamobile'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "# both 'imagenet'&'imagenet+background' are loaded from same parameters", "model", "=", "NASNetAMobile", "(", "num_classes", "=", "num_classes", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ",", "map_location", "=", "None", ")", ")", "# if pretrained == 'imagenet':", "# new_last_linear = nn.Linear(model.last_linear.in_features, 1000)", "# new_last_linear.weight.data = model.last_linear.weight.data[1:]", "# new_last_linear.bias.data = model.last_linear.bias.data[1:]", "# model.last_linear = new_last_linear", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "else", ":", "settings", "=", "pretrained_settings", "[", "'nasnetamobile'", "]", "[", "'imagenet'", "]", "model", "=", "NASNetAMobile", "(", "num_classes", "=", "num_classes", ")", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/nasnet_mobile.py#L618-L652
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "bias", "=", "True", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L27-L30
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
fbresnet18
(num_classes=1000)
return model
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-18 model.
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
def fbresnet18(num_classes=1000): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(BasicBlock, [2, 2, 2, 2], num_classes=num_classes) return model
[ "def", "fbresnet18", "(", "num_classes", "=", "1000", ")", ":", "model", "=", "FBResNet", "(", "BasicBlock", ",", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L176-L183
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
fbresnet34
(num_classes=1000)
return model
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-34 model.
[ "Constructs", "a", "ResNet", "-", "34", "model", "." ]
def fbresnet34(num_classes=1000): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(BasicBlock, [3, 4, 6, 3], num_classes=num_classes) return model
[ "def", "fbresnet34", "(", "num_classes", "=", "1000", ")", ":", "model", "=", "FBResNet", "(", "BasicBlock", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L186-L193
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
fbresnet50
(num_classes=1000)
return model
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-50 model.
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
def fbresnet50(num_classes=1000): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 4, 6, 3], num_classes=num_classes) return model
[ "def", "fbresnet50", "(", "num_classes", "=", "1000", ")", ":", "model", "=", "FBResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L196-L203
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
fbresnet101
(num_classes=1000)
return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-101 model.
[ "Constructs", "a", "ResNet", "-", "101", "model", "." ]
def fbresnet101(num_classes=1000): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 4, 23, 3], num_classes=num_classes) return model
[ "def", "fbresnet101", "(", "num_classes", "=", "1000", ")", ":", "model", "=", "FBResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L206-L213
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet.py
python
fbresnet152
(num_classes=1000, pretrained='imagenet')
return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-152 model.
[ "Constructs", "a", "ResNet", "-", "152", "model", "." ]
def fbresnet152(num_classes=1000, pretrained='imagenet'): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = FBResNet(Bottleneck, [3, 8, 36, 3], num_classes=num_classes) if pretrained is not None: settings = pretrained_settings['fbresnet152'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] return model
[ "def", "fbresnet152", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "model", "=", "FBResNet", "(", "Bottleneck", ",", "[", "3", ",", "8", ",", "36", ",", "3", "]", ",", "num_classes", "=", "num_classes", ")", "if", "pretrained", "is", "not", "None", ":", "settings", "=", "pretrained_settings", "[", "'fbresnet152'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet.py#L216-L233
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/inceptionresnetv2.py
python
inceptionresnetv2
(num_classes=1000, pretrained='imagenet')
return model
r"""InceptionResNetV2 model architecture from the `"InceptionV4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper.
r"""InceptionResNetV2 model architecture from the `"InceptionV4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper.
[ "r", "InceptionResNetV2", "model", "architecture", "from", "the", "InceptionV4", "Inception", "-", "ResNet", "...", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1602", ".", "07261", ">", "_", "paper", "." ]
def inceptionresnetv2(num_classes=1000, pretrained='imagenet'): r"""InceptionResNetV2 model architecture from the `"InceptionV4, Inception-ResNet..." <https://arxiv.org/abs/1602.07261>`_ paper. """ if pretrained: settings = pretrained_settings['inceptionresnetv2'][pretrained] assert num_classes == settings['num_classes'], \ "num_classes should be {}, but is {}".format(settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = InceptionResNetV2(num_classes=1001) model.load_state_dict(model_zoo.load_url(settings['url'])) if pretrained == 'imagenet': new_last_linear = nn.Linear(1536, 1000) new_last_linear.weight.data = model.last_linear.weight.data[1:] new_last_linear.bias.data = model.last_linear.bias.data[1:] model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = InceptionResNetV2(num_classes=num_classes) return model
[ "def", "inceptionresnetv2", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'inceptionresnetv2'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "\"num_classes should be {}, but is {}\"", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "# both 'imagenet'&'imagenet+background' are loaded from same parameters", "model", "=", "InceptionResNetV2", "(", "num_classes", "=", "1001", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "if", "pretrained", "==", "'imagenet'", ":", "new_last_linear", "=", "nn", ".", "Linear", "(", "1536", ",", "1000", ")", "new_last_linear", ".", "weight", ".", "data", "=", "model", ".", "last_linear", ".", "weight", ".", "data", "[", "1", ":", "]", "new_last_linear", ".", "bias", ".", "data", "=", "model", ".", "last_linear", ".", "bias", ".", "data", "[", "1", ":", "]", "model", ".", "last_linear", "=", "new_last_linear", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "else", ":", "model", "=", "InceptionResNetV2", "(", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/inceptionresnetv2.py#L333-L360
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/xception.py
python
Xception.__init__
(self, num_classes=1000)
Constructor Args: num_classes: number of classes
Constructor Args: num_classes: number of classes
[ "Constructor", "Args", ":", "num_classes", ":", "number", "of", "classes" ]
def __init__(self, num_classes=1000): """ Constructor Args: num_classes: number of classes """ super(Xception, self).__init__() self.num_classes = num_classes self.conv1 = nn.Conv2d(3, 32, 3,2, 0, bias=False) self.bn1 = nn.BatchNorm2d(32) self.relu1 = nn.ReLU(inplace=True) self.conv2 = nn.Conv2d(32,64,3,bias=False) self.bn2 = nn.BatchNorm2d(64) self.relu2 = nn.ReLU(inplace=True) #do relu here self.block1=Block(64,128,2,2,start_with_relu=False,grow_first=True) self.block2=Block(128,256,2,2,start_with_relu=True,grow_first=True) self.block3=Block(256,728,2,2,start_with_relu=True,grow_first=True) self.block4=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block5=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block6=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block7=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block8=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block9=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block10=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block11=Block(728,728,3,1,start_with_relu=True,grow_first=True) self.block12=Block(728,1024,2,2,start_with_relu=True,grow_first=False) self.conv3 = SeparableConv2d(1024,1536,3,1,1) self.bn3 = nn.BatchNorm2d(1536) self.relu3 = nn.ReLU(inplace=True) #do relu here self.conv4 = SeparableConv2d(1536,2048,3,1,1) self.bn4 = nn.BatchNorm2d(2048) self.fc = nn.Linear(2048, num_classes)
[ "def", "__init__", "(", "self", ",", "num_classes", "=", "1000", ")", ":", "super", "(", "Xception", ",", "self", ")", ".", "__init__", "(", ")", "self", ".", "num_classes", "=", "num_classes", "self", ".", "conv1", "=", "nn", ".", "Conv2d", "(", "3", ",", "32", ",", "3", ",", "2", ",", "0", ",", "bias", "=", "False", ")", "self", ".", "bn1", "=", "nn", ".", "BatchNorm2d", "(", "32", ")", "self", ".", "relu1", "=", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", "self", ".", "conv2", "=", "nn", ".", "Conv2d", "(", "32", ",", "64", ",", "3", ",", "bias", "=", "False", ")", "self", ".", "bn2", "=", "nn", ".", "BatchNorm2d", "(", "64", ")", "self", ".", "relu2", "=", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", "#do relu here", "self", ".", "block1", "=", "Block", "(", "64", ",", "128", ",", "2", ",", "2", ",", "start_with_relu", "=", "False", ",", "grow_first", "=", "True", ")", "self", ".", "block2", "=", "Block", "(", "128", ",", "256", ",", "2", ",", "2", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block3", "=", "Block", "(", "256", ",", "728", ",", "2", ",", "2", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block4", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block5", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block6", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block7", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block8", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block9", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block10", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block11", "=", "Block", "(", "728", ",", "728", ",", "3", ",", "1", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "True", ")", "self", ".", "block12", "=", "Block", "(", "728", ",", "1024", ",", "2", ",", "2", ",", "start_with_relu", "=", "True", ",", "grow_first", "=", "False", ")", "self", ".", "conv3", "=", "SeparableConv2d", "(", "1024", ",", "1536", ",", "3", ",", "1", ",", "1", ")", "self", ".", "bn3", "=", "nn", ".", "BatchNorm2d", "(", "1536", ")", "self", ".", "relu3", "=", "nn", ".", "ReLU", "(", "inplace", "=", "True", ")", "#do relu here", "self", ".", "conv4", "=", "SeparableConv2d", "(", "1536", ",", "2048", ",", "3", ",", "1", ",", "1", ")", "self", ".", "bn4", "=", "nn", ".", "BatchNorm2d", "(", "2048", ")", "self", ".", "fc", "=", "nn", ".", "Linear", "(", "2048", ",", "num_classes", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/xception.py#L119-L160
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/pnasnet.py
python
pnasnet5large
(num_classes=1001, pretrained='imagenet')
return model
r"""PNASNet-5 model architecture from the `"Progressive Neural Architecture Search" <https://arxiv.org/abs/1712.00559>`_ paper.
r"""PNASNet-5 model architecture from the `"Progressive Neural Architecture Search" <https://arxiv.org/abs/1712.00559>`_ paper.
[ "r", "PNASNet", "-", "5", "model", "architecture", "from", "the", "Progressive", "Neural", "Architecture", "Search", "<https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1712", ".", "00559", ">", "_", "paper", "." ]
def pnasnet5large(num_classes=1001, pretrained='imagenet'): r"""PNASNet-5 model architecture from the `"Progressive Neural Architecture Search" <https://arxiv.org/abs/1712.00559>`_ paper. """ if pretrained: settings = pretrained_settings['pnasnet5large'][pretrained] assert num_classes == settings[ 'num_classes'], 'num_classes should be {}, but is {}'.format( settings['num_classes'], num_classes) # both 'imagenet'&'imagenet+background' are loaded from same parameters model = PNASNet5Large(num_classes=1001) model.load_state_dict(model_zoo.load_url(settings['url'])) if pretrained == 'imagenet': new_last_linear = nn.Linear(model.last_linear.in_features, 1000) new_last_linear.weight.data = model.last_linear.weight.data[1:] new_last_linear.bias.data = model.last_linear.bias.data[1:] model.last_linear = new_last_linear model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = PNASNet5Large(num_classes=num_classes) return model
[ "def", "pnasnet5large", "(", "num_classes", "=", "1001", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'pnasnet5large'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "'num_classes should be {}, but is {}'", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "# both 'imagenet'&'imagenet+background' are loaded from same parameters", "model", "=", "PNASNet5Large", "(", "num_classes", "=", "1001", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "if", "pretrained", "==", "'imagenet'", ":", "new_last_linear", "=", "nn", ".", "Linear", "(", "model", ".", "last_linear", ".", "in_features", ",", "1000", ")", "new_last_linear", ".", "weight", ".", "data", "=", "model", ".", "last_linear", ".", "weight", ".", "data", "[", "1", ":", "]", "new_last_linear", ".", "bias", ".", "data", "=", "model", ".", "last_linear", ".", "bias", ".", "data", "[", "1", ":", "]", "model", ".", "last_linear", "=", "new_last_linear", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "else", ":", "model", "=", "PNASNet5Large", "(", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/pnasnet.py#L372-L401
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/polynet.py
python
polynet
(num_classes=1000, pretrained='imagenet')
return model
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725
PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725
[ "PolyNet", "architecture", "from", "the", "paper", "PolyNet", ":", "A", "Pursuit", "of", "Structural", "Diversity", "in", "Very", "Deep", "Networks", "https", ":", "//", "arxiv", ".", "org", "/", "abs", "/", "1611", ".", "05725" ]
def polynet(num_classes=1000, pretrained='imagenet'): """PolyNet architecture from the paper 'PolyNet: A Pursuit of Structural Diversity in Very Deep Networks' https://arxiv.org/abs/1611.05725 """ if pretrained: settings = pretrained_settings['polynet'][pretrained] assert num_classes == settings['num_classes'], \ 'num_classes should be {}, but is {}'.format( settings['num_classes'], num_classes) model = PolyNet(num_classes=num_classes) model.load_state_dict(model_zoo.load_url(settings['url'])) model.input_space = settings['input_space'] model.input_size = settings['input_size'] model.input_range = settings['input_range'] model.mean = settings['mean'] model.std = settings['std'] else: model = PolyNet(num_classes=num_classes) return model
[ "def", "polynet", "(", "num_classes", "=", "1000", ",", "pretrained", "=", "'imagenet'", ")", ":", "if", "pretrained", ":", "settings", "=", "pretrained_settings", "[", "'polynet'", "]", "[", "pretrained", "]", "assert", "num_classes", "==", "settings", "[", "'num_classes'", "]", ",", "'num_classes should be {}, but is {}'", ".", "format", "(", "settings", "[", "'num_classes'", "]", ",", "num_classes", ")", "model", "=", "PolyNet", "(", "num_classes", "=", "num_classes", ")", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "settings", "[", "'url'", "]", ")", ")", "model", ".", "input_space", "=", "settings", "[", "'input_space'", "]", "model", ".", "input_size", "=", "settings", "[", "'input_size'", "]", "model", ".", "input_range", "=", "settings", "[", "'input_range'", "]", "model", ".", "mean", "=", "settings", "[", "'mean'", "]", "model", ".", "std", "=", "settings", "[", "'std'", "]", "else", ":", "model", "=", "PolyNet", "(", "num_classes", "=", "num_classes", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/polynet.py#L461-L480
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/dpn.py
python
adaptive_avgmax_pool2d
(x, pool_type='avg', padding=0, count_include_pad=False)
return x
Selectable global pooling function with dynamic input kernel size
Selectable global pooling function with dynamic input kernel size
[ "Selectable", "global", "pooling", "function", "with", "dynamic", "input", "kernel", "size" ]
def adaptive_avgmax_pool2d(x, pool_type='avg', padding=0, count_include_pad=False): """Selectable global pooling function with dynamic input kernel size """ if pool_type == 'avgmaxc': x = torch.cat([ F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad), F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) ], dim=1) elif pool_type == 'avgmax': x_avg = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) x_max = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) x = 0.5 * (x_avg + x_max) elif pool_type == 'max': x = F.max_pool2d(x, kernel_size=(x.size(2), x.size(3)), padding=padding) else: if pool_type != 'avg': print('Invalid pool type %s specified. Defaulting to average pooling.' % pool_type) x = F.avg_pool2d( x, kernel_size=(x.size(2), x.size(3)), padding=padding, count_include_pad=count_include_pad) return x
[ "def", "adaptive_avgmax_pool2d", "(", "x", ",", "pool_type", "=", "'avg'", ",", "padding", "=", "0", ",", "count_include_pad", "=", "False", ")", ":", "if", "pool_type", "==", "'avgmaxc'", ":", "x", "=", "torch", ".", "cat", "(", "[", "F", ".", "avg_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ",", "count_include_pad", "=", "count_include_pad", ")", ",", "F", ".", "max_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ")", "]", ",", "dim", "=", "1", ")", "elif", "pool_type", "==", "'avgmax'", ":", "x_avg", "=", "F", ".", "avg_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ",", "count_include_pad", "=", "count_include_pad", ")", "x_max", "=", "F", ".", "max_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ")", "x", "=", "0.5", "*", "(", "x_avg", "+", "x_max", ")", "elif", "pool_type", "==", "'max'", ":", "x", "=", "F", ".", "max_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ")", "else", ":", "if", "pool_type", "!=", "'avg'", ":", "print", "(", "'Invalid pool type %s specified. Defaulting to average pooling.'", "%", "pool_type", ")", "x", "=", "F", ".", "avg_pool2d", "(", "x", ",", "kernel_size", "=", "(", "x", ".", "size", "(", "2", ")", ",", "x", ".", "size", "(", "3", ")", ")", ",", "padding", "=", "padding", ",", "count_include_pad", "=", "count_include_pad", ")", "return", "x" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/dpn.py#L407-L428
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
conv3x3
(in_planes, out_planes, stride=1)
return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
3x3 convolution with padding
3x3 convolution with padding
[ "3x3", "convolution", "with", "padding" ]
def conv3x3(in_planes, out_planes, stride=1): "3x3 convolution with padding" return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, padding=1, bias=True)
[ "def", "conv3x3", "(", "in_planes", ",", "out_planes", ",", "stride", "=", "1", ")", ":", "return", "nn", ".", "Conv2d", "(", "in_planes", ",", "out_planes", ",", "kernel_size", "=", "3", ",", "stride", "=", "stride", ",", "padding", "=", "1", ",", "bias", "=", "True", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L20-L23
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
resnet18
(pretrained=False, **kwargs)
return model
Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-18 model.
[ "Constructs", "a", "ResNet", "-", "18", "model", "." ]
def resnet18(pretrained=False, **kwargs): """Constructs a ResNet-18 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet18'])) return model
[ "def", "resnet18", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "2", ",", "2", ",", "2", ",", "2", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet18'", "]", ")", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L160-L169
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
resnet34
(pretrained=False, **kwargs)
return model
Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-34 model.
[ "Constructs", "a", "ResNet", "-", "34", "model", "." ]
def resnet34(pretrained=False, **kwargs): """Constructs a ResNet-34 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet34'])) return model
[ "def", "resnet34", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "BasicBlock", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet34'", "]", ")", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L172-L181
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
resnet50
(pretrained=False, **kwargs)
return model
Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-50 model.
[ "Constructs", "a", "ResNet", "-", "50", "model", "." ]
def resnet50(pretrained=False, **kwargs): """Constructs a ResNet-50 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet50'])) return model
[ "def", "resnet50", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "6", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet50'", "]", ")", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L184-L193
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
resnet101
(pretrained=False, **kwargs)
return model
Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-101 model.
[ "Constructs", "a", "ResNet", "-", "101", "model", "." ]
def resnet101(pretrained=False, **kwargs): """Constructs a ResNet-101 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet101'])) return model
[ "def", "resnet101", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "4", ",", "23", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet101'", "]", ")", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L196-L205
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/models/fbresnet/resnet152_load.py
python
resnet152
(pretrained=False, **kwargs)
return model
Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet
Constructs a ResNet-152 model.
[ "Constructs", "a", "ResNet", "-", "152", "model", "." ]
def resnet152(pretrained=False, **kwargs): """Constructs a ResNet-152 model. Args: pretrained (bool): If True, returns a model pre-trained on ImageNet """ model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs) if pretrained: model.load_state_dict(model_zoo.load_url(model_urls['resnet152'])) return model
[ "def", "resnet152", "(", "pretrained", "=", "False", ",", "*", "*", "kwargs", ")", ":", "model", "=", "ResNet", "(", "Bottleneck", ",", "[", "3", ",", "8", ",", "36", ",", "3", "]", ",", "*", "*", "kwargs", ")", "if", "pretrained", ":", "model", ".", "load_state_dict", "(", "model_zoo", ".", "load_url", "(", "model_urls", "[", "'resnet152'", "]", ")", ")", "return", "model" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/models/fbresnet/resnet152_load.py#L208-L217
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/datasets/utils.py
python
download_url
(url, destination=None, progress_bar=True)
Download a URL to a local file. Parameters ---------- url : str The URL to download. destination : str, None The destination of the file. If None is given the file is saved to a temporary directory. progress_bar : bool Whether to show a command-line progress bar while downloading. Returns ------- filename : str The location of the downloaded file. Notes ----- Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm
Download a URL to a local file.
[ "Download", "a", "URL", "to", "a", "local", "file", "." ]
def download_url(url, destination=None, progress_bar=True): """Download a URL to a local file. Parameters ---------- url : str The URL to download. destination : str, None The destination of the file. If None is given the file is saved to a temporary directory. progress_bar : bool Whether to show a command-line progress bar while downloading. Returns ------- filename : str The location of the downloaded file. Notes ----- Progress bar use/example adapted from tqdm documentation: https://github.com/tqdm/tqdm """ def my_hook(t): last_b = [0] def inner(b=1, bsize=1, tsize=None): if tsize is not None: t.total = tsize if b > 0: t.update((b - last_b[0]) * bsize) last_b[0] = b return inner if progress_bar: with tqdm(unit='B', unit_scale=True, miniters=1, desc=url.split('/')[-1]) as t: filename, _ = urlretrieve(url, filename=destination, reporthook=my_hook(t)) else: filename, _ = urlretrieve(url, filename=destination)
[ "def", "download_url", "(", "url", ",", "destination", "=", "None", ",", "progress_bar", "=", "True", ")", ":", "def", "my_hook", "(", "t", ")", ":", "last_b", "=", "[", "0", "]", "def", "inner", "(", "b", "=", "1", ",", "bsize", "=", "1", ",", "tsize", "=", "None", ")", ":", "if", "tsize", "is", "not", "None", ":", "t", ".", "total", "=", "tsize", "if", "b", ">", "0", ":", "t", ".", "update", "(", "(", "b", "-", "last_b", "[", "0", "]", ")", "*", "bsize", ")", "last_b", "[", "0", "]", "=", "b", "return", "inner", "if", "progress_bar", ":", "with", "tqdm", "(", "unit", "=", "'B'", ",", "unit_scale", "=", "True", ",", "miniters", "=", "1", ",", "desc", "=", "url", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", ")", "as", "t", ":", "filename", ",", "_", "=", "urlretrieve", "(", "url", ",", "filename", "=", "destination", ",", "reporthook", "=", "my_hook", "(", "t", ")", ")", "else", ":", "filename", ",", "_", "=", "urlretrieve", "(", "url", ",", "filename", "=", "destination", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/datasets/utils.py#L45-L83
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/datasets/utils.py
python
AveragePrecisionMeter.reset
(self)
Resets the meter with empty member variables
Resets the meter with empty member variables
[ "Resets", "the", "meter", "with", "empty", "member", "variables" ]
def reset(self): """Resets the meter with empty member variables""" self.scores = torch.FloatTensor(torch.FloatStorage()) self.targets = torch.LongTensor(torch.LongStorage())
[ "def", "reset", "(", "self", ")", ":", "self", ".", "scores", "=", "torch", ".", "FloatTensor", "(", "torch", ".", "FloatStorage", "(", ")", ")", "self", ".", "targets", "=", "torch", ".", "LongTensor", "(", "torch", ".", "LongStorage", "(", ")", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/datasets/utils.py#L105-L108
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/datasets/utils.py
python
AveragePrecisionMeter.add
(self, output, target)
Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0)
Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0)
[ "Args", ":", "output", "(", "Tensor", ")", ":", "NxK", "tensor", "that", "for", "each", "of", "the", "N", "examples", "indicates", "the", "probability", "of", "the", "example", "belonging", "to", "each", "of", "the", "K", "classes", "according", "to", "the", "model", ".", "The", "probabilities", "should", "sum", "to", "one", "over", "all", "classes", "target", "(", "Tensor", ")", ":", "binary", "NxK", "tensort", "that", "encodes", "which", "of", "the", "K", "classes", "are", "associated", "with", "the", "N", "-", "th", "input", "(", "eg", ":", "a", "row", "[", "0", "1", "0", "1", "]", "indicates", "that", "the", "example", "is", "associated", "with", "classes", "2", "and", "4", ")", "weight", "(", "optional", "Tensor", ")", ":", "Nx1", "tensor", "representing", "the", "weight", "for", "each", "example", "(", "each", "weight", ">", "0", ")" ]
def add(self, output, target): """ Args: output (Tensor): NxK tensor that for each of the N examples indicates the probability of the example belonging to each of the K classes, according to the model. The probabilities should sum to one over all classes target (Tensor): binary NxK tensort that encodes which of the K classes are associated with the N-th input (eg: a row [0, 1, 0, 1] indicates that the example is associated with classes 2 and 4) weight (optional, Tensor): Nx1 tensor representing the weight for each example (each weight > 0) """ if not torch.is_tensor(output): output = torch.from_numpy(output) if not torch.is_tensor(target): target = torch.from_numpy(target) if output.dim() == 1: output = output.view(-1, 1) else: assert output.dim() == 2, \ 'wrong output size (should be 1D or 2D with one column \ per class)' if target.dim() == 1: target = target.view(-1, 1) else: assert target.dim() == 2, \ 'wrong target size (should be 1D or 2D with one column \ per class)' if self.scores.numel() > 0: assert target.size(1) == self.targets.size(1), \ 'dimensions for output should match previously added examples.' # make sure storage is of sufficient size if self.scores.storage().size() < self.scores.numel() + output.numel(): new_size = math.ceil(self.scores.storage().size() * 1.5) self.scores.storage().resize_(int(new_size + output.numel())) self.targets.storage().resize_(int(new_size + output.numel())) # store scores and targets offset = self.scores.size(0) if self.scores.dim() > 0 else 0 self.scores.resize_(offset + output.size(0), output.size(1)) self.targets.resize_(offset + target.size(0), target.size(1)) self.scores.narrow(0, offset, output.size(0)).copy_(output) self.targets.narrow(0, offset, target.size(0)).copy_(target)
[ "def", "add", "(", "self", ",", "output", ",", "target", ")", ":", "if", "not", "torch", ".", "is_tensor", "(", "output", ")", ":", "output", "=", "torch", ".", "from_numpy", "(", "output", ")", "if", "not", "torch", ".", "is_tensor", "(", "target", ")", ":", "target", "=", "torch", ".", "from_numpy", "(", "target", ")", "if", "output", ".", "dim", "(", ")", "==", "1", ":", "output", "=", "output", ".", "view", "(", "-", "1", ",", "1", ")", "else", ":", "assert", "output", ".", "dim", "(", ")", "==", "2", ",", "'wrong output size (should be 1D or 2D with one column \\\n per class)'", "if", "target", ".", "dim", "(", ")", "==", "1", ":", "target", "=", "target", ".", "view", "(", "-", "1", ",", "1", ")", "else", ":", "assert", "target", ".", "dim", "(", ")", "==", "2", ",", "'wrong target size (should be 1D or 2D with one column \\\n per class)'", "if", "self", ".", "scores", ".", "numel", "(", ")", ">", "0", ":", "assert", "target", ".", "size", "(", "1", ")", "==", "self", ".", "targets", ".", "size", "(", "1", ")", ",", "'dimensions for output should match previously added examples.'", "# make sure storage is of sufficient size", "if", "self", ".", "scores", ".", "storage", "(", ")", ".", "size", "(", ")", "<", "self", ".", "scores", ".", "numel", "(", ")", "+", "output", ".", "numel", "(", ")", ":", "new_size", "=", "math", ".", "ceil", "(", "self", ".", "scores", ".", "storage", "(", ")", ".", "size", "(", ")", "*", "1.5", ")", "self", ".", "scores", ".", "storage", "(", ")", ".", "resize_", "(", "int", "(", "new_size", "+", "output", ".", "numel", "(", ")", ")", ")", "self", ".", "targets", ".", "storage", "(", ")", ".", "resize_", "(", "int", "(", "new_size", "+", "output", ".", "numel", "(", ")", ")", ")", "# store scores and targets", "offset", "=", "self", ".", "scores", ".", "size", "(", "0", ")", "if", "self", ".", "scores", ".", "dim", "(", ")", ">", "0", "else", "0", "self", ".", "scores", ".", "resize_", "(", "offset", "+", "output", ".", "size", "(", "0", ")", ",", "output", ".", "size", "(", "1", ")", ")", "self", ".", "targets", ".", "resize_", "(", "offset", "+", "target", ".", "size", "(", "0", ")", ",", "target", ".", "size", "(", "1", ")", ")", "self", ".", "scores", ".", "narrow", "(", "0", ",", "offset", ",", "output", ".", "size", "(", "0", ")", ")", ".", "copy_", "(", "output", ")", "self", ".", "targets", ".", "narrow", "(", "0", ",", "offset", ",", "target", ".", "size", "(", "0", ")", ")", ".", "copy_", "(", "target", ")" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/datasets/utils.py#L110-L156
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
pretrainedmodels/datasets/utils.py
python
AveragePrecisionMeter.value
(self)
return ap
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k
[ "Returns", "the", "model", "s", "average", "precision", "for", "each", "class", "Return", ":", "ap", "(", "FloatTensor", ")", ":", "1xK", "tensor", "with", "avg", "precision", "for", "each", "class", "k" ]
def value(self): """Returns the model's average precision for each class Return: ap (FloatTensor): 1xK tensor, with avg precision for each class k """ if self.scores.numel() == 0: return 0 ap = torch.zeros(self.scores.size(1)) rg = torch.arange(1, self.scores.size(0)).float() # compute average precision for each class for k in range(self.scores.size(1)): # sort scores scores = self.scores[:, k] targets = self.targets[:, k] # compute average precision ap[k] = AveragePrecisionMeter.average_precision(scores, targets, self.difficult_examples) return ap
[ "def", "value", "(", "self", ")", ":", "if", "self", ".", "scores", ".", "numel", "(", ")", "==", "0", ":", "return", "0", "ap", "=", "torch", ".", "zeros", "(", "self", ".", "scores", ".", "size", "(", "1", ")", ")", "rg", "=", "torch", ".", "arange", "(", "1", ",", "self", ".", "scores", ".", "size", "(", "0", ")", ")", ".", "float", "(", ")", "# compute average precision for each class", "for", "k", "in", "range", "(", "self", ".", "scores", ".", "size", "(", "1", ")", ")", ":", "# sort scores", "scores", "=", "self", ".", "scores", "[", ":", ",", "k", "]", "targets", "=", "self", ".", "targets", "[", ":", ",", "k", "]", "# compute average precision", "ap", "[", "k", "]", "=", "AveragePrecisionMeter", ".", "average_precision", "(", "scores", ",", "targets", ",", "self", ".", "difficult_examples", ")", "return", "ap" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/pretrainedmodels/datasets/utils.py#L158-L177
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
examples/imagenet_eval.py
python
adjust_learning_rate
(optimizer, epoch)
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
Sets the learning rate to the initial LR decayed by 10 every 30 epochs
[ "Sets", "the", "learning", "rate", "to", "the", "initial", "LR", "decayed", "by", "10", "every", "30", "epochs" ]
def adjust_learning_rate(optimizer, epoch): """Sets the learning rate to the initial LR decayed by 10 every 30 epochs""" lr = args.lr * (0.1 ** (epoch // 30)) for param_group in optimizer.param_groups: param_group['lr'] = lr
[ "def", "adjust_learning_rate", "(", "optimizer", ",", "epoch", ")", ":", "lr", "=", "args", ".", "lr", "*", "(", "0.1", "**", "(", "epoch", "//", "30", ")", ")", "for", "param_group", "in", "optimizer", ".", "param_groups", ":", "param_group", "[", "'lr'", "]", "=", "lr" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/examples/imagenet_eval.py#L280-L284
Cadene/pretrained-models.pytorch
8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0
examples/imagenet_eval.py
python
accuracy
(output, target, topk=(1,))
return res
Computes the precision@k for the specified values of k
Computes the precision
[ "Computes", "the", "precision" ]
def accuracy(output, target, topk=(1,)): """Computes the precision@k for the specified values of k""" maxk = max(topk) batch_size = target.size(0) _, pred = output.topk(maxk, 1, True, True) pred = pred.t() correct = pred.eq(target.view(1, -1).expand_as(pred)) res = [] for k in topk: correct_k = correct[:k].view(-1).float().sum(0) res.append(correct_k.mul_(100.0 / batch_size)) return res
[ "def", "accuracy", "(", "output", ",", "target", ",", "topk", "=", "(", "1", ",", ")", ")", ":", "maxk", "=", "max", "(", "topk", ")", "batch_size", "=", "target", ".", "size", "(", "0", ")", "_", ",", "pred", "=", "output", ".", "topk", "(", "maxk", ",", "1", ",", "True", ",", "True", ")", "pred", "=", "pred", ".", "t", "(", ")", "correct", "=", "pred", ".", "eq", "(", "target", ".", "view", "(", "1", ",", "-", "1", ")", ".", "expand_as", "(", "pred", ")", ")", "res", "=", "[", "]", "for", "k", "in", "topk", ":", "correct_k", "=", "correct", "[", ":", "k", "]", ".", "view", "(", "-", "1", ")", ".", "float", "(", ")", ".", "sum", "(", "0", ")", "res", ".", "append", "(", "correct_k", ".", "mul_", "(", "100.0", "/", "batch_size", ")", ")", "return", "res" ]
https://github.com/Cadene/pretrained-models.pytorch/blob/8aae3d8f1135b6b13fed79c1d431e3449fdbf6e0/examples/imagenet_eval.py#L287-L300
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
truncated_noise_sample
(batch_size=1, dim_z=128, truncation=1., seed=None)
return truncation * values
Create a truncated noise vector. Params: batch_size: batch size. dim_z: dimension of z truncation: truncation value to use seed: seed for the random generator Output: array of shape (batch_size, dim_z)
Create a truncated noise vector. Params: batch_size: batch size. dim_z: dimension of z truncation: truncation value to use seed: seed for the random generator Output: array of shape (batch_size, dim_z)
[ "Create", "a", "truncated", "noise", "vector", ".", "Params", ":", "batch_size", ":", "batch", "size", ".", "dim_z", ":", "dimension", "of", "z", "truncation", ":", "truncation", "value", "to", "use", "seed", ":", "seed", "for", "the", "random", "generator", "Output", ":", "array", "of", "shape", "(", "batch_size", "dim_z", ")" ]
def truncated_noise_sample(batch_size=1, dim_z=128, truncation=1., seed=None): """ Create a truncated noise vector. Params: batch_size: batch size. dim_z: dimension of z truncation: truncation value to use seed: seed for the random generator Output: array of shape (batch_size, dim_z) """ state = None if seed is None else np.random.RandomState(seed) values = truncnorm.rvs(-2, 2, size=(batch_size, dim_z), random_state=state).astype(np.float32) return truncation * values
[ "def", "truncated_noise_sample", "(", "batch_size", "=", "1", ",", "dim_z", "=", "128", ",", "truncation", "=", "1.", ",", "seed", "=", "None", ")", ":", "state", "=", "None", "if", "seed", "is", "None", "else", "np", ".", "random", ".", "RandomState", "(", "seed", ")", "values", "=", "truncnorm", ".", "rvs", "(", "-", "2", ",", "2", ",", "size", "=", "(", "batch_size", ",", "dim_z", ")", ",", "random_state", "=", "state", ")", ".", "astype", "(", "np", ".", "float32", ")", "return", "truncation", "*", "values" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L21-L33
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
convert_to_images
(obj)
return img
Convert an output tensor from BigGAN in a list of images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) Output: list of Pillow Images of size (height, width)
Convert an output tensor from BigGAN in a list of images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) Output: list of Pillow Images of size (height, width)
[ "Convert", "an", "output", "tensor", "from", "BigGAN", "in", "a", "list", "of", "images", ".", "Params", ":", "obj", ":", "tensor", "or", "numpy", "array", "of", "shape", "(", "batch_size", "channels", "height", "width", ")", "Output", ":", "list", "of", "Pillow", "Images", "of", "size", "(", "height", "width", ")" ]
def convert_to_images(obj): """ Convert an output tensor from BigGAN in a list of images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) Output: list of Pillow Images of size (height, width) """ try: import PIL except ImportError: raise ImportError("Please install Pillow to use images: pip install Pillow") if not isinstance(obj, np.ndarray): obj = obj.detach().numpy() obj = obj.transpose((0, 2, 3, 1)) obj = np.clip(((obj + 1) / 2.0) * 256, 0, 255) img = [] for i, out in enumerate(obj): out_array = np.asarray(np.uint8(out), dtype=np.uint8) img.append(PIL.Image.fromarray(out_array)) return img
[ "def", "convert_to_images", "(", "obj", ")", ":", "try", ":", "import", "PIL", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Please install Pillow to use images: pip install Pillow\"", ")", "if", "not", "isinstance", "(", "obj", ",", "np", ".", "ndarray", ")", ":", "obj", "=", "obj", ".", "detach", "(", ")", ".", "numpy", "(", ")", "obj", "=", "obj", ".", "transpose", "(", "(", "0", ",", "2", ",", "3", ",", "1", ")", ")", "obj", "=", "np", ".", "clip", "(", "(", "(", "obj", "+", "1", ")", "/", "2.0", ")", "*", "256", ",", "0", ",", "255", ")", "img", "=", "[", "]", "for", "i", ",", "out", "in", "enumerate", "(", "obj", ")", ":", "out_array", "=", "np", ".", "asarray", "(", "np", ".", "uint8", "(", "out", ")", ",", "dtype", "=", "np", ".", "uint8", ")", "img", ".", "append", "(", "PIL", ".", "Image", ".", "fromarray", "(", "out_array", ")", ")", "return", "img" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L36-L58
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
save_as_images
(obj, file_name='output')
Convert and save an output tensor from BigGAN in a list of saved images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will be saved as `file_name_{image_number}.png`
Convert and save an output tensor from BigGAN in a list of saved images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will be saved as `file_name_{image_number}.png`
[ "Convert", "and", "save", "an", "output", "tensor", "from", "BigGAN", "in", "a", "list", "of", "saved", "images", ".", "Params", ":", "obj", ":", "tensor", "or", "numpy", "array", "of", "shape", "(", "batch_size", "channels", "height", "width", ")", "file_name", ":", "path", "and", "beggingin", "of", "filename", "to", "save", ".", "Images", "will", "be", "saved", "as", "file_name_", "{", "image_number", "}", ".", "png" ]
def save_as_images(obj, file_name='output'): """ Convert and save an output tensor from BigGAN in a list of saved images. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will be saved as `file_name_{image_number}.png` """ img = convert_to_images(obj) for i, out in enumerate(img): current_file_name = file_name + '_%d.png' % i logger.info("Saving image to {}".format(current_file_name)) out.save(current_file_name, 'png')
[ "def", "save_as_images", "(", "obj", ",", "file_name", "=", "'output'", ")", ":", "img", "=", "convert_to_images", "(", "obj", ")", "for", "i", ",", "out", "in", "enumerate", "(", "img", ")", ":", "current_file_name", "=", "file_name", "+", "'_%d.png'", "%", "i", "logger", ".", "info", "(", "\"Saving image to {}\"", ".", "format", "(", "current_file_name", ")", ")", "out", ".", "save", "(", "current_file_name", ",", "'png'", ")" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L61-L73
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
display_in_terminal
(obj)
Convert and display an output tensor from BigGAN in the terminal. This function use `libsixel` and will only work in a libsixel-compatible terminal. Please refer to https://github.com/saitoha/libsixel for more details. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will be saved as `file_name_{image_number}.png`
Convert and display an output tensor from BigGAN in the terminal. This function use `libsixel` and will only work in a libsixel-compatible terminal. Please refer to https://github.com/saitoha/libsixel for more details.
[ "Convert", "and", "display", "an", "output", "tensor", "from", "BigGAN", "in", "the", "terminal", ".", "This", "function", "use", "libsixel", "and", "will", "only", "work", "in", "a", "libsixel", "-", "compatible", "terminal", ".", "Please", "refer", "to", "https", ":", "//", "github", ".", "com", "/", "saitoha", "/", "libsixel", "for", "more", "details", "." ]
def display_in_terminal(obj): """ Convert and display an output tensor from BigGAN in the terminal. This function use `libsixel` and will only work in a libsixel-compatible terminal. Please refer to https://github.com/saitoha/libsixel for more details. Params: obj: tensor or numpy array of shape (batch_size, channels, height, width) file_name: path and beggingin of filename to save. Images will be saved as `file_name_{image_number}.png` """ try: import PIL from libsixel import (sixel_output_new, sixel_dither_new, sixel_dither_initialize, sixel_dither_set_palette, sixel_dither_set_pixelformat, sixel_dither_get, sixel_encode, sixel_dither_unref, sixel_output_unref, SIXEL_PIXELFORMAT_RGBA8888, SIXEL_PIXELFORMAT_RGB888, SIXEL_PIXELFORMAT_PAL8, SIXEL_PIXELFORMAT_G8, SIXEL_PIXELFORMAT_G1) except ImportError: raise ImportError("Display in Terminal requires Pillow, libsixel " "and a libsixel compatible terminal. " "Please read info at https://github.com/saitoha/libsixel " "and install with pip install Pillow libsixel-python") s = BytesIO() images = convert_to_images(obj) widths, heights = zip(*(i.size for i in images)) output_width = sum(widths) output_height = max(heights) output_image = PIL.Image.new('RGB', (output_width, output_height)) x_offset = 0 for im in images: output_image.paste(im, (x_offset,0)) x_offset += im.size[0] try: data = output_image.tobytes() except NotImplementedError: data = output_image.tostring() output = sixel_output_new(lambda data, s: s.write(data), s) try: if output_image.mode == 'RGBA': dither = sixel_dither_new(256) sixel_dither_initialize(dither, data, output_width, output_height, SIXEL_PIXELFORMAT_RGBA8888) elif output_image.mode == 'RGB': dither = sixel_dither_new(256) sixel_dither_initialize(dither, data, output_width, output_height, SIXEL_PIXELFORMAT_RGB888) elif output_image.mode == 'P': palette = output_image.getpalette() dither = sixel_dither_new(256) sixel_dither_set_palette(dither, palette) sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_PAL8) elif output_image.mode == 'L': dither = sixel_dither_get(SIXEL_BUILTIN_G8) sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G8) elif output_image.mode == '1': dither = sixel_dither_get(SIXEL_BUILTIN_G1) sixel_dither_set_pixelformat(dither, SIXEL_PIXELFORMAT_G1) else: raise RuntimeError('unexpected output_image mode') try: sixel_encode(data, output_width, output_height, 1, dither, output) print(s.getvalue().decode('ascii')) finally: sixel_dither_unref(dither) finally: sixel_output_unref(output)
[ "def", "display_in_terminal", "(", "obj", ")", ":", "try", ":", "import", "PIL", "from", "libsixel", "import", "(", "sixel_output_new", ",", "sixel_dither_new", ",", "sixel_dither_initialize", ",", "sixel_dither_set_palette", ",", "sixel_dither_set_pixelformat", ",", "sixel_dither_get", ",", "sixel_encode", ",", "sixel_dither_unref", ",", "sixel_output_unref", ",", "SIXEL_PIXELFORMAT_RGBA8888", ",", "SIXEL_PIXELFORMAT_RGB888", ",", "SIXEL_PIXELFORMAT_PAL8", ",", "SIXEL_PIXELFORMAT_G8", ",", "SIXEL_PIXELFORMAT_G1", ")", "except", "ImportError", ":", "raise", "ImportError", "(", "\"Display in Terminal requires Pillow, libsixel \"", "\"and a libsixel compatible terminal. \"", "\"Please read info at https://github.com/saitoha/libsixel \"", "\"and install with pip install Pillow libsixel-python\"", ")", "s", "=", "BytesIO", "(", ")", "images", "=", "convert_to_images", "(", "obj", ")", "widths", ",", "heights", "=", "zip", "(", "*", "(", "i", ".", "size", "for", "i", "in", "images", ")", ")", "output_width", "=", "sum", "(", "widths", ")", "output_height", "=", "max", "(", "heights", ")", "output_image", "=", "PIL", ".", "Image", ".", "new", "(", "'RGB'", ",", "(", "output_width", ",", "output_height", ")", ")", "x_offset", "=", "0", "for", "im", "in", "images", ":", "output_image", ".", "paste", "(", "im", ",", "(", "x_offset", ",", "0", ")", ")", "x_offset", "+=", "im", ".", "size", "[", "0", "]", "try", ":", "data", "=", "output_image", ".", "tobytes", "(", ")", "except", "NotImplementedError", ":", "data", "=", "output_image", ".", "tostring", "(", ")", "output", "=", "sixel_output_new", "(", "lambda", "data", ",", "s", ":", "s", ".", "write", "(", "data", ")", ",", "s", ")", "try", ":", "if", "output_image", ".", "mode", "==", "'RGBA'", ":", "dither", "=", "sixel_dither_new", "(", "256", ")", "sixel_dither_initialize", "(", "dither", ",", "data", ",", "output_width", ",", "output_height", ",", "SIXEL_PIXELFORMAT_RGBA8888", ")", "elif", "output_image", ".", "mode", "==", "'RGB'", ":", "dither", "=", "sixel_dither_new", "(", "256", ")", "sixel_dither_initialize", "(", "dither", ",", "data", ",", "output_width", ",", "output_height", ",", "SIXEL_PIXELFORMAT_RGB888", ")", "elif", "output_image", ".", "mode", "==", "'P'", ":", "palette", "=", "output_image", ".", "getpalette", "(", ")", "dither", "=", "sixel_dither_new", "(", "256", ")", "sixel_dither_set_palette", "(", "dither", ",", "palette", ")", "sixel_dither_set_pixelformat", "(", "dither", ",", "SIXEL_PIXELFORMAT_PAL8", ")", "elif", "output_image", ".", "mode", "==", "'L'", ":", "dither", "=", "sixel_dither_get", "(", "SIXEL_BUILTIN_G8", ")", "sixel_dither_set_pixelformat", "(", "dither", ",", "SIXEL_PIXELFORMAT_G8", ")", "elif", "output_image", ".", "mode", "==", "'1'", ":", "dither", "=", "sixel_dither_get", "(", "SIXEL_BUILTIN_G1", ")", "sixel_dither_set_pixelformat", "(", "dither", ",", "SIXEL_PIXELFORMAT_G1", ")", "else", ":", "raise", "RuntimeError", "(", "'unexpected output_image mode'", ")", "try", ":", "sixel_encode", "(", "data", ",", "output_width", ",", "output_height", ",", "1", ",", "dither", ",", "output", ")", "print", "(", "s", ".", "getvalue", "(", ")", ".", "decode", "(", "'ascii'", ")", ")", "finally", ":", "sixel_dither_unref", "(", "dither", ")", "finally", ":", "sixel_output_unref", "(", "output", ")" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L76-L147
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
one_hot_from_int
(int_or_list, batch_size=1)
return array
Create a one-hot vector from a class index or a list of class indices. Params: int_or_list: int, or list of int, of the imagenet classes (between 0 and 999) batch_size: batch size. If int_or_list is an int create a batch of identical classes. If int_or_list is a list, we should have `len(int_or_list) == batch_size` Output: array of shape (batch_size, 1000)
Create a one-hot vector from a class index or a list of class indices. Params: int_or_list: int, or list of int, of the imagenet classes (between 0 and 999) batch_size: batch size. If int_or_list is an int create a batch of identical classes. If int_or_list is a list, we should have `len(int_or_list) == batch_size` Output: array of shape (batch_size, 1000)
[ "Create", "a", "one", "-", "hot", "vector", "from", "a", "class", "index", "or", "a", "list", "of", "class", "indices", ".", "Params", ":", "int_or_list", ":", "int", "or", "list", "of", "int", "of", "the", "imagenet", "classes", "(", "between", "0", "and", "999", ")", "batch_size", ":", "batch", "size", ".", "If", "int_or_list", "is", "an", "int", "create", "a", "batch", "of", "identical", "classes", ".", "If", "int_or_list", "is", "a", "list", "we", "should", "have", "len", "(", "int_or_list", ")", "==", "batch_size", "Output", ":", "array", "of", "shape", "(", "batch_size", "1000", ")" ]
def one_hot_from_int(int_or_list, batch_size=1): """ Create a one-hot vector from a class index or a list of class indices. Params: int_or_list: int, or list of int, of the imagenet classes (between 0 and 999) batch_size: batch size. If int_or_list is an int create a batch of identical classes. If int_or_list is a list, we should have `len(int_or_list) == batch_size` Output: array of shape (batch_size, 1000) """ if isinstance(int_or_list, int): int_or_list = [int_or_list] if len(int_or_list) == 1 and batch_size > 1: int_or_list = [int_or_list[0]] * batch_size assert batch_size == len(int_or_list) array = np.zeros((batch_size, NUM_CLASSES), dtype=np.float32) for i, j in enumerate(int_or_list): array[i, j] = 1.0 return array
[ "def", "one_hot_from_int", "(", "int_or_list", ",", "batch_size", "=", "1", ")", ":", "if", "isinstance", "(", "int_or_list", ",", "int", ")", ":", "int_or_list", "=", "[", "int_or_list", "]", "if", "len", "(", "int_or_list", ")", "==", "1", "and", "batch_size", ">", "1", ":", "int_or_list", "=", "[", "int_or_list", "[", "0", "]", "]", "*", "batch_size", "assert", "batch_size", "==", "len", "(", "int_or_list", ")", "array", "=", "np", ".", "zeros", "(", "(", "batch_size", ",", "NUM_CLASSES", ")", ",", "dtype", "=", "np", ".", "float32", ")", "for", "i", ",", "j", "in", "enumerate", "(", "int_or_list", ")", ":", "array", "[", "i", ",", "j", "]", "=", "1.0", "return", "array" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L150-L171
huggingface/pytorch-pretrained-BigGAN
1e18aed2dff75db51428f13b940c38b923eb4a3d
pytorch_pretrained_biggan/utils.py
python
one_hot_from_names
(class_name_or_list, batch_size=1)
return one_hot_from_int(classes, batch_size=batch_size)
Create a one-hot vector from the name of an imagenet class ('tennis ball', 'daisy', ...). We use NLTK's wordnet search to try to find the relevant synset of ImageNet and take the first one. If we can't find it direcly, we look at the hyponyms and hypernyms of the class name. Params: class_name_or_list: string containing the name of an imagenet object or a list of such strings (for a batch). Output: array of shape (batch_size, 1000)
Create a one-hot vector from the name of an imagenet class ('tennis ball', 'daisy', ...). We use NLTK's wordnet search to try to find the relevant synset of ImageNet and take the first one. If we can't find it direcly, we look at the hyponyms and hypernyms of the class name.
[ "Create", "a", "one", "-", "hot", "vector", "from", "the", "name", "of", "an", "imagenet", "class", "(", "tennis", "ball", "daisy", "...", ")", ".", "We", "use", "NLTK", "s", "wordnet", "search", "to", "try", "to", "find", "the", "relevant", "synset", "of", "ImageNet", "and", "take", "the", "first", "one", ".", "If", "we", "can", "t", "find", "it", "direcly", "we", "look", "at", "the", "hyponyms", "and", "hypernyms", "of", "the", "class", "name", "." ]
def one_hot_from_names(class_name_or_list, batch_size=1): """ Create a one-hot vector from the name of an imagenet class ('tennis ball', 'daisy', ...). We use NLTK's wordnet search to try to find the relevant synset of ImageNet and take the first one. If we can't find it direcly, we look at the hyponyms and hypernyms of the class name. Params: class_name_or_list: string containing the name of an imagenet object or a list of such strings (for a batch). Output: array of shape (batch_size, 1000) """ try: from nltk.corpus import wordnet as wn except ImportError: raise ImportError("You need to install nltk to use this function") if not isinstance(class_name_or_list, (list, tuple)): class_name_or_list = [class_name_or_list] else: batch_size = max(batch_size, len(class_name_or_list)) classes = [] for class_name in class_name_or_list: class_name = class_name.replace(" ", "_") original_synsets = wn.synsets(class_name) original_synsets = list(filter(lambda s: s.pos() == 'n', original_synsets)) # keep only names if not original_synsets: return None possible_synsets = list(filter(lambda s: s.offset() in IMAGENET, original_synsets)) if possible_synsets: classes.append(IMAGENET[possible_synsets[0].offset()]) else: # try hypernyms and hyponyms possible_synsets = sum([s.hypernyms() + s.hyponyms() for s in original_synsets], []) possible_synsets = list(filter(lambda s: s.offset() in IMAGENET, possible_synsets)) if possible_synsets: classes.append(IMAGENET[possible_synsets[0].offset()]) return one_hot_from_int(classes, batch_size=batch_size)
[ "def", "one_hot_from_names", "(", "class_name_or_list", ",", "batch_size", "=", "1", ")", ":", "try", ":", "from", "nltk", ".", "corpus", "import", "wordnet", "as", "wn", "except", "ImportError", ":", "raise", "ImportError", "(", "\"You need to install nltk to use this function\"", ")", "if", "not", "isinstance", "(", "class_name_or_list", ",", "(", "list", ",", "tuple", ")", ")", ":", "class_name_or_list", "=", "[", "class_name_or_list", "]", "else", ":", "batch_size", "=", "max", "(", "batch_size", ",", "len", "(", "class_name_or_list", ")", ")", "classes", "=", "[", "]", "for", "class_name", "in", "class_name_or_list", ":", "class_name", "=", "class_name", ".", "replace", "(", "\" \"", ",", "\"_\"", ")", "original_synsets", "=", "wn", ".", "synsets", "(", "class_name", ")", "original_synsets", "=", "list", "(", "filter", "(", "lambda", "s", ":", "s", ".", "pos", "(", ")", "==", "'n'", ",", "original_synsets", ")", ")", "# keep only names", "if", "not", "original_synsets", ":", "return", "None", "possible_synsets", "=", "list", "(", "filter", "(", "lambda", "s", ":", "s", ".", "offset", "(", ")", "in", "IMAGENET", ",", "original_synsets", ")", ")", "if", "possible_synsets", ":", "classes", ".", "append", "(", "IMAGENET", "[", "possible_synsets", "[", "0", "]", ".", "offset", "(", ")", "]", ")", "else", ":", "# try hypernyms and hyponyms", "possible_synsets", "=", "sum", "(", "[", "s", ".", "hypernyms", "(", ")", "+", "s", ".", "hyponyms", "(", ")", "for", "s", "in", "original_synsets", "]", ",", "[", "]", ")", "possible_synsets", "=", "list", "(", "filter", "(", "lambda", "s", ":", "s", ".", "offset", "(", ")", "in", "IMAGENET", ",", "possible_synsets", ")", ")", "if", "possible_synsets", ":", "classes", ".", "append", "(", "IMAGENET", "[", "possible_synsets", "[", "0", "]", ".", "offset", "(", ")", "]", ")", "return", "one_hot_from_int", "(", "classes", ",", "batch_size", "=", "batch_size", ")" ]
https://github.com/huggingface/pytorch-pretrained-BigGAN/blob/1e18aed2dff75db51428f13b940c38b923eb4a3d/pytorch_pretrained_biggan/utils.py#L174-L213
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-06-model-serving-api/house-prices-api/app/api.py
python
health
()
return health.dict()
Root Get
Root Get
[ "Root", "Get" ]
def health() -> dict: """ Root Get """ health = schemas.Health( name=settings.PROJECT_NAME, api_version=__version__, model_version=model_version ) return health.dict()
[ "def", "health", "(", ")", "->", "dict", ":", "health", "=", "schemas", ".", "Health", "(", "name", "=", "settings", ".", "PROJECT_NAME", ",", "api_version", "=", "__version__", ",", "model_version", "=", "model_version", ")", "return", "health", ".", "dict", "(", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-06-model-serving-api/house-prices-api/app/api.py#L19-L27
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-06-model-serving-api/house-prices-api/app/api.py
python
predict
(input_data: schemas.MultipleHouseDataInputs)
return results
Make house price predictions with the TID regression model
Make house price predictions with the TID regression model
[ "Make", "house", "price", "predictions", "with", "the", "TID", "regression", "model" ]
async def predict(input_data: schemas.MultipleHouseDataInputs) -> Any: """ Make house price predictions with the TID regression model """ input_df = pd.DataFrame(jsonable_encoder(input_data.inputs)) # Advanced: You can improve performance of your API by rewriting the # `make prediction` function to be async and using await here. logger.info(f"Making prediction on inputs: {input_data.inputs}") results = make_prediction(input_data=input_df.replace({np.nan: None})) if results["errors"] is not None: logger.warning(f"Prediction validation error: {results.get('errors')}") raise HTTPException(status_code=400, detail=json.loads(results["errors"])) logger.info(f"Prediction results: {results.get('predictions')}") return results
[ "async", "def", "predict", "(", "input_data", ":", "schemas", ".", "MultipleHouseDataInputs", ")", "->", "Any", ":", "input_df", "=", "pd", ".", "DataFrame", "(", "jsonable_encoder", "(", "input_data", ".", "inputs", ")", ")", "# Advanced: You can improve performance of your API by rewriting the", "# `make prediction` function to be async and using await here.", "logger", ".", "info", "(", "f\"Making prediction on inputs: {input_data.inputs}\"", ")", "results", "=", "make_prediction", "(", "input_data", "=", "input_df", ".", "replace", "(", "{", "np", ".", "nan", ":", "None", "}", ")", ")", "if", "results", "[", "\"errors\"", "]", "is", "not", "None", ":", "logger", ".", "warning", "(", "f\"Prediction validation error: {results.get('errors')}\"", ")", "raise", "HTTPException", "(", "status_code", "=", "400", ",", "detail", "=", "json", ".", "loads", "(", "results", "[", "\"errors\"", "]", ")", ")", "logger", ".", "info", "(", "f\"Prediction results: {results.get('predictions')}\"", ")", "return", "results" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-06-model-serving-api/house-prices-api/app/api.py#L31-L49
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-06-model-serving-api/house-prices-api/app/config.py
python
setup_app_logging
(config: Settings)
Prepare custom logging for our application.
Prepare custom logging for our application.
[ "Prepare", "custom", "logging", "for", "our", "application", "." ]
def setup_app_logging(config: Settings) -> None: """Prepare custom logging for our application.""" LOGGERS = ("uvicorn.asgi", "uvicorn.access") logging.getLogger().handlers = [InterceptHandler()] for logger_name in LOGGERS: logging_logger = logging.getLogger(logger_name) logging_logger.handlers = [InterceptHandler(level=config.logging.LOGGING_LEVEL)] logger.configure( handlers=[{"sink": sys.stderr, "level": config.logging.LOGGING_LEVEL}] )
[ "def", "setup_app_logging", "(", "config", ":", "Settings", ")", "->", "None", ":", "LOGGERS", "=", "(", "\"uvicorn.asgi\"", ",", "\"uvicorn.access\"", ")", "logging", ".", "getLogger", "(", ")", ".", "handlers", "=", "[", "InterceptHandler", "(", ")", "]", "for", "logger_name", "in", "LOGGERS", ":", "logging_logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logging_logger", ".", "handlers", "=", "[", "InterceptHandler", "(", "level", "=", "config", ".", "logging", ".", "LOGGING_LEVEL", ")", "]", "logger", ".", "configure", "(", "handlers", "=", "[", "{", "\"sink\"", ":", "sys", ".", "stderr", ",", "\"level\"", ":", "config", ".", "logging", ".", "LOGGING_LEVEL", "}", "]", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-06-model-serving-api/house-prices-api/app/config.py#L56-L67
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-06-model-serving-api/house-prices-api/app/main.py
python
index
(request: Request)
return HTMLResponse(content=body)
Basic HTML response.
Basic HTML response.
[ "Basic", "HTML", "response", "." ]
def index(request: Request) -> Any: """Basic HTML response.""" body = ( "<html>" "<body style='padding: 10px;'>" "<h1>Welcome to the API</h1>" "<div>" "Check the docs: <a href='/docs'>here</a>" "</div>" "</body>" "</html>" ) return HTMLResponse(content=body)
[ "def", "index", "(", "request", ":", "Request", ")", "->", "Any", ":", "body", "=", "(", "\"<html>\"", "\"<body style='padding: 10px;'>\"", "\"<h1>Welcome to the API</h1>\"", "\"<div>\"", "\"Check the docs: <a href='/docs'>here</a>\"", "\"</div>\"", "\"</body>\"", "\"</html>\"", ")", "return", "HTMLResponse", "(", "content", "=", "body", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-06-model-serving-api/house-prices-api/app/main.py#L23-L36
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/train_pipeline.py
python
run_training
(save_result: bool = True)
Train a Convolutional Neural Network.
Train a Convolutional Neural Network.
[ "Train", "a", "Convolutional", "Neural", "Network", "." ]
def run_training(save_result: bool = True): """Train a Convolutional Neural Network.""" images_df = dm.load_image_paths(config.DATA_FOLDER) X_train, X_test, y_train, y_test = dm.get_train_test_target(images_df) enc = pp.TargetEncoder() enc.fit(y_train) y_train = enc.transform(y_train) pipe.pipe.fit(X_train, y_train) if save_result: joblib.dump(enc, config.ENCODER_PATH) dm.save_pipeline_keras(pipe.pipe)
[ "def", "run_training", "(", "save_result", ":", "bool", "=", "True", ")", ":", "images_df", "=", "dm", ".", "load_image_paths", "(", "config", ".", "DATA_FOLDER", ")", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "dm", ".", "get_train_test_target", "(", "images_df", ")", "enc", "=", "pp", ".", "TargetEncoder", "(", ")", "enc", ".", "fit", "(", "y_train", ")", "y_train", "=", "enc", ".", "transform", "(", "y_train", ")", "pipe", ".", "pipe", ".", "fit", "(", "X_train", ",", "y_train", ")", "if", "save_result", ":", "joblib", ".", "dump", "(", "enc", ",", "config", ".", "ENCODER_PATH", ")", "dm", ".", "save_pipeline_keras", "(", "pipe", ".", "pipe", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/train_pipeline.py#L9-L23
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/predict.py
python
make_single_prediction
(*, image_name: str, image_directory: str)
return dict(predictions=predictions, readable_predictions=readable_predictions, version=_version)
Make a single prediction using the saved model pipeline. Args: image_name: Filename of the image to classify image_directory: Location of the image to classify Returns Dictionary with both raw predictions and readable values.
Make a single prediction using the saved model pipeline.
[ "Make", "a", "single", "prediction", "using", "the", "saved", "model", "pipeline", "." ]
def make_single_prediction(*, image_name: str, image_directory: str): """Make a single prediction using the saved model pipeline. Args: image_name: Filename of the image to classify image_directory: Location of the image to classify Returns Dictionary with both raw predictions and readable values. """ image_df = dm.load_single_image( data_folder=image_directory, filename=image_name) prepared_df = image_df['image'].reset_index(drop=True) _logger.info(f'received input array: {prepared_df}, ' f'filename: {image_name}') predictions = KERAS_PIPELINE.predict(prepared_df) readable_predictions = ENCODER.encoder.inverse_transform(predictions) _logger.info(f'Made prediction: {predictions}' f' with model version: {_version}') return dict(predictions=predictions, readable_predictions=readable_predictions, version=_version)
[ "def", "make_single_prediction", "(", "*", ",", "image_name", ":", "str", ",", "image_directory", ":", "str", ")", ":", "image_df", "=", "dm", ".", "load_single_image", "(", "data_folder", "=", "image_directory", ",", "filename", "=", "image_name", ")", "prepared_df", "=", "image_df", "[", "'image'", "]", ".", "reset_index", "(", "drop", "=", "True", ")", "_logger", ".", "info", "(", "f'received input array: {prepared_df}, '", "f'filename: {image_name}'", ")", "predictions", "=", "KERAS_PIPELINE", ".", "predict", "(", "prepared_df", ")", "readable_predictions", "=", "ENCODER", ".", "encoder", ".", "inverse_transform", "(", "predictions", ")", "_logger", ".", "info", "(", "f'Made prediction: {predictions}'", "f' with model version: {_version}'", ")", "return", "dict", "(", "predictions", "=", "predictions", ",", "readable_predictions", "=", "readable_predictions", ",", "version", "=", "_version", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/predict.py#L13-L40
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/predict.py
python
make_bulk_prediction
(*, images_df: pd.Series)
return dict(predictions=predictions, readable_predictions=readable_predictions, version=_version)
Make multiple predictions using the saved model pipeline. Currently, this function is primarily for testing purposes, allowing us to pass in a directory of images for running bulk predictions. Args: images_df: Pandas series of images Returns Dictionary with both raw predictions and their classifications.
Make multiple predictions using the saved model pipeline.
[ "Make", "multiple", "predictions", "using", "the", "saved", "model", "pipeline", "." ]
def make_bulk_prediction(*, images_df: pd.Series) -> dict: """Make multiple predictions using the saved model pipeline. Currently, this function is primarily for testing purposes, allowing us to pass in a directory of images for running bulk predictions. Args: images_df: Pandas series of images Returns Dictionary with both raw predictions and their classifications. """ _logger.info(f'received input df: {images_df}') predictions = KERAS_PIPELINE.predict(images_df) readable_predictions = ENCODER.encoder.inverse_transform(predictions) _logger.info(f'Made predictions: {predictions}' f' with model version: {_version}') return dict(predictions=predictions, readable_predictions=readable_predictions, version=_version)
[ "def", "make_bulk_prediction", "(", "*", ",", "images_df", ":", "pd", ".", "Series", ")", "->", "dict", ":", "_logger", ".", "info", "(", "f'received input df: {images_df}'", ")", "predictions", "=", "KERAS_PIPELINE", ".", "predict", "(", "images_df", ")", "readable_predictions", "=", "ENCODER", ".", "encoder", ".", "inverse_transform", "(", "predictions", ")", "_logger", ".", "info", "(", "f'Made predictions: {predictions}'", "f' with model version: {_version}'", ")", "return", "dict", "(", "predictions", "=", "predictions", ",", "readable_predictions", "=", "readable_predictions", ",", "version", "=", "_version", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/predict.py#L43-L67
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
load_single_image
(data_folder: str, filename: str)
return images_df
Makes dataframe with image path and target.
Makes dataframe with image path and target.
[ "Makes", "dataframe", "with", "image", "path", "and", "target", "." ]
def load_single_image(data_folder: str, filename: str) -> pd.DataFrame: """Makes dataframe with image path and target.""" image_df = [] # search for specific image in directory for image_path in glob(os.path.join(data_folder, f'{filename}')): tmp = pd.DataFrame([image_path, 'unknown']).T image_df.append(tmp) # concatenate the final df images_df = pd.concat(image_df, axis=0, ignore_index=True) images_df.columns = ['image', 'target'] return images_df
[ "def", "load_single_image", "(", "data_folder", ":", "str", ",", "filename", ":", "str", ")", "->", "pd", ".", "DataFrame", ":", "image_df", "=", "[", "]", "# search for specific image in directory", "for", "image_path", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "data_folder", ",", "f'{filename}'", ")", ")", ":", "tmp", "=", "pd", ".", "DataFrame", "(", "[", "image_path", ",", "'unknown'", "]", ")", ".", "T", "image_df", ".", "append", "(", "tmp", ")", "# concatenate the final df", "images_df", "=", "pd", ".", "concat", "(", "image_df", ",", "axis", "=", "0", ",", "ignore_index", "=", "True", ")", "images_df", ".", "columns", "=", "[", "'image'", ",", "'target'", "]", "return", "images_df" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L21-L35
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
load_image_paths
(data_folder: str)
return images_df
Makes dataframe with image path and target.
Makes dataframe with image path and target.
[ "Makes", "dataframe", "with", "image", "path", "and", "target", "." ]
def load_image_paths(data_folder: str) -> pd.DataFrame: """Makes dataframe with image path and target.""" images_df = [] # navigate within each folder for class_folder_name in os.listdir(data_folder): class_folder_path = os.path.join(data_folder, class_folder_name) # collect every image path for image_path in glob(os.path.join(class_folder_path, "*.png")): tmp = pd.DataFrame([image_path, class_folder_name]).T images_df.append(tmp) # concatenate the final df images_df = pd.concat(images_df, axis=0, ignore_index=True) images_df.columns = ['image', 'target'] return images_df
[ "def", "load_image_paths", "(", "data_folder", ":", "str", ")", "->", "pd", ".", "DataFrame", ":", "images_df", "=", "[", "]", "# navigate within each folder", "for", "class_folder_name", "in", "os", ".", "listdir", "(", "data_folder", ")", ":", "class_folder_path", "=", "os", ".", "path", ".", "join", "(", "data_folder", ",", "class_folder_name", ")", "# collect every image path", "for", "image_path", "in", "glob", "(", "os", ".", "path", ".", "join", "(", "class_folder_path", ",", "\"*.png\"", ")", ")", ":", "tmp", "=", "pd", ".", "DataFrame", "(", "[", "image_path", ",", "class_folder_name", "]", ")", ".", "T", "images_df", ".", "append", "(", "tmp", ")", "# concatenate the final df", "images_df", "=", "pd", ".", "concat", "(", "images_df", ",", "axis", "=", "0", ",", "ignore_index", "=", "True", ")", "images_df", ".", "columns", "=", "[", "'image'", ",", "'target'", "]", "return", "images_df" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L38-L56
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
get_train_test_target
(df: pd.DataFrame)
return X_train, X_test, y_train, y_test
Split a dataset into train and test segments.
Split a dataset into train and test segments.
[ "Split", "a", "dataset", "into", "train", "and", "test", "segments", "." ]
def get_train_test_target(df: pd.DataFrame): """Split a dataset into train and test segments.""" X_train, X_test, y_train, y_test = train_test_split(df['image'], df['target'], test_size=0.20, random_state=101) X_train.reset_index(drop=True, inplace=True) X_test.reset_index(drop=True, inplace=True) y_train.reset_index(drop=True, inplace=True) y_test.reset_index(drop=True, inplace=True) return X_train, X_test, y_train, y_test
[ "def", "get_train_test_target", "(", "df", ":", "pd", ".", "DataFrame", ")", ":", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "df", "[", "'image'", "]", ",", "df", "[", "'target'", "]", ",", "test_size", "=", "0.20", ",", "random_state", "=", "101", ")", "X_train", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "=", "True", ")", "X_test", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "=", "True", ")", "y_train", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "=", "True", ")", "y_test", ".", "reset_index", "(", "drop", "=", "True", ",", "inplace", "=", "True", ")", "return", "X_train", ",", "X_test", ",", "y_train", ",", "y_test" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L59-L73
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
save_pipeline_keras
(model)
Persist keras model to disk.
Persist keras model to disk.
[ "Persist", "keras", "model", "to", "disk", "." ]
def save_pipeline_keras(model) -> None: """Persist keras model to disk.""" joblib.dump(model.named_steps['dataset'], config.PIPELINE_PATH) joblib.dump(model.named_steps['cnn_model'].classes_, config.CLASSES_PATH) model.named_steps['cnn_model'].model.save(str(config.MODEL_PATH)) remove_old_pipelines( files_to_keep=[config.MODEL_FILE_NAME, config.ENCODER_FILE_NAME, config.PIPELINE_FILE_NAME, config.CLASSES_FILE_NAME])
[ "def", "save_pipeline_keras", "(", "model", ")", "->", "None", ":", "joblib", ".", "dump", "(", "model", ".", "named_steps", "[", "'dataset'", "]", ",", "config", ".", "PIPELINE_PATH", ")", "joblib", ".", "dump", "(", "model", ".", "named_steps", "[", "'cnn_model'", "]", ".", "classes_", ",", "config", ".", "CLASSES_PATH", ")", "model", ".", "named_steps", "[", "'cnn_model'", "]", ".", "model", ".", "save", "(", "str", "(", "config", ".", "MODEL_PATH", ")", ")", "remove_old_pipelines", "(", "files_to_keep", "=", "[", "config", ".", "MODEL_FILE_NAME", ",", "config", ".", "ENCODER_FILE_NAME", ",", "config", ".", "PIPELINE_FILE_NAME", ",", "config", ".", "CLASSES_FILE_NAME", "]", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L76-L85
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
load_pipeline_keras
()
return Pipeline([ ('dataset', dataset), ('cnn_model', classifier) ])
Load a Keras Pipeline from disk.
Load a Keras Pipeline from disk.
[ "Load", "a", "Keras", "Pipeline", "from", "disk", "." ]
def load_pipeline_keras() -> Pipeline: """Load a Keras Pipeline from disk.""" dataset = joblib.load(config.PIPELINE_PATH) build_model = lambda: load_model(config.MODEL_PATH) classifier = KerasClassifier(build_fn=build_model, batch_size=config.BATCH_SIZE, validation_split=10, epochs=config.EPOCHS, verbose=2, callbacks=m.callbacks_list, # image_size = config.IMAGE_SIZE ) classifier.classes_ = joblib.load(config.CLASSES_PATH) classifier.model = build_model() return Pipeline([ ('dataset', dataset), ('cnn_model', classifier) ])
[ "def", "load_pipeline_keras", "(", ")", "->", "Pipeline", ":", "dataset", "=", "joblib", ".", "load", "(", "config", ".", "PIPELINE_PATH", ")", "build_model", "=", "lambda", ":", "load_model", "(", "config", ".", "MODEL_PATH", ")", "classifier", "=", "KerasClassifier", "(", "build_fn", "=", "build_model", ",", "batch_size", "=", "config", ".", "BATCH_SIZE", ",", "validation_split", "=", "10", ",", "epochs", "=", "config", ".", "EPOCHS", ",", "verbose", "=", "2", ",", "callbacks", "=", "m", ".", "callbacks_list", ",", "# image_size = config.IMAGE_SIZE", ")", "classifier", ".", "classes_", "=", "joblib", ".", "load", "(", "config", ".", "CLASSES_PATH", ")", "classifier", ".", "model", "=", "build_model", "(", ")", "return", "Pipeline", "(", "[", "(", "'dataset'", ",", "dataset", ")", ",", "(", "'cnn_model'", ",", "classifier", ")", "]", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L88-L110
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/neural_network_model/neural_network_model/processing/data_management.py
python
remove_old_pipelines
(*, files_to_keep: t.List[str])
Remove old model pipelines, models, encoders and classes. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications.
Remove old model pipelines, models, encoders and classes.
[ "Remove", "old", "model", "pipelines", "models", "encoders", "and", "classes", "." ]
def remove_old_pipelines(*, files_to_keep: t.List[str]) -> None: """ Remove old model pipelines, models, encoders and classes. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications. """ do_not_delete = files_to_keep + ['__init__.py'] for model_file in Path(config.TRAINED_MODEL_DIR).iterdir(): if model_file.name not in do_not_delete: model_file.unlink()
[ "def", "remove_old_pipelines", "(", "*", ",", "files_to_keep", ":", "t", ".", "List", "[", "str", "]", ")", "->", "None", ":", "do_not_delete", "=", "files_to_keep", "+", "[", "'__init__.py'", "]", "for", "model_file", "in", "Path", "(", "config", ".", "TRAINED_MODEL_DIR", ")", ".", "iterdir", "(", ")", ":", "if", "model_file", ".", "name", "not", "in", "do_not_delete", ":", "model_file", ".", "unlink", "(", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/neural_network_model/neural_network_model/processing/data_management.py#L119-L130
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/ml_api/api/validation.py
python
_filter_error_rows
(errors: dict, validated_input: t.List[dict] )
return validated_input
Remove input data rows with errors.
Remove input data rows with errors.
[ "Remove", "input", "data", "rows", "with", "errors", "." ]
def _filter_error_rows(errors: dict, validated_input: t.List[dict] ) -> t.List[dict]: """Remove input data rows with errors.""" indexes = errors.keys() # delete them in reverse order so that you # don't throw off the subsequent indexes. for index in sorted(indexes, reverse=True): del validated_input[index] return validated_input
[ "def", "_filter_error_rows", "(", "errors", ":", "dict", ",", "validated_input", ":", "t", ".", "List", "[", "dict", "]", ")", "->", "t", ".", "List", "[", "dict", "]", ":", "indexes", "=", "errors", ".", "keys", "(", ")", "# delete them in reverse order so that you", "# don't throw off the subsequent indexes.", "for", "index", "in", "sorted", "(", "indexes", ",", "reverse", "=", "True", ")", ":", "del", "validated_input", "[", "index", "]", "return", "validated_input" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/ml_api/api/validation.py#L103-L114
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/ml_api/api/validation.py
python
validate_inputs
(input_data)
return validated_input, errors
Check prediction inputs against schema.
Check prediction inputs against schema.
[ "Check", "prediction", "inputs", "against", "schema", "." ]
def validate_inputs(input_data): """Check prediction inputs against schema.""" # set many=True to allow passing in a list schema = HouseDataRequestSchema(strict=True, many=True) # convert syntax error field names (beginning with numbers) for dict in input_data: for key, value in SYNTAX_ERROR_FIELD_MAP.items(): dict[value] = dict[key] del dict[key] errors = None try: schema.load(input_data) except ValidationError as exc: errors = exc.messages # convert syntax error field names back # this is a hack - never name your data # fields with numbers as the first letter. for dict in input_data: for key, value in SYNTAX_ERROR_FIELD_MAP.items(): dict[key] = dict[value] del dict[value] if errors: validated_input = _filter_error_rows( errors=errors, validated_input=input_data) else: validated_input = input_data return validated_input, errors
[ "def", "validate_inputs", "(", "input_data", ")", ":", "# set many=True to allow passing in a list", "schema", "=", "HouseDataRequestSchema", "(", "strict", "=", "True", ",", "many", "=", "True", ")", "# convert syntax error field names (beginning with numbers)", "for", "dict", "in", "input_data", ":", "for", "key", ",", "value", "in", "SYNTAX_ERROR_FIELD_MAP", ".", "items", "(", ")", ":", "dict", "[", "value", "]", "=", "dict", "[", "key", "]", "del", "dict", "[", "key", "]", "errors", "=", "None", "try", ":", "schema", ".", "load", "(", "input_data", ")", "except", "ValidationError", "as", "exc", ":", "errors", "=", "exc", ".", "messages", "# convert syntax error field names back", "# this is a hack - never name your data", "# fields with numbers as the first letter.", "for", "dict", "in", "input_data", ":", "for", "key", ",", "value", "in", "SYNTAX_ERROR_FIELD_MAP", ".", "items", "(", ")", ":", "dict", "[", "key", "]", "=", "dict", "[", "value", "]", "del", "dict", "[", "value", "]", "if", "errors", ":", "validated_input", "=", "_filter_error_rows", "(", "errors", "=", "errors", ",", "validated_input", "=", "input_data", ")", "else", ":", "validated_input", "=", "input_data", "return", "validated_input", ",", "errors" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/ml_api/api/validation.py#L117-L150
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/ml_api/api/config.py
python
get_logger
(*, logger_name)
return logger
Get logger with prepared handlers.
Get logger with prepared handlers.
[ "Get", "logger", "with", "prepared", "handlers", "." ]
def get_logger(*, logger_name): """Get logger with prepared handlers.""" logger = logging.getLogger(logger_name) logger.setLevel(logging.INFO) logger.addHandler(get_console_handler()) logger.addHandler(get_file_handler()) logger.propagate = False return logger
[ "def", "get_logger", "(", "*", ",", "logger_name", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "logger_name", ")", "logger", ".", "setLevel", "(", "logging", ".", "INFO", ")", "logger", ".", "addHandler", "(", "get_console_handler", "(", ")", ")", "logger", ".", "addHandler", "(", "get_file_handler", "(", ")", ")", "logger", ".", "propagate", "=", "False", "return", "logger" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/ml_api/api/config.py#L35-L46
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/ml_api/api/app.py
python
create_app
(*, config_object)
return flask_app
Create a flask app instance.
Create a flask app instance.
[ "Create", "a", "flask", "app", "instance", "." ]
def create_app(*, config_object) -> Flask: """Create a flask app instance.""" flask_app = Flask('ml_api') flask_app.config.from_object(config_object) # import blueprints from api.controller import prediction_app flask_app.register_blueprint(prediction_app) _logger.debug('Application instance created') return flask_app
[ "def", "create_app", "(", "*", ",", "config_object", ")", "->", "Flask", ":", "flask_app", "=", "Flask", "(", "'ml_api'", ")", "flask_app", ".", "config", ".", "from_object", "(", "config_object", ")", "# import blueprints", "from", "api", ".", "controller", "import", "prediction_app", "flask_app", ".", "register_blueprint", "(", "prediction_app", ")", "_logger", ".", "debug", "(", "'Application instance created'", ")", "return", "flask_app" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/ml_api/api/app.py#L9-L20
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/train_pipeline.py
python
run_training
()
Train the model.
Train the model.
[ "Train", "the", "model", "." ]
def run_training() -> None: """Train the model.""" # read training data data = load_dataset(file_name=config.TRAINING_DATA_FILE) # divide train and test X_train, X_test, y_train, y_test = train_test_split( data[config.FEATURES], data[config.TARGET], test_size=0.1, random_state=0 ) # we are setting the seed here # transform the target y_train = np.log(y_train) pipeline.price_pipe.fit(X_train[config.FEATURES], y_train) _logger.info(f"saving model version: {_version}") save_pipeline(pipeline_to_persist=pipeline.price_pipe)
[ "def", "run_training", "(", ")", "->", "None", ":", "# read training data", "data", "=", "load_dataset", "(", "file_name", "=", "config", ".", "TRAINING_DATA_FILE", ")", "# divide train and test", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "data", "[", "config", ".", "FEATURES", "]", ",", "data", "[", "config", ".", "TARGET", "]", ",", "test_size", "=", "0.1", ",", "random_state", "=", "0", ")", "# we are setting the seed here", "# transform the target", "y_train", "=", "np", ".", "log", "(", "y_train", ")", "pipeline", ".", "price_pipe", ".", "fit", "(", "X_train", "[", "config", ".", "FEATURES", "]", ",", "y_train", ")", "_logger", ".", "info", "(", "f\"saving model version: {_version}\"", ")", "save_pipeline", "(", "pipeline_to_persist", "=", "pipeline", ".", "price_pipe", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/train_pipeline.py#L15-L32
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/predict.py
python
make_prediction
(*, input_data: t.Union[pd.DataFrame, dict], )
return results
Make a prediction using a saved model pipeline. Args: input_data: Array of model prediction inputs. Returns: Predictions for each input row, as well as the model version.
Make a prediction using a saved model pipeline.
[ "Make", "a", "prediction", "using", "a", "saved", "model", "pipeline", "." ]
def make_prediction(*, input_data: t.Union[pd.DataFrame, dict], ) -> dict: """Make a prediction using a saved model pipeline. Args: input_data: Array of model prediction inputs. Returns: Predictions for each input row, as well as the model version. """ data = pd.DataFrame(input_data) validated_data = validate_inputs(input_data=data) prediction = _price_pipe.predict(validated_data[config.FEATURES]) output = np.exp(prediction) results = {"predictions": output, "version": _version} _logger.info( f"Making predictions with model version: {_version} " f"Inputs: {validated_data} " f"Predictions: {results}" ) return results
[ "def", "make_prediction", "(", "*", ",", "input_data", ":", "t", ".", "Union", "[", "pd", ".", "DataFrame", ",", "dict", "]", ",", ")", "->", "dict", ":", "data", "=", "pd", ".", "DataFrame", "(", "input_data", ")", "validated_data", "=", "validate_inputs", "(", "input_data", "=", "data", ")", "prediction", "=", "_price_pipe", ".", "predict", "(", "validated_data", "[", "config", ".", "FEATURES", "]", ")", "output", "=", "np", ".", "exp", "(", "prediction", ")", "results", "=", "{", "\"predictions\"", ":", "output", ",", "\"version\"", ":", "_version", "}", "_logger", ".", "info", "(", "f\"Making predictions with model version: {_version} \"", "f\"Inputs: {validated_data} \"", "f\"Predictions: {results}\"", ")", "return", "results" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/predict.py#L19-L45
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/validation.py
python
validate_inputs
(input_data: pd.DataFrame)
return validated_data
Check model inputs for unprocessable values.
Check model inputs for unprocessable values.
[ "Check", "model", "inputs", "for", "unprocessable", "values", "." ]
def validate_inputs(input_data: pd.DataFrame) -> pd.DataFrame: """Check model inputs for unprocessable values.""" validated_data = input_data.copy() # check for numerical variables with NA not seen during training if input_data[config.NUMERICAL_NA_NOT_ALLOWED].isnull().any().any(): validated_data = validated_data.dropna( axis=0, subset=config.NUMERICAL_NA_NOT_ALLOWED ) # check for categorical variables with NA not seen during training if input_data[config.CATEGORICAL_NA_NOT_ALLOWED].isnull().any().any(): validated_data = validated_data.dropna( axis=0, subset=config.CATEGORICAL_NA_NOT_ALLOWED ) # check for values <= 0 for the log transformed variables if (input_data[config.NUMERICALS_LOG_VARS] <= 0).any().any(): vars_with_neg_values = config.NUMERICALS_LOG_VARS[ (input_data[config.NUMERICALS_LOG_VARS] <= 0).any() ] validated_data = validated_data[validated_data[vars_with_neg_values] > 0] return validated_data
[ "def", "validate_inputs", "(", "input_data", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "validated_data", "=", "input_data", ".", "copy", "(", ")", "# check for numerical variables with NA not seen during training", "if", "input_data", "[", "config", ".", "NUMERICAL_NA_NOT_ALLOWED", "]", ".", "isnull", "(", ")", ".", "any", "(", ")", ".", "any", "(", ")", ":", "validated_data", "=", "validated_data", ".", "dropna", "(", "axis", "=", "0", ",", "subset", "=", "config", ".", "NUMERICAL_NA_NOT_ALLOWED", ")", "# check for categorical variables with NA not seen during training", "if", "input_data", "[", "config", ".", "CATEGORICAL_NA_NOT_ALLOWED", "]", ".", "isnull", "(", ")", ".", "any", "(", ")", ".", "any", "(", ")", ":", "validated_data", "=", "validated_data", ".", "dropna", "(", "axis", "=", "0", ",", "subset", "=", "config", ".", "CATEGORICAL_NA_NOT_ALLOWED", ")", "# check for values <= 0 for the log transformed variables", "if", "(", "input_data", "[", "config", ".", "NUMERICALS_LOG_VARS", "]", "<=", "0", ")", ".", "any", "(", ")", ".", "any", "(", ")", ":", "vars_with_neg_values", "=", "config", ".", "NUMERICALS_LOG_VARS", "[", "(", "input_data", "[", "config", ".", "NUMERICALS_LOG_VARS", "]", "<=", "0", ")", ".", "any", "(", ")", "]", "validated_data", "=", "validated_data", "[", "validated_data", "[", "vars_with_neg_values", "]", ">", "0", "]", "return", "validated_data" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/validation.py#L6-L30
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/data_management.py
python
save_pipeline
(*, pipeline_to_persist)
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
[ "Persist", "the", "pipeline", ".", "Saves", "the", "versioned", "model", "and", "overwrites", "any", "previous", "saved", "models", ".", "This", "ensures", "that", "when", "the", "package", "is", "published", "there", "is", "only", "one", "trained", "model", "that", "can", "be", "called", "and", "we", "know", "exactly", "how", "it", "was", "built", "." ]
def save_pipeline(*, pipeline_to_persist) -> None: """Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built. """ # Prepare versioned save file name save_file_name = f"{config.PIPELINE_SAVE_FILE}{_version}.pkl" save_path = config.TRAINED_MODEL_DIR / save_file_name remove_old_pipelines(files_to_keep=[save_file_name]) joblib.dump(pipeline_to_persist, save_path) _logger.info(f"saved pipeline: {save_file_name}")
[ "def", "save_pipeline", "(", "*", ",", "pipeline_to_persist", ")", "->", "None", ":", "# Prepare versioned save file name", "save_file_name", "=", "f\"{config.PIPELINE_SAVE_FILE}{_version}.pkl\"", "save_path", "=", "config", ".", "TRAINED_MODEL_DIR", "/", "save_file_name", "remove_old_pipelines", "(", "files_to_keep", "=", "[", "save_file_name", "]", ")", "joblib", ".", "dump", "(", "pipeline_to_persist", ",", "save_path", ")", "_logger", ".", "info", "(", "f\"saved pipeline: {save_file_name}\"", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/data_management.py#L20-L34
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/data_management.py
python
load_pipeline
(*, file_name: str)
return trained_model
Load a persisted pipeline.
Load a persisted pipeline.
[ "Load", "a", "persisted", "pipeline", "." ]
def load_pipeline(*, file_name: str) -> Pipeline: """Load a persisted pipeline.""" file_path = config.TRAINED_MODEL_DIR / file_name trained_model = joblib.load(filename=file_path) return trained_model
[ "def", "load_pipeline", "(", "*", ",", "file_name", ":", "str", ")", "->", "Pipeline", ":", "file_path", "=", "config", ".", "TRAINED_MODEL_DIR", "/", "file_name", "trained_model", "=", "joblib", ".", "load", "(", "filename", "=", "file_path", ")", "return", "trained_model" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/data_management.py#L37-L42
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/data_management.py
python
remove_old_pipelines
(*, files_to_keep: t.List[str])
Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications. However, we do also include the immediate previous pipeline version for differential testing purposes.
Remove old model pipelines.
[ "Remove", "old", "model", "pipelines", "." ]
def remove_old_pipelines(*, files_to_keep: t.List[str]) -> None: """ Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications. However, we do also include the immediate previous pipeline version for differential testing purposes. """ do_not_delete = files_to_keep + ['__init__.py'] for model_file in config.TRAINED_MODEL_DIR.iterdir(): if model_file.name not in do_not_delete: model_file.unlink()
[ "def", "remove_old_pipelines", "(", "*", ",", "files_to_keep", ":", "t", ".", "List", "[", "str", "]", ")", "->", "None", ":", "do_not_delete", "=", "files_to_keep", "+", "[", "'__init__.py'", "]", "for", "model_file", "in", "config", ".", "TRAINED_MODEL_DIR", ".", "iterdir", "(", ")", ":", "if", "model_file", ".", "name", "not", "in", "do_not_delete", ":", "model_file", ".", "unlink", "(", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/data_management.py#L45-L58
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/preprocessors.py
python
CategoricalImputer.fit
(self, X: pd.DataFrame, y: pd.Series = None)
return self
Fit statement to accomodate the sklearn pipeline.
Fit statement to accomodate the sklearn pipeline.
[ "Fit", "statement", "to", "accomodate", "the", "sklearn", "pipeline", "." ]
def fit(self, X: pd.DataFrame, y: pd.Series = None) -> "CategoricalImputer": """Fit statement to accomodate the sklearn pipeline.""" return self
[ "def", "fit", "(", "self", ",", "X", ":", "pd", ".", "DataFrame", ",", "y", ":", "pd", ".", "Series", "=", "None", ")", "->", "\"CategoricalImputer\"", ":", "return", "self" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/preprocessors.py#L17-L20
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
packages/regression_model/regression_model/processing/preprocessors.py
python
CategoricalImputer.transform
(self, X: pd.DataFrame)
return X
Apply the transforms to the dataframe.
Apply the transforms to the dataframe.
[ "Apply", "the", "transforms", "to", "the", "dataframe", "." ]
def transform(self, X: pd.DataFrame) -> pd.DataFrame: """Apply the transforms to the dataframe.""" X = X.copy() for feature in self.variables: X[feature] = X[feature].fillna("Missing") return X
[ "def", "transform", "(", "self", ",", "X", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "X", "=", "X", ".", "copy", "(", ")", "for", "feature", "in", "self", ".", "variables", ":", "X", "[", "feature", "]", "=", "X", "[", "feature", "]", ".", "fillna", "(", "\"Missing\"", ")", "return", "X" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/packages/regression_model/regression_model/processing/preprocessors.py#L22-L29
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/train_pipeline.py
python
run_training
()
Train the model.
Train the model.
[ "Train", "the", "model", "." ]
def run_training() -> None: """Train the model.""" # read training data data = load_dataset(file_name=config.app_config.training_data_file) # divide train and test X_train, X_test, y_train, y_test = train_test_split( data[config.model_config.features], # predictors data[config.model_config.target], test_size=config.model_config.test_size, # we are setting the random seed here # for reproducibility random_state=config.model_config.random_state, ) y_train = np.log(y_train) # fit model price_pipe.fit(X_train, y_train) # persist trained model save_pipeline(pipeline_to_persist=price_pipe)
[ "def", "run_training", "(", ")", "->", "None", ":", "# read training data", "data", "=", "load_dataset", "(", "file_name", "=", "config", ".", "app_config", ".", "training_data_file", ")", "# divide train and test", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "data", "[", "config", ".", "model_config", ".", "features", "]", ",", "# predictors", "data", "[", "config", ".", "model_config", ".", "target", "]", ",", "test_size", "=", "config", ".", "model_config", ".", "test_size", ",", "# we are setting the random seed here", "# for reproducibility", "random_state", "=", "config", ".", "model_config", ".", "random_state", ",", ")", "y_train", "=", "np", ".", "log", "(", "y_train", ")", "# fit model", "price_pipe", ".", "fit", "(", "X_train", ",", "y_train", ")", "# persist trained model", "save_pipeline", "(", "pipeline_to_persist", "=", "price_pipe", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/train_pipeline.py#L8-L29
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/predict.py
python
make_prediction
( *, input_data: t.Union[pd.DataFrame, dict], )
return results
Make a prediction using a saved model pipeline.
Make a prediction using a saved model pipeline.
[ "Make", "a", "prediction", "using", "a", "saved", "model", "pipeline", "." ]
def make_prediction( *, input_data: t.Union[pd.DataFrame, dict], ) -> dict: """Make a prediction using a saved model pipeline.""" data = pd.DataFrame(input_data) validated_data, errors = validate_inputs(input_data=data) results = {"predictions": None, "version": _version, "errors": errors} if not errors: predictions = _price_pipe.predict( X=validated_data[config.model_config.features] ) results = { "predictions": [np.exp(pred) for pred in predictions], # type: ignore "version": _version, "errors": errors, } return results
[ "def", "make_prediction", "(", "*", ",", "input_data", ":", "t", ".", "Union", "[", "pd", ".", "DataFrame", ",", "dict", "]", ",", ")", "->", "dict", ":", "data", "=", "pd", ".", "DataFrame", "(", "input_data", ")", "validated_data", ",", "errors", "=", "validate_inputs", "(", "input_data", "=", "data", ")", "results", "=", "{", "\"predictions\"", ":", "None", ",", "\"version\"", ":", "_version", ",", "\"errors\"", ":", "errors", "}", "if", "not", "errors", ":", "predictions", "=", "_price_pipe", ".", "predict", "(", "X", "=", "validated_data", "[", "config", ".", "model_config", ".", "features", "]", ")", "results", "=", "{", "\"predictions\"", ":", "[", "np", ".", "exp", "(", "pred", ")", "for", "pred", "in", "predictions", "]", ",", "# type: ignore", "\"version\"", ":", "_version", ",", "\"errors\"", ":", "errors", ",", "}", "return", "results" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/predict.py#L15-L35
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/processing/validation.py
python
drop_na_inputs
(*, input_data: pd.DataFrame)
return validated_data
Check model inputs for na values and filter.
Check model inputs for na values and filter.
[ "Check", "model", "inputs", "for", "na", "values", "and", "filter", "." ]
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame: """Check model inputs for na values and filter.""" validated_data = input_data.copy() new_vars_with_na = [ var for var in config.model_config.features if var not in config.model_config.categorical_vars_with_na_frequent + config.model_config.categorical_vars_with_na_missing + config.model_config.numerical_vars_with_na and validated_data[var].isnull().sum() > 0 ] validated_data.dropna(subset=new_vars_with_na, inplace=True) return validated_data
[ "def", "drop_na_inputs", "(", "*", ",", "input_data", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "validated_data", "=", "input_data", ".", "copy", "(", ")", "new_vars_with_na", "=", "[", "var", "for", "var", "in", "config", ".", "model_config", ".", "features", "if", "var", "not", "in", "config", ".", "model_config", ".", "categorical_vars_with_na_frequent", "+", "config", ".", "model_config", ".", "categorical_vars_with_na_missing", "+", "config", ".", "model_config", ".", "numerical_vars_with_na", "and", "validated_data", "[", "var", "]", ".", "isnull", "(", ")", ".", "sum", "(", ")", ">", "0", "]", "validated_data", ".", "dropna", "(", "subset", "=", "new_vars_with_na", ",", "inplace", "=", "True", ")", "return", "validated_data" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/processing/validation.py#L10-L24
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/processing/validation.py
python
validate_inputs
(*, input_data: pd.DataFrame)
return validated_data, errors
Check model inputs for unprocessable values.
Check model inputs for unprocessable values.
[ "Check", "model", "inputs", "for", "unprocessable", "values", "." ]
def validate_inputs(*, input_data: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[dict]]: """Check model inputs for unprocessable values.""" # convert syntax error field names (beginning with numbers) input_data.rename(columns=config.model_config.variables_to_rename, inplace=True) input_data["MSSubClass"] = input_data["MSSubClass"].astype("O") relevant_data = input_data[config.model_config.features].copy() validated_data = drop_na_inputs(input_data=relevant_data) errors = None try: # replace numpy nans so that pydantic can validate MultipleHouseDataInputs( inputs=validated_data.replace({np.nan: None}).to_dict(orient="records") ) except ValidationError as error: errors = error.json() return validated_data, errors
[ "def", "validate_inputs", "(", "*", ",", "input_data", ":", "pd", ".", "DataFrame", ")", "->", "Tuple", "[", "pd", ".", "DataFrame", ",", "Optional", "[", "dict", "]", "]", ":", "# convert syntax error field names (beginning with numbers)", "input_data", ".", "rename", "(", "columns", "=", "config", ".", "model_config", ".", "variables_to_rename", ",", "inplace", "=", "True", ")", "input_data", "[", "\"MSSubClass\"", "]", "=", "input_data", "[", "\"MSSubClass\"", "]", ".", "astype", "(", "\"O\"", ")", "relevant_data", "=", "input_data", "[", "config", ".", "model_config", ".", "features", "]", ".", "copy", "(", ")", "validated_data", "=", "drop_na_inputs", "(", "input_data", "=", "relevant_data", ")", "errors", "=", "None", "try", ":", "# replace numpy nans so that pydantic can validate", "MultipleHouseDataInputs", "(", "inputs", "=", "validated_data", ".", "replace", "(", "{", "np", ".", "nan", ":", "None", "}", ")", ".", "to_dict", "(", "orient", "=", "\"records\"", ")", ")", "except", "ValidationError", "as", "error", ":", "errors", "=", "error", ".", "json", "(", ")", "return", "validated_data", ",", "errors" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/processing/validation.py#L27-L45
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/processing/data_manager.py
python
save_pipeline
(*, pipeline_to_persist: Pipeline)
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
[ "Persist", "the", "pipeline", ".", "Saves", "the", "versioned", "model", "and", "overwrites", "any", "previous", "saved", "models", ".", "This", "ensures", "that", "when", "the", "package", "is", "published", "there", "is", "only", "one", "trained", "model", "that", "can", "be", "called", "and", "we", "know", "exactly", "how", "it", "was", "built", "." ]
def save_pipeline(*, pipeline_to_persist: Pipeline) -> None: """Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built. """ # Prepare versioned save file name save_file_name = f"{config.app_config.pipeline_save_file}{_version}.pkl" save_path = TRAINED_MODEL_DIR / save_file_name remove_old_pipelines(files_to_keep=[save_file_name]) joblib.dump(pipeline_to_persist, save_path)
[ "def", "save_pipeline", "(", "*", ",", "pipeline_to_persist", ":", "Pipeline", ")", "->", "None", ":", "# Prepare versioned save file name", "save_file_name", "=", "f\"{config.app_config.pipeline_save_file}{_version}.pkl\"", "save_path", "=", "TRAINED_MODEL_DIR", "/", "save_file_name", "remove_old_pipelines", "(", "files_to_keep", "=", "[", "save_file_name", "]", ")", "joblib", ".", "dump", "(", "pipeline_to_persist", ",", "save_path", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/processing/data_manager.py#L21-L34
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/processing/data_manager.py
python
load_pipeline
(*, file_name: str)
return trained_model
Load a persisted pipeline.
Load a persisted pipeline.
[ "Load", "a", "persisted", "pipeline", "." ]
def load_pipeline(*, file_name: str) -> Pipeline: """Load a persisted pipeline.""" file_path = TRAINED_MODEL_DIR / file_name trained_model = joblib.load(filename=file_path) return trained_model
[ "def", "load_pipeline", "(", "*", ",", "file_name", ":", "str", ")", "->", "Pipeline", ":", "file_path", "=", "TRAINED_MODEL_DIR", "/", "file_name", "trained_model", "=", "joblib", ".", "load", "(", "filename", "=", "file_path", ")", "return", "trained_model" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/processing/data_manager.py#L37-L42
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/processing/data_manager.py
python
remove_old_pipelines
(*, files_to_keep: t.List[str])
Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications.
Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications.
[ "Remove", "old", "model", "pipelines", ".", "This", "is", "to", "ensure", "there", "is", "a", "simple", "one", "-", "to", "-", "one", "mapping", "between", "the", "package", "version", "and", "the", "model", "version", "to", "be", "imported", "and", "used", "by", "other", "applications", "." ]
def remove_old_pipelines(*, files_to_keep: t.List[str]) -> None: """ Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications. """ do_not_delete = files_to_keep + ["__init__.py"] for model_file in TRAINED_MODEL_DIR.iterdir(): if model_file.name not in do_not_delete: model_file.unlink()
[ "def", "remove_old_pipelines", "(", "*", ",", "files_to_keep", ":", "t", ".", "List", "[", "str", "]", ")", "->", "None", ":", "do_not_delete", "=", "files_to_keep", "+", "[", "\"__init__.py\"", "]", "for", "model_file", "in", "TRAINED_MODEL_DIR", ".", "iterdir", "(", ")", ":", "if", "model_file", ".", "name", "not", "in", "do_not_delete", ":", "model_file", ".", "unlink", "(", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/processing/data_manager.py#L45-L55
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/config/core.py
python
find_config_file
()
Locate the configuration file.
Locate the configuration file.
[ "Locate", "the", "configuration", "file", "." ]
def find_config_file() -> Path: """Locate the configuration file.""" if CONFIG_FILE_PATH.is_file(): return CONFIG_FILE_PATH raise Exception(f"Config not found at {CONFIG_FILE_PATH!r}")
[ "def", "find_config_file", "(", ")", "->", "Path", ":", "if", "CONFIG_FILE_PATH", ".", "is_file", "(", ")", ":", "return", "CONFIG_FILE_PATH", "raise", "Exception", "(", "f\"Config not found at {CONFIG_FILE_PATH!r}\"", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/config/core.py#L65-L69
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/config/core.py
python
fetch_config_from_yaml
(cfg_path: Path = None)
Parse YAML containing the package configuration.
Parse YAML containing the package configuration.
[ "Parse", "YAML", "containing", "the", "package", "configuration", "." ]
def fetch_config_from_yaml(cfg_path: Path = None) -> YAML: """Parse YAML containing the package configuration.""" if not cfg_path: cfg_path = find_config_file() if cfg_path: with open(cfg_path, "r") as conf_file: parsed_config = load(conf_file.read()) return parsed_config raise OSError(f"Did not find config file at path: {cfg_path}")
[ "def", "fetch_config_from_yaml", "(", "cfg_path", ":", "Path", "=", "None", ")", "->", "YAML", ":", "if", "not", "cfg_path", ":", "cfg_path", "=", "find_config_file", "(", ")", "if", "cfg_path", ":", "with", "open", "(", "cfg_path", ",", "\"r\"", ")", "as", "conf_file", ":", "parsed_config", "=", "load", "(", "conf_file", ".", "read", "(", ")", ")", "return", "parsed_config", "raise", "OSError", "(", "f\"Did not find config file at path: {cfg_path}\"", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/config/core.py#L72-L82
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-05-production-model-package/regression_model/config/core.py
python
create_and_validate_config
(parsed_config: YAML = None)
return _config
Run validation on config values.
Run validation on config values.
[ "Run", "validation", "on", "config", "values", "." ]
def create_and_validate_config(parsed_config: YAML = None) -> Config: """Run validation on config values.""" if parsed_config is None: parsed_config = fetch_config_from_yaml() # specify the data attribute from the strictyaml YAML type. _config = Config( app_config=AppConfig(**parsed_config.data), model_config=ModelConfig(**parsed_config.data), ) return _config
[ "def", "create_and_validate_config", "(", "parsed_config", ":", "YAML", "=", "None", ")", "->", "Config", ":", "if", "parsed_config", "is", "None", ":", "parsed_config", "=", "fetch_config_from_yaml", "(", ")", "# specify the data attribute from the strictyaml YAML type.", "_config", "=", "Config", "(", "app_config", "=", "AppConfig", "(", "*", "*", "parsed_config", ".", "data", ")", ",", "model_config", "=", "ModelConfig", "(", "*", "*", "parsed_config", ".", "data", ")", ",", ")", "return", "_config" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-05-production-model-package/regression_model/config/core.py#L85-L96
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/train_pipeline.py
python
run_training
()
Train the model.
Train the model.
[ "Train", "the", "model", "." ]
def run_training() -> None: """Train the model.""" # read training data data = load_dataset(file_name=config.app_config.training_data_file) # divide train and test X_train, X_test, y_train, y_test = train_test_split( data[config.model_config.features], # predictors data[config.model_config.target], test_size=config.model_config.test_size, # we are setting the random seed here # for reproducibility random_state=config.model_config.random_state, ) y_train = np.log(y_train) # fit model price_pipe.fit(X_train, y_train) # persist trained model save_pipeline(pipeline_to_persist=price_pipe)
[ "def", "run_training", "(", ")", "->", "None", ":", "# read training data", "data", "=", "load_dataset", "(", "file_name", "=", "config", ".", "app_config", ".", "training_data_file", ")", "# divide train and test", "X_train", ",", "X_test", ",", "y_train", ",", "y_test", "=", "train_test_split", "(", "data", "[", "config", ".", "model_config", ".", "features", "]", ",", "# predictors", "data", "[", "config", ".", "model_config", ".", "target", "]", ",", "test_size", "=", "config", ".", "model_config", ".", "test_size", ",", "# we are setting the random seed here", "# for reproducibility", "random_state", "=", "config", ".", "model_config", ".", "random_state", ",", ")", "y_train", "=", "np", ".", "log", "(", "y_train", ")", "# fit model", "price_pipe", ".", "fit", "(", "X_train", ",", "y_train", ")", "# persist trained model", "save_pipeline", "(", "pipeline_to_persist", "=", "price_pipe", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/train_pipeline.py#L8-L29
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/predict.py
python
make_prediction
( *, input_data: t.Union[pd.DataFrame, dict], )
return results
Make a prediction using a saved model pipeline.
Make a prediction using a saved model pipeline.
[ "Make", "a", "prediction", "using", "a", "saved", "model", "pipeline", "." ]
def make_prediction( *, input_data: t.Union[pd.DataFrame, dict], ) -> dict: """Make a prediction using a saved model pipeline.""" data = pd.DataFrame(input_data) validated_data, errors = validate_inputs(input_data=data) results = {"predictions": None, "version": _version, "errors": errors} if not errors: predictions = _price_pipe.predict( X=validated_data[config.model_config.features] ) results = { "predictions": [np.exp(pred) for pred in predictions], # type: ignore "version": _version, "errors": errors, } return results
[ "def", "make_prediction", "(", "*", ",", "input_data", ":", "t", ".", "Union", "[", "pd", ".", "DataFrame", ",", "dict", "]", ",", ")", "->", "dict", ":", "data", "=", "pd", ".", "DataFrame", "(", "input_data", ")", "validated_data", ",", "errors", "=", "validate_inputs", "(", "input_data", "=", "data", ")", "results", "=", "{", "\"predictions\"", ":", "None", ",", "\"version\"", ":", "_version", ",", "\"errors\"", ":", "errors", "}", "if", "not", "errors", ":", "predictions", "=", "_price_pipe", ".", "predict", "(", "X", "=", "validated_data", "[", "config", ".", "model_config", ".", "features", "]", ")", "results", "=", "{", "\"predictions\"", ":", "[", "np", ".", "exp", "(", "pred", ")", "for", "pred", "in", "predictions", "]", ",", "# type: ignore", "\"version\"", ":", "_version", ",", "\"errors\"", ":", "errors", ",", "}", "return", "results" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/predict.py#L15-L35
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/processing/validation.py
python
drop_na_inputs
(*, input_data: pd.DataFrame)
return validated_data
Check model inputs for na values and filter.
Check model inputs for na values and filter.
[ "Check", "model", "inputs", "for", "na", "values", "and", "filter", "." ]
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame: """Check model inputs for na values and filter.""" validated_data = input_data.copy() new_vars_with_na = [ var for var in config.model_config.features if var not in config.model_config.categorical_vars_with_na_frequent + config.model_config.categorical_vars_with_na_missing + config.model_config.numerical_vars_with_na and validated_data[var].isnull().sum() > 0 ] validated_data.dropna(subset=new_vars_with_na, inplace=True) return validated_data
[ "def", "drop_na_inputs", "(", "*", ",", "input_data", ":", "pd", ".", "DataFrame", ")", "->", "pd", ".", "DataFrame", ":", "validated_data", "=", "input_data", ".", "copy", "(", ")", "new_vars_with_na", "=", "[", "var", "for", "var", "in", "config", ".", "model_config", ".", "features", "if", "var", "not", "in", "config", ".", "model_config", ".", "categorical_vars_with_na_frequent", "+", "config", ".", "model_config", ".", "categorical_vars_with_na_missing", "+", "config", ".", "model_config", ".", "numerical_vars_with_na", "and", "validated_data", "[", "var", "]", ".", "isnull", "(", ")", ".", "sum", "(", ")", ">", "0", "]", "validated_data", ".", "dropna", "(", "subset", "=", "new_vars_with_na", ",", "inplace", "=", "True", ")", "return", "validated_data" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/processing/validation.py#L10-L24
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/processing/validation.py
python
validate_inputs
(*, input_data: pd.DataFrame)
return validated_data, errors
Check model inputs for unprocessable values.
Check model inputs for unprocessable values.
[ "Check", "model", "inputs", "for", "unprocessable", "values", "." ]
def validate_inputs(*, input_data: pd.DataFrame) -> Tuple[pd.DataFrame, Optional[dict]]: """Check model inputs for unprocessable values.""" # convert syntax error field names (beginning with numbers) input_data.rename(columns=config.model_config.variables_to_rename, inplace=True) input_data["MSSubClass"] = input_data["MSSubClass"].astype("O") relevant_data = input_data[config.model_config.features].copy() validated_data = drop_na_inputs(input_data=relevant_data) errors = None try: # replace numpy nans so that pydantic can validate MultipleHouseDataInputs( inputs=validated_data.replace({np.nan: None}).to_dict(orient="records") ) except ValidationError as error: errors = error.json() return validated_data, errors
[ "def", "validate_inputs", "(", "*", ",", "input_data", ":", "pd", ".", "DataFrame", ")", "->", "Tuple", "[", "pd", ".", "DataFrame", ",", "Optional", "[", "dict", "]", "]", ":", "# convert syntax error field names (beginning with numbers)", "input_data", ".", "rename", "(", "columns", "=", "config", ".", "model_config", ".", "variables_to_rename", ",", "inplace", "=", "True", ")", "input_data", "[", "\"MSSubClass\"", "]", "=", "input_data", "[", "\"MSSubClass\"", "]", ".", "astype", "(", "\"O\"", ")", "relevant_data", "=", "input_data", "[", "config", ".", "model_config", ".", "features", "]", ".", "copy", "(", ")", "validated_data", "=", "drop_na_inputs", "(", "input_data", "=", "relevant_data", ")", "errors", "=", "None", "try", ":", "# replace numpy nans so that pydantic can validate", "MultipleHouseDataInputs", "(", "inputs", "=", "validated_data", ".", "replace", "(", "{", "np", ".", "nan", ":", "None", "}", ")", ".", "to_dict", "(", "orient", "=", "\"records\"", ")", ")", "except", "ValidationError", "as", "error", ":", "errors", "=", "error", ".", "json", "(", ")", "return", "validated_data", ",", "errors" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/processing/validation.py#L27-L45
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py
python
save_pipeline
(*, pipeline_to_persist: Pipeline)
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built.
[ "Persist", "the", "pipeline", ".", "Saves", "the", "versioned", "model", "and", "overwrites", "any", "previous", "saved", "models", ".", "This", "ensures", "that", "when", "the", "package", "is", "published", "there", "is", "only", "one", "trained", "model", "that", "can", "be", "called", "and", "we", "know", "exactly", "how", "it", "was", "built", "." ]
def save_pipeline(*, pipeline_to_persist: Pipeline) -> None: """Persist the pipeline. Saves the versioned model, and overwrites any previous saved models. This ensures that when the package is published, there is only one trained model that can be called, and we know exactly how it was built. """ # Prepare versioned save file name save_file_name = f"{config.app_config.pipeline_save_file}{_version}.pkl" save_path = TRAINED_MODEL_DIR / save_file_name remove_old_pipelines(files_to_keep=[save_file_name]) joblib.dump(pipeline_to_persist, save_path)
[ "def", "save_pipeline", "(", "*", ",", "pipeline_to_persist", ":", "Pipeline", ")", "->", "None", ":", "# Prepare versioned save file name", "save_file_name", "=", "f\"{config.app_config.pipeline_save_file}{_version}.pkl\"", "save_path", "=", "TRAINED_MODEL_DIR", "/", "save_file_name", "remove_old_pipelines", "(", "files_to_keep", "=", "[", "save_file_name", "]", ")", "joblib", ".", "dump", "(", "pipeline_to_persist", ",", "save_path", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py#L21-L34
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py
python
load_pipeline
(*, file_name: str)
return trained_model
Load a persisted pipeline.
Load a persisted pipeline.
[ "Load", "a", "persisted", "pipeline", "." ]
def load_pipeline(*, file_name: str) -> Pipeline: """Load a persisted pipeline.""" file_path = TRAINED_MODEL_DIR / file_name trained_model = joblib.load(filename=file_path) return trained_model
[ "def", "load_pipeline", "(", "*", ",", "file_name", ":", "str", ")", "->", "Pipeline", ":", "file_path", "=", "TRAINED_MODEL_DIR", "/", "file_name", "trained_model", "=", "joblib", ".", "load", "(", "filename", "=", "file_path", ")", "return", "trained_model" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py#L37-L42
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py
python
remove_old_pipelines
(*, files_to_keep: t.List[str])
Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications.
Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications.
[ "Remove", "old", "model", "pipelines", ".", "This", "is", "to", "ensure", "there", "is", "a", "simple", "one", "-", "to", "-", "one", "mapping", "between", "the", "package", "version", "and", "the", "model", "version", "to", "be", "imported", "and", "used", "by", "other", "applications", "." ]
def remove_old_pipelines(*, files_to_keep: t.List[str]) -> None: """ Remove old model pipelines. This is to ensure there is a simple one-to-one mapping between the package version and the model version to be imported and used by other applications. """ do_not_delete = files_to_keep + ["__init__.py"] for model_file in TRAINED_MODEL_DIR.iterdir(): if model_file.name not in do_not_delete: model_file.unlink()
[ "def", "remove_old_pipelines", "(", "*", ",", "files_to_keep", ":", "t", ".", "List", "[", "str", "]", ")", "->", "None", ":", "do_not_delete", "=", "files_to_keep", "+", "[", "\"__init__.py\"", "]", "for", "model_file", "in", "TRAINED_MODEL_DIR", ".", "iterdir", "(", ")", ":", "if", "model_file", ".", "name", "not", "in", "do_not_delete", ":", "model_file", ".", "unlink", "(", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/processing/data_manager.py#L45-L55
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/config/core.py
python
find_config_file
()
Locate the configuration file.
Locate the configuration file.
[ "Locate", "the", "configuration", "file", "." ]
def find_config_file() -> Path: """Locate the configuration file.""" if CONFIG_FILE_PATH.is_file(): return CONFIG_FILE_PATH raise Exception(f"Config not found at {CONFIG_FILE_PATH!r}")
[ "def", "find_config_file", "(", ")", "->", "Path", ":", "if", "CONFIG_FILE_PATH", ".", "is_file", "(", ")", ":", "return", "CONFIG_FILE_PATH", "raise", "Exception", "(", "f\"Config not found at {CONFIG_FILE_PATH!r}\"", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/config/core.py#L65-L69
trainindata/deploying-machine-learning-models
aaeb3e65d0a58ad583289aaa39b089f11d06a4eb
section-07-ci-and-publishing/model-package/regression_model/config/core.py
python
fetch_config_from_yaml
(cfg_path: Path = None)
Parse YAML containing the package configuration.
Parse YAML containing the package configuration.
[ "Parse", "YAML", "containing", "the", "package", "configuration", "." ]
def fetch_config_from_yaml(cfg_path: Path = None) -> YAML: """Parse YAML containing the package configuration.""" if not cfg_path: cfg_path = find_config_file() if cfg_path: with open(cfg_path, "r") as conf_file: parsed_config = load(conf_file.read()) return parsed_config raise OSError(f"Did not find config file at path: {cfg_path}")
[ "def", "fetch_config_from_yaml", "(", "cfg_path", ":", "Path", "=", "None", ")", "->", "YAML", ":", "if", "not", "cfg_path", ":", "cfg_path", "=", "find_config_file", "(", ")", "if", "cfg_path", ":", "with", "open", "(", "cfg_path", ",", "\"r\"", ")", "as", "conf_file", ":", "parsed_config", "=", "load", "(", "conf_file", ".", "read", "(", ")", ")", "return", "parsed_config", "raise", "OSError", "(", "f\"Did not find config file at path: {cfg_path}\"", ")" ]
https://github.com/trainindata/deploying-machine-learning-models/blob/aaeb3e65d0a58ad583289aaa39b089f11d06a4eb/section-07-ci-and-publishing/model-package/regression_model/config/core.py#L72-L82
End of preview (truncated to 100 rows)

No dataset card yet

New: Create and edit this dataset card directly on the website!

Contribute a Dataset Card
Add dataset card