pytorch学习(二) torchvision.models

 torchvision.models包含解决不同任务的模型定义,包括:图像分类、像素语义分割、物体检测、实例分割、人物关键点检测、视频分类和光流。

1、关于预训练权重的一般信息

TorchVision使用PyTorch torch.hub为每个提供的架构提供预训练的权重。实例化预训练的模型将下载其权重到缓存目录中。这个目录可以使用TORCH_HOME环境变量来设置。 

2、初始化预训练的模型

 从0.13版开始,TorchVision提供了一个新的多重量支持API,用于加载不同的重量到现有的模型生成器方法。

通过weights选择不同的模型,有不同的精确度。

from torchvision.models import resnet50, ResNet50_Weights

# Old weights with accuracy 76.130%
resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)

# New weights with accuracy 80.858%
resnet50(weights=ResNet50_Weights.IMAGENET1K_V2)


# No weights - random initialization
resnet50(weights=None)

3、使用预训练模型

在使用预训练的模型之前,必须对图像进行预处理(用正确的分辨率/插值调整大小,应用推理变换,重新调整数值等)。没有标准的方法可以做到这一点,因为这取决于一个特定的模型是如何训练的。它可以在不同的模型系列、变体或甚至权重版本中有所不同。使用正确的预处理方法是至关重要的,如果不这样做,可能会导致精度下降或输出不正确。

每个预训练模型的推理变换的所有必要信息都在其权重文档中提供。为了简化推理,TorchVision将必要的预处理变换捆绑到每个模型权重中。这些可以通过weight.transforms属性访问。

# Initialize the Weight Transforms
weights = ResNet50_Weights.DEFAULT
preprocess = weights.transforms()

# Apply it to the input image
img_transformed = preprocess(img)

 一些模型使用的模块有不同的训练和评估行为,比如BN。要在这些模式之间切换,请根据情况使用model.train()或model.eval()。详情见train()或eval()。

# Initialize model
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights)

# Set model to eval mode
model.eval()

 4、模型注册机制

TorchVision提供了一个新的模型注册机制,它允许通过模型和权重的名称来重构模型。

# List available models
all_models = list_models()
classification_models = list_models(module=torchvision.models)

# Initialize models
m1 = get_model("mobilenet_v3_large", weights=None)
m2 = get_model("quantized_mobilenet_v3_large", weights="DEFAULT")

# Fetch weights
weights = get_weight("MobileNet_V3_Large_QuantizedWeights.DEFAULT")
assert weights == MobileNet_V3_Large_QuantizedWeights.DEFAULT

weights_enum = get_model_weights("quantized_mobilenet_v3_large")
assert weights_enum == MobileNet_V3_Large_QuantizedWeights

weights_enum2 = get_model_weights(torchvision.models.quantization.mobilenet_v3_large)
assert weights_enum == weights_enum2

一些公用方法 。

#获取模型名称和配置,并返回一个实例化的模型。
get_model(name, **config)
	

 5、使用来自hub的模型

 大多数预训练的模型可以直接通过PyTorch Hub访问,而无需安装TorchVision。

import torch

# Option 1: passing weights param as string
model = torch.hub.load("pytorch/vision", "resnet50", weights="IMAGENET1K_V2")

# Option 2: passing weights param as enum
weights = torch.hub.load("pytorch/vision", "get_weight", weights="ResNet50_Weights.IMAGENET1K_V2")
model = torch.hub.load("pytorch/vision", "resnet50", weights=weights)

6、分类网络

    AlexNet
    ConvNeXt
    DenseNet
    EfficientNet
    EfficientNetV2
    GoogLeNet
    Inception V3
    MaxVit
    MNASNet
    MobileNet V2
    MobileNet V3
    RegNet
    ResNet
    ResNeXt
    ShuffleNet V2
    SqueezeNet
    SwinTransformer
    VGG
    VisionTransformer
    Wide ResNet

 一个使用模型的例子:

from torchvision.io import read_image
from torchvision.models import resnet50, ResNet50_Weights

img = read_image("test/assets/encode_jpeg/grace_hopper_517x606.jpg")

# Step 1: Initialize model with the best available weights
weights = ResNet50_Weights.DEFAULT
model = resnet50(weights=weights)
model.eval()

# Step 2: Initialize the inference transforms
preprocess = weights.transforms()

# Step 3: Apply inference preprocessing transforms
batch = preprocess(img).unsqueeze(0)

# Step 4: Use the model and print the predicted category
prediction = model(batch).squeeze(0).softmax(0)
class_id = prediction.argmax().item()
score = prediction[class_id].item()
category_name = weights.meta["categories"][class_id]
print(f"{category_name}: {100 * score:.1f}%")

 目前对于这个的理解还比较浅,以后应用多了会再来完善。

 

你可能感兴趣的:(pytorch,学习,深度学习)