本文整理汇总了Python中torchvision.models.vgg19方法的典型用法代码示例。如果您正苦于以下问题:Python models.vgg19方法的具体用法?Python models.vgg19怎么用?Python models.vgg19使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类torchvision.models
的用法示例。
在下文中一共展示了models.vgg19方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def __init__(self, requires_grad=False):
super(Vgg19, self).__init__()
vgg_pretrained_features = models.vgg19(pretrained=True).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()
for x in range(2):
self.slice1.add_module(str(x), vgg_pretrained_features[x])
for x in range(2, 7):
self.slice2.add_module(str(x), vgg_pretrained_features[x])
for x in range(7, 12):
self.slice3.add_module(str(x), vgg_pretrained_features[x])
for x in range(12, 21):
self.slice4.add_module(str(x), vgg_pretrained_features[x])
for x in range(21, 30):
self.slice5.add_module(str(x), vgg_pretrained_features[x])
if not requires_grad:
for param in self.parameters():
param.requires_grad = False
示例2: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def __init__(self, vgg_path, layers='45', input='RGB', loss='l1'):
super(VGGLoss, self).__init__()
self.input = input
vgg = models.vgg19(pretrained=False)
if vgg_path is not '':
vgg.load_state_dict(torch.load(vgg_path))
# vgg.load_state_dict(torch.load('../../../'+vgg_path))
self.layers = [int(l) for l in layers]
layers_dict = [0, 4, 9, 18, 27, 36]
self.vgg = []
if loss == 'l1':
self.loss_func = l1_loss
# pytorch 0.4 l1_loss malfunction
elif loss == 'l2':
self.loss_func = nn.functional.mse_loss
else:
raise Exception('Do not support this loss.')
i = 0
for j in self.layers:
self.vgg.append(nn.Sequential(*list(vgg.features.children())[layers_dict[i]:layers_dict[j]]))
i = j
示例3: get_image_format
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def get_image_format(framework_name, model_name):
"""Return the correct input range and shape for target framework and model"""
special_shape = {'pytorch':{'inception_v3': (299, 299)},
'keras': {'xception': (299, 299),
'inception_v3':(299, 299),
'yolo_v3': (416, 416),
'ssd300': (300, 300)}}
special_bound = {'keras':{'vgg16':(0, 255),
'vgg19':(0, 255),
'resnet50':(0, 255),
'ssd300': (0, 255)},
'cloud': {'aip_antiporn': (0, 255),
'google_safesearch': (0, 255),
'google_objectdetection': (0, 255)}}
default_shape = (224, 224)
default_bound = (0, 1)
if special_shape.get(framework_name, None):
if special_shape[framework_name].get(model_name, None):
default_shape = special_shape[framework_name][model_name]
if special_bound.get(framework_name, None):
if special_bound[framework_name].get(model_name, None):
default_bound = special_bound[framework_name][model_name]
return {'shape': default_shape, 'bounds': default_bound}
示例4: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def __init__(self, image_size=128, c_dim = 5, net_type='vgg19', max_filters=None, global_pool='mean',use_bias=False, class_ftune = 0):
super(DiscriminatorGAP_ImageNet, self).__init__()
layers = []
nFilt = 512 if max_filters is None else max_filters
self.pnet = Vgg19(only_last=True) if net_type == 'vgg19' else None
if class_ftune > 0.:
pAll = list(self.pnet.named_parameters())
# Multiply by two for weight and bias
for pn in pAll[::-1][:2*class_ftune]:
pn[1].requires_grad = True
layers.append(nn.LeakyReLU(0.1, inplace=True))
layers.append(nn.Conv2d(512, nFilt, kernel_size=3, stride=1, padding=1))
layers.append(nn.BatchNorm2d(nFilt))
layers.append(nn.LeakyReLU(0.1, inplace=True))
layers.append(nn.Conv2d(nFilt, nFilt, kernel_size=3, stride=1, padding=1))
layers.append(nn.BatchNorm2d(nFilt))
layers.append(nn.LeakyReLU(0.1, inplace=True))
self.layers = nn.Sequential(*layers)
self.globalPool = nn.AdaptiveAvgPool2d(1) if global_pool == 'mean' else nn.AdaptiveMaxPool2d(1)
self.classifyFC = nn.Linear(nFilt, c_dim, bias=use_bias)
self.shift = torch.autograd.Variable(torch.Tensor([-.030, -.088, -.188]).view(1,3,1,1), requires_grad=False).cuda()
self.scale = torch.autograd.Variable(torch.Tensor([.458, .448, .450]).view(1,3,1,1), requires_grad=False).cuda()
self.c_dim = c_dim
示例5: forward
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def forward(self, x):
out = {}
x = x - self.mean
ci = 1
ri = 0
for layer in self.vgg19.children():
if isinstance(layer, nn.Conv2d):
ri += 1
name = 'conv{}_{}'.format(ci, ri)
elif isinstance(layer, nn.ReLU):
ri += 1
name = 'relu{}_{}'.format(ci, ri)
layer = nn.ReLU(inplace=False)
elif isinstance(layer, nn.MaxPool2d):
ri = 0
name = 'pool_{}'.format(ci)
ci += 1
elif isinstance(layer, nn.BatchNorm2d):
name = 'bn_{}'.format(ci)
else:
raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
x = layer(x)
out[name] = x
# print([x for x in out])
return out
示例6: main
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def main():
# model = models.vgg19_bn(pretrained=True)
# _, summary = weight_watcher.analyze(model, alphas=False)
# for key, value in summary.items():
# print('{:10s} : {:}'.format(key, value))
_, summary = weight_watcher.analyze(models.vgg13(pretrained=True), alphas=False)
print('vgg-13 : {:}'.format(summary['lognorm']))
_, summary = weight_watcher.analyze(models.vgg13_bn(pretrained=True), alphas=False)
print('vgg-13-BN : {:}'.format(summary['lognorm']))
_, summary = weight_watcher.analyze(models.vgg16(pretrained=True), alphas=False)
print('vgg-16 : {:}'.format(summary['lognorm']))
_, summary = weight_watcher.analyze(models.vgg16_bn(pretrained=True), alphas=False)
print('vgg-16-BN : {:}'.format(summary['lognorm']))
_, summary = weight_watcher.analyze(models.vgg19(pretrained=True), alphas=False)
print('vgg-19 : {:}'.format(summary['lognorm']))
_, summary = weight_watcher.analyze(models.vgg19_bn(pretrained=True), alphas=False)
print('vgg-19-BN : {:}'.format(summary['lognorm']))
示例7: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def __init__(self, conv_index, rgb_range=1):
super(VGG, self).__init__()
vgg_features = models.vgg19(pretrained=True).features
modules = [m for m in vgg_features]
if conv_index == '22':
self.vgg = nn.Sequential(*modules[:8])
elif conv_index == '54':
self.vgg = nn.Sequential(*modules[:35])
vgg_mean = (0.485, 0.456, 0.406)
vgg_std = (0.229 * rgb_range, 0.224 * rgb_range, 0.225 * rgb_range)
self.sub_mean = common.MeanShift(rgb_range, vgg_mean, vgg_std)
self.vgg.requires_grad = False
示例8: vgg19
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
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
示例9: get_vgg19
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def get_vgg19(model_name, model_path):
# load base model
if model_name == 'vgg19_caffe':
model = vgg19()
elif model_name == 'vgg19_pytorch':
model = vgg19(pretrained=True)
elif model_name == 'vgg19_pytorch_modified':
model = VGGModified(vgg19(), 0.2)
model.load_state_dict(torch.load('%s/%s.pkl' % (model_path, model_name))['state_dict'])
# convert model into standard form
model.classifier = nn.Sequential(utils.View(), *model.classifier._modules.values())
vgg = model.features
vgg_classifier = model.classifier
names = ['conv1_1','relu1_1','conv1_2','relu1_2','pool1',
'conv2_1','relu2_1','conv2_2','relu2_2','pool2',
'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','conv3_4','relu3_4','pool3',
'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','conv4_4','relu4_4','pool4',
'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','conv5_4','relu5_4','pool5',
'torch_view','fc6','relu6','drop6','fc7','relu7','drop7','fc8']
model = nn.Sequential()
for n, m in zip(names, list(vgg) + list(vgg_classifier)):
model.add_module(n, m)
if model_name == 'vgg19_caffe':
model.load_state_dict(torch.load('%s/%s.pth' % (model_path, model_name)))
return model
示例10: _load_keras_model
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def _load_keras_model(model_name, summary):
import keras.applications as models
switcher = {
'xception': lambda: models.xception.Xception(weights='imagenet'),
'vgg16': lambda: models.vgg16.VGG16(weights='imagenet'),
'vgg19': lambda: models.vgg19.VGG19(weights='imagenet'),
"resnet50": lambda: models.resnet50.ResNet50(weights='imagenet'),
"inception_v3": lambda: models.inception_v3.InceptionV3(weights='imagenet'),
"yolo_v3": lambda: _load_yolov3_model(),
"ssd300": lambda: _load_ssd300_model(),
"retina_resnet_50": lambda: _load_retinanet_resnet50_model()
}
_load_model = switcher.get(model_name, None)
_model = _load_model()
from perceptron.models.classification.keras import KerasModel as ClsKerasModel
from perceptron.models.detection.keras_ssd300 import KerasSSD300Model
from perceptron.models.detection.keras_yolov3 import KerasYOLOv3Model
from perceptron.models.detection.keras_retina_resnet50 import KerasResNet50RetinaNetModel
import numpy as np
format = get_image_format('keras', model_name)
if format['bounds'][1] == 1:
mean = np.array([0.485, 0.456, 0.406]).reshape((1, 1, 3))
std = np.array([0.229, 0.224, 0.225]).reshape((1, 1, 3))
preprocessing = (mean, std)
else:
preprocessing = (np.array([104, 116, 123]), 1)
switcher = {
'yolo_v3': lambda x: KerasYOLOv3Model(x, bounds=(0, 1)),
'ssd300': lambda x: KerasSSD300Model(x, bounds=(0, 255)),
'retina_resnet_50': lambda x: KerasResNet50RetinaNetModel(None, bounds=(0, 255)),
}
_wrap_model = switcher.get(
model_name,
lambda x: ClsKerasModel(x, bounds=format['bounds'], preprocessing=preprocessing))
kmodel = _wrap_model(_model)
return kmodel
示例11: _load_pytorch_model
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
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
示例12: load_pytorch_model
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
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
示例13: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import vgg19 [as 别名]
def __init__(self):
super(FeatureExtractor, self).__init__()
vgg19_model = vgg19(pretrained=True)
self.feature_extractor = nn.Sequential(*list(vgg19_model.features.children())[:18])