本文整理汇总了Python中torchvision.models.resnet18方法的典型用法代码示例。如果您正苦于以下问题:Python models.resnet18方法的具体用法?Python models.resnet18怎么用?Python models.resnet18使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类torchvision.models
的用法示例。
在下文中一共展示了models.resnet18方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [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)
示例2: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, args):
super(ResNet18Image2IMUOneTower, self).__init__()
assert args.sequence_length == 1, "ResNet18Image2IMU supports seq-len=1"
self.class_weights = args.dataset.CLASS_WEIGHTS[torch.LongTensor(
args.imus)]
resnet_model = torchvision_resnet18(pretrained=args.pretrain)
# Remove the last fully connected layer.
del resnet_model.fc
self.resnet = resnet_model
self.resnet.conv1 = nn.Conv2d(6, 64, kernel_size=(7, 7), stride=(2, 2),
padding=(3, 3), bias=False)
num_features = 512
num_frames = 1
num_classes = args.num_classes
# Make num_imu fc layers
self.imus = args.imus
for i in self.imus:
setattr(self, 'imu{}'.format(i),
nn.Linear(num_frames * num_features, num_classes))
self.dropout = nn.Dropout()
示例3: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, args):
super(ResNet18Image2IMURegress, self).__init__()
assert args.sequence_length == 1, "ResNet18Image2IMURegress supports seq-len=1"
assert args.regression, "--regression must be true"
self.class_weights = args.dataset.CLASS_WEIGHTS[torch.LongTensor(
args.imus)]
resnet_model = torchvision_resnet18(pretrained=args.pretrain)
# Remove the last fully connected layer.
del resnet_model.fc
self.resnet = resnet_model
num_features = 512
num_frames = 2
num_output = 4
# Make num_imu fc layers
self.imus = args.imus
for i in self.imus:
setattr(self, 'imu{}'.format(i),
nn.Linear(num_frames * num_features, num_output))
示例4: tl_fine_tuning
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def tl_fine_tuning(epochs=3):
# load the pre-trained model
model = models.resnet18(pretrained=True)
# replace the last layer
num_features = model.fc.in_features
model.fc = nn.Linear(num_features, 10)
# transfer the model to the GPU
model = model.to(device)
# loss function
loss_function = nn.CrossEntropyLoss()
# We'll optimize all parameters
optimizer = optim.Adam(model.parameters())
# train
for epoch in range(epochs):
print('Epoch {}/{}'.format(epoch + 1, epochs))
train_model(model, loss_function, optimizer, train_loader)
test_model(model, loss_function, val_order)
示例5: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, original_model, arch, num_classes):
super(FineTuneModel, self).__init__()
if arch.startswith('alexnet') or arch.startswith('vgg'):
self.features = original_model.features
self.fc = nn.Sequential(*list(original_model.classifier.children())[:-1])
self.classifier = nn.Sequential(
nn.Linear(4096, num_classes)
)
elif arch.startswith('resnet') or arch.startswith('resnext'):
# Everything except the last linear layer
self.features = nn.Sequential(*list(original_model.children())[:-1])
if arch == 'resnet18':
self.classifier = nn.Sequential(
nn.Linear(512, num_classes)
)
else:
self.classifier = nn.Sequential(
nn.Linear(2048, num_classes)
)
else:
raise ("Finetuning not supported on this architecture yet. Feel free to add")
self.unfreeze(False) # Freeze weights except last layer
示例6: load_net_param
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def load_net_param(self):
from torchvision.models import resnet18
resnet = resnet18(pretrained=True)
self.enc1_conv1.load_state_dict(resnet.conv1.state_dict())
self.enc1_bn1.load_state_dict(resnet.bn1.state_dict())
self.enc1_res1_1.load_state_dict(list(resnet.layer1.children())[0].state_dict())
self.enc1_res1_2.load_state_dict(list(resnet.layer1.children())[1].state_dict())
self.enc1_res2_1.load_state_dict(list(resnet.layer2.children())[0].state_dict())
self.enc1_res2_2.load_state_dict(list(resnet.layer2.children())[1].state_dict())
self.enc1_res3_1.load_state_dict(list(resnet.layer3.children())[0].state_dict())
self.enc1_res3_2.load_state_dict(list(resnet.layer3.children())[1].state_dict())
self.enc1_res4_1.load_state_dict(list(resnet.layer4.children())[0].state_dict())
self.enc1_res4_2.load_state_dict(list(resnet.layer4.children())[1].state_dict())
self.enc2_conv1.load_state_dict(resnet.conv1.state_dict())
self.enc2_bn1.load_state_dict(resnet.bn1.state_dict())
self.enc2_res1_1.load_state_dict(list(resnet.layer1.children())[0].state_dict())
self.enc2_res1_2.load_state_dict(list(resnet.layer1.children())[1].state_dict())
self.enc2_res2_1.load_state_dict(list(resnet.layer2.children())[0].state_dict())
self.enc2_res2_2.load_state_dict(list(resnet.layer2.children())[1].state_dict())
self.enc2_res3_1.load_state_dict(list(resnet.layer3.children())[0].state_dict())
self.enc2_res3_2.load_state_dict(list(resnet.layer3.children())[1].state_dict())
self.enc2_res4_1.load_state_dict(list(resnet.layer4.children())[0].state_dict())
self.enc2_res4_2.load_state_dict(list(resnet.layer4.children())[1].state_dict())
示例7: test_untargeted_resnet18
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def test_untargeted_resnet18(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.resnet18(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
示例8: gcn_embed
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def gcn_embed(self, state):
x = self.resnet18[0](state)
x = x.view(x.size(0), -1)
x = torch.sigmoid(self.resnet18[1](x))
class_embed = self.get_class_embed(x)
word_embed = self.get_word_embed(self.all_glove.detach())
x = torch.cat((class_embed.repeat(self.n, 1), word_embed), dim=1)
x = torch.mm(self.A, x)
x = F.relu(self.W0(x))
x = torch.mm(self.A, x)
x = F.relu(self.W1(x))
x = torch.mm(self.A, x)
x = F.relu(self.W2(x))
x = x.view(1, self.n)
x = self.final_mapping(x)
return x
示例9: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [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
示例10: resnet18_ids
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def resnet18_ids(num_attributes, ids_embedding_size, 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)
classifier = ResNetClassifier(BasicBlock, num_classes=num_attributes, **kwargs)
classifier_ids = ResNetClassifier(BasicBlock, num_classes=ids_embedding_size, **kwargs)
if pretrained:
state_dict = model_zoo.load_url(model_urls['resnet18'])
model.load_state_dict(
{k: v for k, v in state_dict.items() if k in model.state_dict()}
)
return model, classifier, classifier_ids
示例11: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, num_layers):
super(ResNet_BasicBlock_OS16, self).__init__()
if num_layers == 18:
resnet = models.resnet18()
# load pretrained model:
resnet.load_state_dict(torch.load("/root/deeplabv3/pretrained_models/resnet/resnet18-5c106cde.pth"))
# remove fully connected layer, avg pool and layer5:
self.resnet = nn.Sequential(*list(resnet.children())[:-3])
num_blocks = 2
print ("pretrained resnet, 18")
elif num_layers == 34:
resnet = models.resnet34()
# load pretrained model:
resnet.load_state_dict(torch.load("/root/deeplabv3/pretrained_models/resnet/resnet34-333f7ec4.pth"))
# remove fully connected layer, avg pool and layer5:
self.resnet = nn.Sequential(*list(resnet.children())[:-3])
num_blocks = 3
print ("pretrained resnet, 34")
else:
raise Exception("num_layers must be in {18, 34}!")
self.layer5 = make_layer(BasicBlock, in_channels=256, channels=512, num_blocks=num_blocks, stride=1, dilation=2)
示例12: select
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [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)
示例13: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, c_dim=128, normalize=True, use_linear=True):
''' Initialisation.
Args:
c_dim (int): output dimension of the latent embedding
normalize (bool): whether the input images should be normalized
use_linear (bool): whether a final linear layer should be used
'''
super().__init__()
self.normalize = normalize
self.use_linear = use_linear
self.features = models.resnet18(pretrained=True)
self.features.fc = nn.Sequential()
if use_linear:
self.fc = nn.Linear(512, c_dim)
elif c_dim == 512:
self.fc = nn.Sequential()
else:
raise ValueError('c_dim must be 512 if use_linear is False')
示例14: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, c_dim=128, normalize=True, use_linear=True):
''' Initialization.
Args:
c_dim (int): output dimension of the latent embedding
normalize (bool): whether the input images should be normalized
use_linear (bool): whether a final linear layer should be used
'''
super().__init__()
self.normalize = normalize
self.use_linear = use_linear
self.features = models.resnet18(pretrained=True)
self.features.fc = nn.Sequential()
if use_linear:
self.fc = nn.Linear(512, c_dim)
elif c_dim == 512:
self.fc = nn.Sequential()
else:
raise ValueError('c_dim must be 512 if use_linear is False')
示例15: __init__
# 需要导入模块: from torchvision import models [as 别名]
# 或者: from torchvision.models import resnet18 [as 别名]
def __init__(self, encoder, num_classes):
super(SegNet, self).__init__()
self.resnet = encoder
self.upsample = nn.Upsample(scale_factor=2, mode='nearest')
self.conv1 = nn.Conv2d(2048, 1024, kernel_size=3, stride=1, padding=1)
self.conv2 = nn.Conv2d(2048, 512, kernel_size=3, stride=1, padding=1)
self.conv3 = nn.Conv2d(1024, 256, kernel_size=3, stride=1, padding=1)
self.conv4 = nn.Conv2d(512, 64, kernel_size=3, stride=1, padding=1)
self.conv5 = nn.Conv2d(128, 1, kernel_size=3, stride=1, padding=1)
# resnet18
# self.conv1 = nn.Conv2d(512, 256, kernel_size=3, stride=1, padding=1)
# self.conv2 = nn.Conv2d(512, 128, kernel_size=3, stride=1, padding=1)
# self.conv3 = nn.Conv2d(256, 64, kernel_size=3, stride=1, padding=1)
# self.conv4 = nn.Conv2d(128, 64, kernel_size=3, stride=1, padding=1)
# self.conv5 = nn.Conv2d(128, 1, kernel_size=3, stride=1, padding=1)
self.relu = nn.ReLU(inplace=True)
self.sigmoid = nn.Sigmoid()