vgg16 清华镜像_Python models.vgg16方法代码示例

本文详细介绍了Python中torchvision.models.vgg16的使用方法,包括初始化、特征提取、预训练模型加载等。通过18个代码示例,展示了vgg16模型在不同场景下的应用,如图像分类、特征提取和模型迁移学习等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文整理汇总了Python中torchvision.models.vgg16方法的典型用法代码示例。如果您正苦于以下问题:Python models.vgg16方法的具体用法?Python models.vgg16怎么用?Python models.vgg16使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在模块torchvision.models的用法示例。

在下文中一共展示了models.vgg16方法的18个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: __init__

​点赞 7

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, alignsize = 8, reddim = 32, loadweight = True, model = None, downsample = 4):

super(crop_model_multi_scale_shared, self).__init__()

if model == 'shufflenetv2':

self.Feat_ext = shufflenetv2_base(loadweight,downsample)

self.DimRed = nn.Conv2d(812, reddim, kernel_size=1, padding=0)

elif model == 'mobilenetv2':

self.Feat_ext = mobilenetv2_base(loadweight,downsample)

self.DimRed = nn.Conv2d(448, reddim, kernel_size=1, padding=0)

elif model == 'vgg16':

self.Feat_ext = vgg_base(loadweight,downsample)

self.DimRed = nn.Conv2d(1536, reddim, kernel_size=1, padding=0)

elif model == 'resnet50':

self.Feat_ext = resnet50_base(loadweight,downsample)

self.DimRed = nn.Conv2d(3584, reddim, kernel_size=1, padding=0)

self.downsample2 = nn.UpsamplingBilinear2d(scale_factor=1.0/2.0)

self.upsample2 = nn.UpsamplingBilinear2d(scale_factor=2.0)

self.RoIAlign = RoIAlignAvg(alignsize, alignsize, 1.0/2**downsample)

self.RoDAlign = RoDAlignAvg(alignsize, alignsize, 1.0/2**downsample)

self.FC_layers = fc_layers(reddim*2, alignsize)

开发者ID:HuiZeng,项目名称:Grid-Anchor-based-Image-Cropping-Pytorch,代码行数:23,

示例2: get_image_format

​点赞 7

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [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}

开发者ID:advboxes,项目名称:perceptron-benchmark,代码行数:25,

示例3: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self):

super(DANNet, self).__init__()

model = models.vgg16(pretrained=True) #False

self.features = model.features

for param in self.features.parameters(): #NOTE: prune:True // finetune:False

param.requires_grad = True

self.classifier = nn.Sequential(

nn.Dropout(),

nn.Linear(25088, 4096),

nn.ReLU(inplace=True),

nn.Dropout(),

nn.Linear(4096, 4096),

nn.ReLU(inplace=True),

)

self.cls_fc = nn.Linear(4096, 31)

开发者ID:jindongwang,项目名称:transferlearning,代码行数:19,

示例4: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, num_classes):

super().__init__()

feats = list(models.vgg16(pretrained=True).features.children())

self.feats = nn.Sequential(*feats[0:9])

self.feat3 = nn.Sequential(*feats[10:16])

self.feat4 = nn.Sequential(*feats[17:23])

self.feat5 = nn.Sequential(*feats[24:30])

for m in self.modules():

if isinstance(m, nn.Conv2d):

m.requires_grad = False

self.fconn = nn.Sequential(

nn.Conv2d(512, 4096, 7),

nn.ReLU(inplace=True),

nn.Dropout(),

nn.Conv2d(4096, 4096, 1),

nn.ReLU(inplace=True),

nn.Dropout(),

)

self.score_feat3 = nn.Conv2d(256, num_classes, 1)

self.score_feat4 = nn.Conv2d(512, num_classes, 1)

self.score_fconn = nn.Conv2d(4096, num_classes, 1)

开发者ID:mapleneverfade,项目名称:pytorch-semantic-segmentation,代码行数:27,

示例5: test_untargeted_vgg16

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def test_untargeted_vgg16(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.vgg16(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

开发者ID:advboxes,项目名称:perceptron-benchmark,代码行数:19,

示例6: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, alignsize = 8, reddim = 32, loadweight = True, model = None, downsample = 4):

super(crop_model_multi_scale_individual, self).__init__()

if model == 'shufflenetv2':

self.Feat_ext1 = shufflenetv2_base(loadweight,downsample)

self.Feat_ext2 = shufflenetv2_base(loadweight,downsample)

self.Feat_ext3 = shufflenetv2_base(loadweight,downsample)

self.DimRed = nn.Conv2d(232, reddim, kernel_size=1, padding=0)

elif model == 'mobilenetv2':

self.Feat_ext1 = mobilenetv2_base(loadweight,downsample)

self.Feat_ext2 = mobilenetv2_base(loadweight,downsample)

self.Feat_ext3 = mobilenetv2_base(loadweight,downsample)

self.DimRed = nn.Conv2d(96, reddim, kernel_size=1, padding=0)

elif model == 'vgg16':

self.Feat_ext1 = vgg_base(loadweight,downsample)

self.Feat_ext2 = vgg_base(loadweight,downsample)

self.Feat_ext3 = vgg_base(loadweight,downsample)

self.DimRed = nn.Conv2d(512, reddim, kernel_size=1, padding=0)

self.downsample2 = nn.UpsamplingBilinear2d(scale_factor=1.0/2.0)

self.upsample2 = nn.UpsamplingBilinear2d(scale_factor=2.0)

self.RoIAlign = RoIAlignAvg(alignsize, alignsize, 1.0/2**downsample)

self.RoDAlign = RoDAlignAvg(alignsize, alignsize, 1.0/2**downsample)

self.FC_layers = fc_layers(reddim*2, alignsize)

开发者ID:lld533,项目名称:Grid-Anchor-based-Image-Cropping-Pytorch,代码行数:26,

示例7: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, opt, pretrained=True):

super(vgg16, self).__init__()

self.model_path = '%s/imagenet_weights/vgg16_caffe.pth' %(opt.data_path)

self.pretrained = pretrained

vgg = models.vgg16()

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

self.fc = vgg.classifier

self.pooling = nn.AdaptiveAvgPool2d((7,7))

if self.pretrained:

print("Loading pretrained weights from %s" %(self.model_path))

state_dict = torch.load(self.model_path)

vgg.load_state_dict({k:v for k,v in state_dict.items() if k in vgg.state_dict()})

# not using the last maxpool layer

self.cnn_net = nn.Sequential(*list(vgg.features._modules.values())[:-1])

开发者ID:jiasenlu,项目名称:NeuralBabyTalk,代码行数:19,

示例8: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, num_classes):

super(FCN16, self).__init__()

feats = list(models.vgg16(pretrained=True).features.children())

self.feats = nn.Sequential(*feats[0:17])

self.pool4 = nn.Sequential(*feats[17:24])

self.pool5 = nn.Sequential(*feats[24:])

self.fconn = nn.Sequential(nn.Conv2d(512, 4096, 7, padding=3),

nn.ReLU(inplace=True),

nn.Conv2d(4096, 4096, 1),

nn.ReLU(inplace=True),

nn.Conv2d(4096, num_classes, 1)

)

self.score_pool4 = nn.Conv2d(512, num_classes, 1)

self.activation = nn.Sigmoid()

开发者ID:saeedizadi,项目名称:binseg_pytoch,代码行数:18,

示例9: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, num_classes):

super(SegNet, self).__init__()

modules= list(models.vgg16(pretrained=True).features.children())

self.conv1 = nn.Sequential(*modules[0:4])

self.conv2 = nn.Sequential(*modules[5:9])

self.conv3 = nn.Sequential(*modules[10:16])

self.conv4 = nn.Sequential(*modules[17:23])

self.conv5 = nn.Sequential(*modules[24:30])

self.dec512 = DecodeBlock(512,512,3,1,num_layers=3)

self.dec256 = DecodeBlock(512, 256, 3, 1, num_layers=3)

self.dec128 = DecodeBlock(256, 128, 3, 1, num_layers=3)

self.dec64 = DecodeBlock(128, 64, 3, 1, num_layers=2)

self.final = nn.Sequential(nn.Conv2d(64, 64, kernel_size=3, stride=1, padding=1),

nn.Conv2d(64, 1, kernel_size=3, padding=1))

self.activation = nn.Sigmoid()

initialize_weights(self.dec512,self.dec256,self.dec128,self.dec64, self.final)

开发者ID:saeedizadi,项目名称:binseg_pytoch,代码行数:25,

示例10: vgg16_sp

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def vgg16_sp(num_classes, pretrained=True, num_maps=1024):

model = models.vgg16(pretrained=False)

if pretrained:

model_path = 'models/VGG16_ImageNet.pt'

if os.path.isfile(model_path):

state_dict = torch.load(model_path)

model.load_state_dict(state_dict)

else:

print('Please download the pretrained VGG16 into ./models')

num_features = model.features[28].out_channels

pooling = nn.Sequential()

pooling.add_module('adconv', nn.Conv2d(num_features, num_maps, kernel_size=3, stride=1, padding=1, groups=2, bias=True))

pooling.add_module('maps', nn.ReLU())

pooling.add_module('sp', SoftProposal())

pooling.add_module('sum', SpatialSumOverMap())

return SPNetWSL(model, num_classes, num_maps, pooling)

开发者ID:yeezhu,项目名称:SPN.pytorch,代码行数:19,

示例11: decom_vgg16

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def decom_vgg16():

# the 30th layer of features is relu of conv5_3

if opt.caffe_pretrain:

model = vgg16(pretrained=False)

if not opt.load_path:

model.load_state_dict(t.load(opt.caffe_pretrain_path))

else:

model = vgg16(not opt.load_path)

features = list(model.features)[:30]

classifier = model.classifier

classifier = list(classifier)

del classifier[6]

if not opt.use_drop:

del classifier[5]

del classifier[2]

classifier = nn.Sequential(*classifier)

# freeze top4 conv

for layer in features[:10]:

for p in layer.parameters():

p.requires_grad = False

return nn.Sequential(*features), classifier

开发者ID:FederatedAI,项目名称:FATE,代码行数:27,

示例12: getNetwork

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def getNetwork(args):

if (args.net_type == 'alexnet'):

net = models.alexnet(pretrained=args.finetune)

file_name = 'alexnet'

elif (args.net_type == 'vggnet'):

if(args.depth == 16):

net = models.vgg16(pretrained=args.finetune)

file_name = 'vgg-%s' %(args.depth)

elif (args.net_type == 'inception'):

net = models.inception(pretrained=args.finetune)

file_name = 'inceptino-v3'

elif (args.net_type == 'resnet'):

net = resnet(args.finetune, args.depth)

file_name = 'resnet-%s' %(args.depth)

else:

print('Error : Network should be either [VGGNet / ResNet]')

sys.exit(1)

return net, file_name

开发者ID:meliketoy,项目名称:fine-tuning.pytorch,代码行数:21,

示例13: select

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def select(self, model_name=None):

"""select models to be run"""

logging.info("Run details")

logging.info("=" * 71)

models = [

self.alexnet,

self.resnet18,

self.resnet50,

self.vgg16,

self.squeezenet,

]

if model_name:

self.models = [

model for model in models for name in model_name if name == model.name

]

logging.info("Selected model(s) :: ")

for m in self.models:

logging.info("%s ------------- Batchsize :: %s " % (m.name, m.batch))

logging.info("=" * 71)

开发者ID:intel,项目名称:stacks-usecase,代码行数:21,

示例14: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, requires_grad=False):

super(Vgg16, self).__init__()

vgg_pretrained_features = models.vgg16(pretrained=True).features

self.slice1 = torch.nn.Sequential()

self.slice2 = torch.nn.Sequential()

self.slice3 = torch.nn.Sequential()

self.slice4 = torch.nn.Sequential()

for x in range(4):

self.slice1.add_module(str(x), vgg_pretrained_features[x])

for x in range(4, 9):

self.slice2.add_module(str(x), vgg_pretrained_features[x])

for x in range(9, 16):

self.slice3.add_module(str(x), vgg_pretrained_features[x])

for x in range(16, 23):

self.slice4.add_module(str(x), vgg_pretrained_features[x])

if not requires_grad:

for param in self.parameters():

param.requires_grad = False

开发者ID:pytorch,项目名称:examples,代码行数:20,

示例15: main

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [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']))

开发者ID:D-X-Y,项目名称:AutoDL-Projects,代码行数:20,

示例16: __init__

​点赞 6

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def __init__(self, num_classes=12):

super(ClassifierMMD, self).__init__()

model_ft = models.vgg16(pretrained=True)

mod = list(model_ft.classifier.children())

mod.pop()

self.classifier1 = nn.Sequential(*mod)

self.classifier2 = nn.Sequential(

nn.Dropout(),

nn.Linear(4096, 1000),

nn.ReLU(inplace=True),

)

self.classifier3 = nn.Sequential(

nn.BatchNorm1d(1000,affine=True),

nn.Dropout(),

nn.ReLU(inplace=True),

)

self.last = nn.Linear(1000, num_classes)

开发者ID:mil-tokyo,项目名称:MCD_DA,代码行数:19,

示例17: _init_head_tail

​点赞 5

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def _init_head_tail(self):

self.vgg = models.vgg16()

# Remove fc8

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

# Fix the layers before conv3:

for layer in range(10):

for p in self.vgg.features[layer].parameters(): p.requires_grad = False

# not using the last maxpool layer

self._layers['head'] = nn.Sequential(*list(self.vgg.features._modules.values())[:-1])

开发者ID:Sunarker,项目名称:Collaborative-Learning-for-Weakly-Supervised-Object-Detection,代码行数:13,

示例18: get_model

​点赞 5

# 需要导入模块: from torchvision import models [as 别名]

# 或者: from torchvision.models import vgg16 [as 别名]

def get_model(name, n_classes, sync_bn=False, version=None):

model = _get_model_instance(name)

if name in ['frrnA', 'frrnB']:

model = model(n_classes, model_type=name[-1])

elif name in ['fcn32s', 'fcn16s', 'fcn8s']:

model = model(n_classes=n_classes)

vgg16 = models.vgg16(pretrained=True)

model.init_vgg16_params(vgg16)

elif name == 'segnet':

model = model(n_classes=n_classes,

is_unpooling=True)

vgg16 = models.vgg16(pretrained=True)

model.init_vgg16_params(vgg16)

elif name == 'unet':

model = model(n_classes=n_classes,

is_batchnorm=True,

in_channels=3,

is_deconv=True)

elif name == 'pspnet':

model = model(n_classes=n_classes, version=version)

elif name == 'plard':

model = model(n_classes=n_classes, version=version)

elif name == 'icnet':

model = model(n_classes=n_classes, with_bn=False, version=version)

elif name == 'icnetBN':

model = model(n_classes=n_classes, with_bn=True, version=version)

else:

model = model(n_classes=n_classes)

return model

开发者ID:zhechen,项目名称:PLARD,代码行数:39,

注:本文中的torchvision.models.vgg16方法示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值