本文整理汇总了Python中torchvision.models.resnet50方法的典型用法代码示例。如果您正苦于以下问题:Python models.resnet50方法的具体用法?Python models.resnet50怎么用?Python models.resnet50使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类torchvision.models
的用法示例。
在下文中一共展示了models.resnet50方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [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)
示例2: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self):
super(ImageEmbedding, self).__init__()
resnet = models.resnet50(pretrained=True)
modules = list(resnet.children())[:-1] # we do not use the last fc layer.
self.visionMLP = nn.Sequential(*modules)
self.visual_embedding = nn.Sequential(
nn.Linear(opts.imfeatDim, opts.embDim),
nn.Tanh(),
)
self.semantic_branch = nn.Linear(opts.embDim, opts.numClasses)
self.fc_visual = nn.Sequential(
nn.Linear(opts.embDim, opts.embDim),
nn.BatchNorm1d(opts.embDim),
nn.Tanh(),
)
示例3: get_image_format
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [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: test_untargeted_resnet50
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def test_untargeted_resnet50(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.resnet50(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
示例5: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self,non_layers=[0,1,1,1],stripes=[16,16,16,16],non_type='normal',temporal=None):
super(Resnet50_NL,self).__init__()
original = models.resnet50(pretrained=True).state_dict()
if non_type == 'normal':
self.backbone = res.ResNet_Video_nonlocal(last_stride=1,non_layers=non_layers)
elif non_type == 'stripe':
self.backbone = res.ResNet_Video_nonlocal_stripe(last_stride = 1, non_layers=non_layers, stripes=stripes)
elif non_type == 'hr':
self.backbone = res.ResNet_Video_nonlocal_hr(last_stride = 1, non_layers=non_layers, stripes=stripes)
elif non_type == 'stripe_hr':
self.backbone = res.ResNet_Video_nonlocal_stripe_hr(last_stride = 1, non_layers=non_layers, stripes=stripes)
for key in original:
if key.find('fc') != -1:
continue
self.backbone.state_dict()[key].copy_(original[key])
del original
self.temporal = temporal
if self.temporal == 'Done':
self.avgpool = nn.AdaptiveAvgPool3d(1)
示例6: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self, num_layers, pretrained, num_input_images=1):
super(ResnetEncoder, self).__init__()
self.num_ch_enc = np.array([64, 64, 128, 256, 512])
resnets = {18: models.resnet18,
34: models.resnet34,
50: models.resnet50,
101: models.resnet101,
152: models.resnet152}
if num_layers not in resnets:
raise ValueError("{} is not a valid number of resnet layers".format(num_layers))
if num_input_images > 1:
self.encoder = resnet_multiimage_input(num_layers, pretrained, num_input_images)
else:
self.encoder = resnets[num_layers](pretrained)
if num_layers > 34:
self.num_ch_enc[1:] *= 4
示例7: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self, class_num):
super(ft_net, self).__init__()
model_ft = models.resnet50(pretrained=True)
# avg pooling to global pooling
model_ft.avgpool = nn.AdaptiveAvgPool2d((1,1))
num_ftrs = model_ft.fc.in_features
add_block = []
num_bottleneck = 512
add_block += [nn.Linear(num_ftrs, num_bottleneck)]
add_block += [nn.BatchNorm1d(num_bottleneck)]
add_block += [nn.LeakyReLU(0.1)]
add_block += [nn.Dropout(p=0.5)] #default dropout rate 0.5
add_block = nn.Sequential(*add_block)
add_block.apply(weights_init_kaiming)
model_ft.fc = add_block
self.model = model_ft
classifier = []
classifier += [nn.Linear(num_bottleneck, class_num)]
classifier = nn.Sequential(*classifier)
classifier.apply(weights_init_classifier)
self.classifier = classifier
示例8: build_resnet_50
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def build_resnet_50(self):
model = models.resnet50(num_classes=self.num_classes)
model_with_bottleneck = AdaptResNetBottleneck(model, self.embedding_size, self.num_classes)
model_with_loss = ResNetCenterLoss(
model_with_bottleneck,
self.num_classes,
self.embedding_size,
center_loss_weight=.0,
use_cuda=self.use_cuda
)
model_with_loss = model_with_loss.cuda() if self.use_cuda else model_with_loss.cpu()
model_with_loss.train(False)
if self.use_cuda:
checkpoint = torch.load(self.weights_path)
else:
checkpoint = torch.load(self.weights_path, map_location=lambda storage, loc: storage)
model_with_loss.load_state_dict(checkpoint['model_state'])
return model_with_loss
示例9: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self, class_num):
super(ft_net, self).__init__()
model_ft = models.resnet50(pretrained=True)
# avg pooling to global pooling
model_ft.avgpool = nn.AdaptiveAvgPool2d((1,1))
add_block = []
num_bottleneck = 2048
add_block += [nn.BatchNorm1d(num_bottleneck)]
add_block = nn.Sequential(*add_block)
add_block.apply(weights_init_kaiming)
model_ft.fc = add_block
self.model = model_ft
self.fc0 = nn.Linear(num_bottleneck, class_num, bias = True)
init.normal(self.fc0.weight.data, std=0.001)
if hasattr(self.fc0.bias, 'data'):
init.constant(self.fc0.bias.data, 0.0)
示例10: select
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [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)
示例11: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self, model_type='resnet50', layer_type='layer4'):
super().__init__()
# get model
if model_type == 'resnet50':
original_model = models.resnet50(pretrained=True)
elif model_type == 'resnet101':
original_model = models.resnet101(pretrained=True)
else:
raise NameError('Unknown model_type passed')
# get requisite layer
if layer_type == 'layer2':
num_layers = 6
pool_size = 28
elif layer_type == 'layer3':
num_layers = 7
pool_size = 14
elif layer_type == 'layer4':
num_layers = 8
pool_size = 7
else:
raise NameError('Uknown layer_type passed')
self.features = nn.Sequential(*list(original_model.children())[:num_layers])
self.avgpool = nn.AvgPool2d(pool_size, stride=1)
示例12: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self,option = 'resnet18',pret=True):
super(ResBase, self).__init__()
self.dim = 2048
if option == 'resnet18':
model_ft = models.resnet18(pretrained=pret)
self.dim = 512
if option == 'resnet50':
model_ft = models.resnet50(pretrained=pret)
if option == 'resnet101':
model_ft = models.resnet101(pretrained=pret)
if option == 'resnet152':
model_ft = models.resnet152(pretrained=pret)
if option == 'resnet200':
model_ft = Res200()
if option == 'resnetnext':
model_ft = ResNeXt(layer_num=101)
mod = list(model_ft.children())
mod.pop()
#self.model_ft =model_ft
self.features = nn.Sequential(*mod)
示例13: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self, requires_grad=False, pretrained=True, num=18):
super(resnet, self).__init__()
if(num==18):
self.net = tv.resnet18(pretrained=pretrained)
elif(num==34):
self.net = tv.resnet34(pretrained=pretrained)
elif(num==50):
self.net = tv.resnet50(pretrained=pretrained)
elif(num==101):
self.net = tv.resnet101(pretrained=pretrained)
elif(num==152):
self.net = tv.resnet152(pretrained=pretrained)
self.N_slices = 5
self.conv1 = self.net.conv1
self.bn1 = self.net.bn1
self.relu = self.net.relu
self.maxpool = self.net.maxpool
self.layer1 = self.net.layer1
self.layer2 = self.net.layer2
self.layer3 = self.net.layer3
self.layer4 = self.net.layer4
示例14: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self):
super(ResNet50Fc, self).__init__()
model_resnet50 = models.resnet50(pretrained=True)
self.conv1 = model_resnet50.conv1
self.bn1 = model_resnet50.bn1
self.relu = model_resnet50.relu
self.maxpool = model_resnet50.maxpool
self.layer1 = model_resnet50.layer1
self.layer2 = model_resnet50.layer2
self.layer3 = model_resnet50.layer3
self.layer4 = model_resnet50.layer4
self.avgpool = model_resnet50.avgpool
self.__in_features = model_resnet50.fc.in_features
示例15: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet50 [as 别名]
def __init__(self):
super(ResNet50Fc, self).__init__()
model_resnet50 = models.resnet50(pretrained=True)
self.conv1 = model_resnet50.conv1
self.bn1 = model_resnet50.bn1
self.relu = model_resnet50.relu
self.maxpool = model_resnet50.maxpool
self.layer1 = model_resnet50.layer1
self.layer2 = model_resnet50.layer2
self.layer3 = model_resnet50.layer3
self.layer4 = model_resnet50.layer4
self.avgpool = model_resnet50.avgpool