当前位置:网站首页>Get the network input dimensions of the pretrained model
Get the network input dimensions of the pretrained model
2022-08-05 06:45:00 【ProfSnail】
When learning about neural networks,Pre-trained network packages are often used.
例如
from torchvision import models
resnet = models.res18(pretrained=True)
But when we are beginners in the use of puzzled:What size image do I need to enter??
解决方案:
方法一:读torchvision.models的说明文档
打开torchvision.models的网站:
https://pytorch.org/hub/research-models
Search for the model name you need,得到resnet的网站:
https://pytorch.org/hub/pytorch_vision_resnet/
在里面看到resnet的指导文档:
import torch
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet18', pretrained=True)
# or any of these variants
# model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet34', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet50', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet101', pretrained=True)
# model = torch.hub.load('pytorch/vision:v0.10.0', 'resnet152', pretrained=True)
model.eval()
All pre-trained models expect input images normalized in the same way, i.e. mini-batches of 3-channel RGB images of shape (3 x H x W), where H and W are expected to be at least 224. The images have to be loaded in to a range of [0, 1] and then normalized using mean = [0.485, 0.456, 0.406] and std = [0.229, 0.224, 0.225].
Here’s a sample execution.
# sample execution (requires torchvision)
from PIL import Image
from torchvision import transforms
input_image = Image.open(filename)
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # create a mini-batch as expected by the model
# move the input and model to GPU for speed if available
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
with torch.no_grad():
output = model(input_batch)
# Tensor of shape 1000, with confidence scores over Imagenet's 1000 classes
print(output[0])
# The output has unnormalized scores. To get probabilities, you can run a softmax on it.
probabilities = torch.nn.functional.softmax(output[0], dim=0)
print(probabilities)
从中,可以了解到,The image needs to be scaled to size[224, 224].
方法二:读GitHub源代码
除了看torchvision的指导文档,也可以进入githubsee the comments in the source code(View on GitHub):
GithubThe code includes the following:
class ResNet18_Weights(WeightsEnum):
IMAGENET1K_V1 = Weights(
url="https://download.pytorch.org/models/resnet18-f37072fd.pth",
transforms=partial(ImageClassification, crop_size=224),
meta={
**_COMMON_META,
"num_params": 11689512,
"recipe": "https://github.com/pytorch/vision/tree/main/references/classification#resnet",
"_metrics": {
"ImageNet-1K": {
"[email protected]": 69.758,
"[email protected]": 89.078,
}
},
"_docs": """These weights reproduce closely the results of the paper using a simple training recipe.""",
},
)
DEFAULT = IMAGENET1K_V1
由其中的crop_size=224Know that it should be scaled or cropped to224大小.

方法三:暴力测试
The size of the size design for yourself think feasible,loop in a certain interval,如果尺寸不合适,PytorchIt will report an error that the model size is not compatible.用exceptSkip these exceptions,保留tryThe size of the success.
transfer_model = resnet18(pretrained=True)
print(transfer_model)
transfer_model.eval()
transfer_model = transfer_model.cuda()
batch_size = 16
ok_list = []
for length in range(1, 1000):
x = torch.zeros(batch_size, 3, length, length, requires_grad=False).cuda()
print('length = {}'.format(length))
try:
torch_out = transfer_model(x)
print('length = {} OK!!!!'.format(length))
ok_list.append(length)
# break
except:
continue
print(ok_list)
hard test,When trying to enter the size,This network model can run through,Run through and test step by step.注意,Since there are some downsampling rounding operations in the neural network,So the size is in some range,For example, the output of the code just now is:
...
length = 998
length = 999
[193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224]
尺寸224Just one of the acceptable sizes,It is also the original size of the designer.
边栏推荐
猜你喜欢

滚动条问题,未解决

NAT experiment

Nacos集群的搭建过程详解

el-progress实现进度条颜色不同

ALC experiment

Alibaba Cloud Video on Demand

VLAN is introduced with the experiment

NB-IOT智能云家具项目系列实站
![In-depth analysis if according to data authority @datascope (annotation + AOP + dynamic sql splicing) [step by step, with analysis process]](/img/b5/03f55bb9058c08a48eae368233376c.png)
In-depth analysis if according to data authority @datascope (annotation + AOP + dynamic sql splicing) [step by step, with analysis process]

el-autocomplete use
随机推荐
document.querySelector()方法
数组&的运算
In-depth analysis if according to data authority @datascope (annotation + AOP + dynamic sql splicing) [step by step, with analysis process]
VSCode编写OpenCV
H5开发调试-Fiddler手机抓包
自营商城提高用户留存小技巧,商城对接小游戏分享
The future of cloud gaming
[Problem has been resolved]-Virtual machine error contains a file system with errors check forced
记录vue-页面缓存问题
Wireshark packet capture and common filtering methods
D41_buffer pool
Come, come, let you understand how Cocos Creator reads and writes JSON files
图像处理、分析与机器视觉一书纠错笔记
多用户商城多商户B2B2C拼团砍价秒杀支持小程序H5+APP全开源
HelloWorld
Pytorch分布式并行处理
D39_ coordinate transformation
txt文件英语单词词频统计
vs2017关于函数命名方面的注意事项
网络协议基础-学习笔记