import torch
model = torch.hub.load('pytorch/vision:v0.10.0', 'resnext50_32x4d', pretrained=True)
# or
# model = torch.hub.load('pytorch/vision:v0.10.0', 'resnext101_32x8d', pretrained=True)
model.eval()
์ฌ์ ํ๋ จ๋ ๋ชจ๋ธ๋ค์ ์ฌ์ฉํ ๋๋ ๋์ผํ ๋ฐฉ์์ผ๋ก ์ ๊ทํ๋ ์ด๋ฏธ์ง๋ฅผ ์
๋ ฅ์ผ๋ก ๋ฃ์ด์ผ ํฉ๋๋ค.
์ฆ, ๋ฏธ๋ ๋ฐฐ์น(mini-batch)์ 3-์ฑ๋ RGB ์ด๋ฏธ์ง๋ค์ (3 x H x W)์ ํํ๋ฅผ ๊ฐ์ง๋ฉฐ, ํด๋น H์ W๋ ์ต์ 224 ์ด์์ด์ด์ผ ํฉ๋๋ค.
๊ฐ ์ด๋ฏธ์ง๋ [0, 1]์ ๋ฒ์ ๋ด์์ ๋ถ๋ฌ์์ผ ํ๋ฉฐ, mean = [0.485, 0.456, 0.406] ๊ณผ std = [0.229, 0.224, 0.225]์ ์ด์ฉํด ์ ๊ทํ๋์ด์ผ ํฉ๋๋ค.
๋ค์์ ์คํ ์์ ์
๋๋ค.
# ํ์ดํ ์น ์น ์ฌ์ดํธ์์ ์ด๋ฏธ์ง ๋ค์ด๋ก๋
import urllib
url, filename = ("https://github.com/pytorch/hub/raw/master/images/dog.jpg", "dog.jpg")
try: urllib.URLopener().retrieve(url, filename)
except: urllib.request.urlretrieve(url, filename)
# ์์ ์ฝ๋ (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) # ๋ชจ๋ธ์์ ๊ฐ์ ํ๋ ๋๋ก ๋ฏธ๋ ๋ฐฐ์น ์์ฑ
# gpu๋ฅผ ์ฌ์ฉํ ์ ์๋ค๋ฉด, ์๋๋ฅผ ์ํด ์
๋ ฅ๊ณผ ๋ชจ๋ธ์ gpu๋ก ์ฎ๊น
if torch.cuda.is_available():
input_batch = input_batch.to('cuda')
model.to('cuda')
with torch.no_grad():
output = model(input_batch)
# output์ shape๊ฐ [1000]์ธ Tensor ์๋ฃํ์ด๋ฉฐ, ์ด๋ ImageNet ๋ฐ์ดํฐ์
์ 1000๊ฐ์ ๊ฐ ํด๋์ค์ ๋ํ ๋ชจ๋ธ์ ํ์ ๋(confidence)๋ฅผ ๋ํ๋.
print(output[0])
# output์ ์ ๊ทํ๋์ง ์์์ผ๋ฏ๋ก, ํ๋ฅ ํํ๊ธฐ ์ํด softmax ํจ์๋ฅผ ์ฒ๋ฆฌ
probabilities = torch.nn.functional.softmax(output[0], dim=0)
print(probabilities)
# ImageNet ๋ฐ์ดํฐ์
๋ ์ด๋ธ ๋ค์ด๋ก๋
!wget https://raw.githubusercontent.com/pytorch/hub/master/imagenet_classes.txt
# ์นดํ
๊ณ ๋ฆฌ(ํด๋์ค) ์ฝ๊ธฐ
with open("imagenet_classes.txt", "r") as f:
categories = [s.strip() for s in f.readlines()]
# ๊ฐ ์ด๋ฏธ์ง์ ๋ํ top 5 ์นดํ
๊ณ ๋ฆฌ ์ถ๋ ฅ
top5_prob, top5_catid = torch.topk(probabilities, 5)
for i in range(top5_prob.size(0)):
print(categories[top5_catid[i]], top5_prob[i].item())
Resnext ๋ชจ๋ธ์ ๋
ผ๋ฌธ [Aggregated Residual Transformations for Deep Neural Networks]์์ ์ ์๋์์ต๋๋ค. (https://arxiv.org/abs/1611.05431).
์ฌ๊ธฐ์๋ 50๊ฐ์ ๊ณ์ธต๊ณผ 101๊ฐ์ ๊ณ์ธต์ ๊ฐ์ง๋ 2๊ฐ์ resnet ๋ชจ๋ธ์ ์ ๊ณตํ๊ณ ์์ต๋๋ค.
resnet50๊ณผ resnext50์ ์ํคํ
์ฒ ์ฐจ์ด๋ ๋
ผ๋ฌธ์ Table 1์ ์ฐธ๊ณ ํ์ญ์์ค.
ImageNet ๋ฐ์ดํฐ์
์ ๋ํ ์ฌ์ ํ๋ จ๋ ๋ชจ๋ธ์ ์๋ฌ(์ฑ๋ฅ)์ ์๋ ํ์ ๊ฐ์ต๋๋ค.
| ๋ชจ๋ธ ๊ตฌ์กฐ |
Top-1 ์ค๋ฅ |
Top-5 ์ค๋ฅ |
| resnext50_32x4d |
22.38 |
6.30 |
| resnext101_32x8d |
20.69 |
5.47 |