Python torchvision.models.squeezenet1_1() Examples

The following are 19 code examples of torchvision.models.squeezenet1_1(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module torchvision.models , or try the search function .
Example #1
Source File: extractor.py    From DeepSpectrum with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, images, model_key, layer, batch_size=256):
        super().__init__(images, batch_size)
        self.models = {
            "alexnet": models.alexnet,
            "squeezenet": models.squeezenet1_1,
            "googlenet": models.googlenet
        }
        self.preprocessors = {
            "alexnet": self.__preprocess_alexnet,
            "squeezenet": self.__preprocess_squeezenet,
            "googlenet": self.__preprocess_googlenet
        }
        self.batch_size = batch_size
        self.layer = layer
        self.model_key = model_key

        self.model, self.feature_layer, self.output_size = self.__build_model(
            layer) 
Example #2
Source File: test_attack_Gaussian_blur.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def test_untargeted_squeezenet1_1(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.squeezenet1_1(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
Example #3
Source File: test_attack_AdditiveGaussianNoiseAttack.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def test_untargeted_squeezenet1_1(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.squeezenet1_1(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
Example #4
Source File: test_attack_AdditiveUniformNoiseAttack.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def test_untargeted_squeezenet1_1(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.squeezenet1_1(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
Example #5
Source File: test_attack_BlendedUniformNoiseAttack.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def test_untargeted_squeezenet1_1(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.squeezenet1_1(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
Example #6
Source File: test_attack_MotionBlurAttack.py    From perceptron-benchmark with Apache License 2.0 6 votes vote down vote up
def test_untargeted_squeezenet1_1(image, label=None):
    import torch
    import torchvision.models as models
    from perceptron.models.classification import PyTorchModel
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    model_pyt = models.squeezenet1_1(pretrained=True).eval()
    if torch.cuda.is_available():
        model_pyt = model_pyt.cuda()
    model = PyTorchModel(
        model_pyt, bounds=(0, 1), num_classes=1000, preprocessing=(mean, std))
    print(np.argmax(model.predictions(image)))
    attack = Attack(model, criterion=Misclassification())
    adversarial_obj = attack(image, label, unpack=False, epsilons=10000)
    distance = adversarial_obj.distance
    adversarial = adversarial_obj.image
    return distance, adversarial 
Example #7
Source File: torchvision_models.py    From pretrained-models.pytorch with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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

###############################################################
# VGGs 
Example #8
Source File: squezenet_qc.py    From AD-DL with MIT License 5 votes vote down vote up
def squeezenet_qc(pretrained=False, **kwargs):
    """Constructs a SqueezeNet 1.1 model

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = SqueezeNetQC(version=1.1, **kwargs)
    if pretrained:
        # load basic Resnet model
        model_ft = models.squeezenet1_1(pretrained=True)
        model.load_from_std(model_ft)
    return model 
Example #9
Source File: pretrained_networks.py    From SMIT with MIT License 5 votes vote down vote up
def __init__(self, requires_grad=False, pretrained=True):
        super(squeezenet, self).__init__()
        pretrained_features = models.squeezenet1_1(
            pretrained=pretrained).features
        self.slice1 = torch.nn.Sequential()
        self.slice2 = torch.nn.Sequential()
        self.slice3 = torch.nn.Sequential()
        self.slice4 = torch.nn.Sequential()
        self.slice5 = torch.nn.Sequential()
        self.slice6 = torch.nn.Sequential()
        self.slice7 = torch.nn.Sequential()
        self.N_slices = 7
        for x in range(2):
            self.slice1.add_module(str(x), pretrained_features[x])
        for x in range(2, 5):
            self.slice2.add_module(str(x), pretrained_features[x])
        for x in range(5, 8):
            self.slice3.add_module(str(x), pretrained_features[x])
        for x in range(8, 10):
            self.slice4.add_module(str(x), pretrained_features[x])
        for x in range(10, 11):
            self.slice5.add_module(str(x), pretrained_features[x])
        for x in range(11, 12):
            self.slice6.add_module(str(x), pretrained_features[x])
        for x in range(12, 13):
            self.slice7.add_module(str(x), pretrained_features[x])
        if not requires_grad:
            for param in self.parameters():
                param.requires_grad = False 
Example #10
Source File: pretrained_networks.py    From TecoGAN with Apache License 2.0 5 votes vote down vote up
def __init__(self, requires_grad=False, pretrained=True):
        super(squeezenet, self).__init__()
        pretrained_features = models.squeezenet1_1(pretrained=pretrained).features
        self.slice1 = torch.nn.Sequential()
        self.slice2 = torch.nn.Sequential()
        self.slice3 = torch.nn.Sequential()
        self.slice4 = torch.nn.Sequential()
        self.slice5 = torch.nn.Sequential()
        self.slice6 = torch.nn.Sequential()
        self.slice7 = torch.nn.Sequential()
        self.N_slices = 7
        for x in range(2):
            self.slice1.add_module(str(x), pretrained_features[x])
        for x in range(2,5):
            self.slice2.add_module(str(x), pretrained_features[x])
        for x in range(5, 8):
            self.slice3.add_module(str(x), pretrained_features[x])
        for x in range(8, 10):
            self.slice4.add_module(str(x), pretrained_features[x])
        for x in range(10, 11):
            self.slice5.add_module(str(x), pretrained_features[x])
        for x in range(11, 12):
            self.slice6.add_module(str(x), pretrained_features[x])
        for x in range(12, 13):
            self.slice7.add_module(str(x), pretrained_features[x])
        if not requires_grad:
            for param in self.parameters():
                param.requires_grad = False 
Example #11
Source File: pretrained_networks.py    From PerceptualSimilarity with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, requires_grad=False, pretrained=True):
        super(squeezenet, self).__init__()
        pretrained_features = tv.squeezenet1_1(pretrained=pretrained).features
        self.slice1 = torch.nn.Sequential()
        self.slice2 = torch.nn.Sequential()
        self.slice3 = torch.nn.Sequential()
        self.slice4 = torch.nn.Sequential()
        self.slice5 = torch.nn.Sequential()
        self.slice6 = torch.nn.Sequential()
        self.slice7 = torch.nn.Sequential()
        self.N_slices = 7
        for x in range(2):
            self.slice1.add_module(str(x), pretrained_features[x])
        for x in range(2,5):
            self.slice2.add_module(str(x), pretrained_features[x])
        for x in range(5, 8):
            self.slice3.add_module(str(x), pretrained_features[x])
        for x in range(8, 10):
            self.slice4.add_module(str(x), pretrained_features[x])
        for x in range(10, 11):
            self.slice5.add_module(str(x), pretrained_features[x])
        for x in range(11, 12):
            self.slice6.add_module(str(x), pretrained_features[x])
        for x in range(12, 13):
            self.slice7.add_module(str(x), pretrained_features[x])
        if not requires_grad:
            for param in self.parameters():
                param.requires_grad = False 
Example #12
Source File: models.py    From adversarial-object-removal with MIT License 5 votes vote down vote up
def __init__(self, requires_grad=False, pretrained=True):
        super(squeezenet, self).__init__()
        pretrained_features = models.squeezenet1_1(pretrained=pretrained).features
        self.slice1 = torch.nn.Sequential()
        self.slice2 = torch.nn.Sequential()
        self.slice3 = torch.nn.Sequential()
        self.slice4 = torch.nn.Sequential()
        self.slice5 = torch.nn.Sequential()
        self.slice6 = torch.nn.Sequential()
        self.slice7 = torch.nn.Sequential()
        self.N_slices = 7
        for x in range(2):
            self.slice1.add_module(str(x), pretrained_features[x])
        for x in range(2,5):
            self.slice2.add_module(str(x), pretrained_features[x])
        for x in range(5, 8):
            self.slice3.add_module(str(x), pretrained_features[x])
        for x in range(8, 10):
            self.slice4.add_module(str(x), pretrained_features[x])
        for x in range(10, 11):
            self.slice5.add_module(str(x), pretrained_features[x])
        for x in range(11, 12):
            self.slice6.add_module(str(x), pretrained_features[x])
        for x in range(12, 13):
            self.slice7.add_module(str(x), pretrained_features[x])


        if not requires_grad:
            for param in self.parameters():
                param.requires_grad = False 
Example #13
Source File: sqeezenet.py    From MOTDT with MIT License 5 votes vote down vote up
def __init__(self, pretrained=True):

        super(FeatExtractorSqueezeNetx16, self).__init__()
        print("loading layers from squeezenet1_1...")
        sq = models.squeezenet1_1(pretrained=pretrained)

        self.conv1 = nn.Sequential(
            sq.features[0],
            sq.features[1],
        )
        self.conv2 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
            sq.features[3],
            sq.features[4],
        )
        self.conv3 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
            sq.features[6],
            sq.features[7],
        )
        self.conv4 = nn.Sequential(
            nn.MaxPool2d(kernel_size=3, stride=2, padding=1),
            sq.features[9],
            sq.features[10],
            sq.features[11],
            sq.features[12],
        )

        self.conv1[0].padding = (1, 1) 
Example #14
Source File: torchvision_models.py    From pretorched-x with MIT License 5 votes vote down vote up
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

###############################################################
# VGGs 
Example #15
Source File: pspnet.py    From pytorch-hair-segmentation with MIT License 5 votes vote down vote up
def __init__(self):
        super(SqueezeNetExtractor, self).__init__()
        model = squeezenet1_1(pretrained=True)
        features = model.features
        self.feature1 = features[:2]
        self.feature2 = features[2:5]
        self.feature3 = features[5:8]
        self.feature4 = features[8:] 
Example #16
Source File: tools.py    From perceptron-benchmark with Apache License 2.0 5 votes vote down vote up
def load_pytorch_model(model_name):
    import torchvision.models as models
    switcher = {
        'alexnet': lambda: models.alexnet(pretrained=True).eval(),
        "vgg11": lambda: models.vgg11(pretrained=True).eval(),
        "vgg11_bn": lambda: models.vgg11_bn(pretrained=True).eval(),
        "vgg13": lambda: models.vgg13(pretrained=True).eval(),
        "vgg13_bn": lambda: models.vgg13_bn(pretrained=True).eval(),
        "vgg16": lambda: models.vgg16(pretrained=True).eval(),
        "vgg16_bn": lambda: models.vgg16_bn(pretrained=True).eval(),
        "vgg19": lambda: models.vgg19(pretrained=True).eval(),
        "vgg19_bn": lambda: models.vgg19_bn(pretrained=True).eval(),
        "resnet18": lambda: models.resnet18(pretrained=True).eval(),
        "resnet34": lambda: models.resnet34(pretrained=True).eval(),
        "resnet50": lambda: models.resnet50(pretrained=True).eval(),
        "resnet101": lambda: models.resnet101(pretrained=True).eval(),
        "resnet152": lambda: models.resnet152(pretrained=True).eval(),
        "squeezenet1_0": lambda: models.squeezenet1_0(pretrained=True).eval(),
        "squeezenet1_1": lambda: models.squeezenet1_1(pretrained=True).eval(),
        "densenet121": lambda: models.densenet121(pretrained=True).eval(),
        "densenet161": lambda: models.densenet161(pretrained=True).eval(),
        "densenet201": lambda: models.densenet201(pretrained=True).eval(),
        "inception_v3": lambda: models.inception_v3(pretrained=True).eval(),
    }

    _load_model = switcher.get(model_name, None)
    _model = _load_model()
    return _model 
Example #17
Source File: tools.py    From perceptron-benchmark with Apache License 2.0 5 votes vote down vote up
def _load_pytorch_model(model_name, summary):
    import torchvision.models as models
    switcher = {
        'alexnet': lambda: models.alexnet(pretrained=True).eval(),
        "vgg11": lambda: models.vgg11(pretrained=True).eval(),
        "vgg11_bn": lambda: models.vgg11_bn(pretrained=True).eval(),
        "vgg13": lambda: models.vgg13(pretrained=True).eval(),
        "vgg13_bn": lambda: models.vgg13_bn(pretrained=True).eval(),
        "vgg16": lambda: models.vgg16(pretrained=True).eval(),
        "vgg16_bn": lambda: models.vgg16_bn(pretrained=True).eval(),
        "vgg19": lambda: models.vgg19(pretrained=True).eval(),
        "vgg19_bn": lambda: models.vgg19_bn(pretrained=True).eval(),
        "resnet18": lambda: models.resnet18(pretrained=True).eval(),
        "resnet34": lambda: models.resnet34(pretrained=True).eval(),
        "resnet50": lambda: models.resnet50(pretrained=True).eval(),
        "resnet101": lambda: models.resnet101(pretrained=True).eval(),
        "resnet152": lambda: models.resnet152(pretrained=True).eval(),
        "squeezenet1_0": lambda: models.squeezenet1_0(pretrained=True).eval(),
        "squeezenet1_1": lambda: models.squeezenet1_1(pretrained=True).eval(),
        "densenet121": lambda: models.densenet121(pretrained=True).eval(),
        "densenet161": lambda: models.densenet161(pretrained=True).eval(),
        "densenet201": lambda: models.densenet201(pretrained=True).eval(),
        "inception_v3": lambda: models.inception_v3(pretrained=True).eval(),
    }

    _load_model = switcher.get(model_name, None)
    _model = _load_model()
    import torch
    if torch.cuda.is_available():
        _model = _model.cuda()
    from perceptron.models.classification.pytorch import PyTorchModel as ClsPyTorchModel
    import numpy as np
    mean = np.array([0.485, 0.456, 0.406]).reshape((3, 1, 1))
    std = np.array([0.229, 0.224, 0.225]).reshape((3, 1, 1))
    pmodel = ClsPyTorchModel(
        _model, bounds=(
            0, 1), num_classes=1000, preprocessing=(
            mean, std))
    return pmodel 
Example #18
Source File: squeezenet.py    From pytorch-lighthead with MIT License 4 votes vote down vote up
def _init_modules(self):
    if self.version == '1_0':
        squeezenet = models.squeezenet1_0()
        self.clip = -2
    elif self.version == '1_1':
        squeezenet = models.squeezenet1_1()
        self.clip = -5
    if self.pretrained:
        print("Loading pretrained weights from %s" %(self.model_path))
        if torch.cuda.is_available():
          state_dict = torch.load(self.model_path)
        else:
          state_dict = torch.load(self.model_path, map_location=lambda storage, loc: storage)
        squeezenet.load_state_dict({k:v for k,v in state_dict.items() if k in squeezenet.state_dict()})

    squeezenet.classifier = nn.Sequential(*list(squeezenet.classifier._modules.values())[:-1])

    # not using the last maxpool layer
    if self.lighthead:
      self.RCNN_base = nn.Sequential(*list(squeezenet.features._modules.values())[:self.clip])
    else:
      self.RCNN_base = nn.Sequential(*list(squeezenet.features._modules.values()))

    # Fix Layers
    for layer in range(len(self.RCNN_base)):
      for p in self.RCNN_base[layer].parameters(): p.requires_grad = False

    # self.RCNN_base = _RCNN_base(vgg.features, self.classes, self.dout_base_model)
    if self.lighthead:
      self.lighthead_base = nn.Sequential(*list(squeezenet.features._modules.values())[self.clip+1:])
      self.RCNN_top = nn.Sequential(nn.Linear(490 * 7 * 7, 2048), nn.ReLU(inplace=True))
    else:
      self.RCNN_top = squeezenet.classifier

    d_in = 2048 if self.lighthead else 512

    # not using the last maxpool layer
    self.RCNN_cls_score = nn.Linear(d_in, self.n_classes)

    if self.class_agnostic:
      self.RCNN_bbox_pred = nn.Linear(d_in, 4)
    else:
      self.RCNN_bbox_pred = nn.Linear(d_in, 4 * self.n_classes) 
Example #19
Source File: torchvision_models.py    From models-comparison.pytorch with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
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

###############################################################
# VGGs

#def modify_vggs(model):
#    # Modify attributs
#    model._features = model.features
#    del model.features
#    model.linear0 = model.classifier[0]
#    model.relu0 = model.classifier[1]
#    model.dropout0 = model.classifier[2]
#    model.linear1 = model.classifier[3]
#    model.relu1 = model.classifier[4]
#    model.dropout1 = model.classifier[5]
#    model.last_linear = model.classifier[6]
#    del model.classifier
#
#    def features(self, input):
#        x = self._features(input)
#        x = x.view(x.size(0), -1)
#        x = self.linear0(x)
#        x = self.relu0(x)
#        x = self.dropout0(x) 
#        x = self.linear1(x)
#        return x
#
#    def logits(self, features):
#        x = self.relu1(features)
#        x = self.dropout1(x)
#        x = self.last_linear(x)
#        return x
#
#    def forward(self, input):
#        x = self.features(input)
#        x = self.logits(x)
#        return x
        
#    # Modify methods
#    setattr(model.__class__, 'features', features)
#    setattr(model.__class__, 'logits', logits)
#    setattr(model.__class__, 'forward', forward)  
#    return model