promotion_model / predict.py
011nuyha's picture
Rename model/predict.py to predict.py
9c54c60 verified
import torch
from efficientnet_pytorch import EfficientNet
import torch.nn.functional as F
# ๋ชจ๋ธ ํด๋ž˜์Šค ์ •์˜ ๋ฐ ๋ชจ๋ธ ๋กœ๋“œ
model_name = 'efficientnet-b0' # ์‚ฌ์šฉํ•œ EfficientNet ๋ชจ๋ธ์˜ ์ด๋ฆ„์— ๋งž๊ฒŒ ์ˆ˜์ •
model = EfficientNet.from_name(model_name)
num_classes = 2
model._fc = torch.nn.Linear(model._fc.in_features, num_classes)
# ๋ชจ๋ธ ๊ฐ€์ค‘์น˜ ๋กœ๋“œ
model.load_state_dict(torch.load('promotion_model.pt', map_location=torch.device('cpu')))
# ๋ชจ๋ธ์„ ํ‰๊ฐ€ ๋ชจ๋“œ๋กœ ์„ค์ •
model.eval()
# ์˜ˆ์ œ ๋ฐ์ดํ„ฐ (์ž…๋ ฅ ๋ฐ์ดํ„ฐ์˜ ํ˜•ํƒœ์— ๋งž๊ฒŒ ์ˆ˜์ •ํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค)
# EfficientNet ๋ชจ๋ธ์— ์ž…๋ ฅ๋˜๋Š” ๋ฐ์ดํ„ฐ๋Š” 224x224 ํฌ๊ธฐ์˜ ์ด๋ฏธ์ง€์ž…๋‹ˆ๋‹ค.
# ์—ฌ๊ธฐ์„œ๋Š” ์ž„์˜์˜ ๋ฐ์ดํ„ฐ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.
from PIL import Image
from torchvision import transforms
# ์ด๋ฏธ์ง€ ์ „์ฒ˜๋ฆฌ
preprocess = transforms.Compose([
transforms.Resize(224),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
# ์˜ˆ์ œ ์ด๋ฏธ์ง€ ๋กœ๋“œ
input_image = Image.open('fake_test.webp') # ์‹ค์ œ ์ด๋ฏธ์ง€ ๊ฒฝ๋กœ๋กœ ์ˆ˜์ •
# input_image = Image.open('real_test.jpg')
input_tensor = preprocess(input_image)
input_batch = input_tensor.unsqueeze(0) # ๋ฐฐ์น˜ ์ฐจ์› ์ถ”๊ฐ€
# CUDA ์‚ฌ์šฉ (GPU๊ฐ€ ์žˆ๋Š” ๊ฒฝ์šฐ)
if torch.cuda.is_available():
model = model.to('cuda')
input_batch = input_batch.to('cuda')
# ์˜ˆ์ธก ์ˆ˜ํ–‰
with torch.no_grad():
output = model(input_batch)
# ์˜ˆ์ธก ๊ฒฐ๊ณผ ์ถœ๋ ฅ
# print(output)
probabilities = F.softmax(output, dim=1)
# ์˜ˆ์ธก ๊ฒฐ๊ณผ ์ถœ๋ ฅ
# print(probabilities)
# ๊ฐ€์žฅ ๋†’์€ ํ™•๋ฅ ์„ ๊ฐ€์ง„ ํด๋ž˜์Šค ํ™•์ธ
_, predicted_class = torch.max(probabilities, 1)
# ์˜ˆ์ธก ๊ฒฐ๊ณผ ์ถœ๋ ฅ
print('Predicted class:')
print('Fake' if predicted_class.item()==0 else 'Real')