To use a Res2Net model for inference, load a pretrained variant using timm.create_model, resolve the appropriate data configuration for preprocessing, and apply the transformation to your input image. Ensure you add a batch dimension before passing the tensor to the model.
Common Res2Net variants include:
res2net101_26w_4sres2net50_14w_8sres2net50_26w_4sres2net50_26w_6sres2net50_26w_8sres2net50_48w_2s
import timm
import torch
import urllib
from PIL import Image
from timm.data import resolve_data_config
from timm.data.transforms_factory import create_transform
# 1. Load pretrained model
model = timm.create_model('res2net101_26w_4s', pretrained=True)
model.eval()
# 2. Preprocess image
config = resolve_data_config({}, model=model)
transform = create_transform(**config)
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
urllib.request.urlretrieve(url, filename)
img = Image.open(filename).convert('RGB')
tensor = transform(img).unsqueeze(0) # transform and add batch dimension
# 3. Get predictions
with torch.inference_mode():
out = model(tensor)
probabilities = torch.nn.functional.softmax(out[0], dim=0)