Views
No views yet
brand)1import torch, torch.nn as nn
2from huggingface_hub import hf_hub_download
3from torchvision import transforms
4from torchvision.models import resnet50, convnext_tiny
5from PIL import Image
6
7path = hf_hub_download("ryosiswand/convnext_tiny-stanford-cars-brand", "model.pth")
8ckpt = torch.load(path, map_location="cpu", weights_only=False)
9
10# bangun arsitektur sesuai ckpt["arch"], lalu muat bobotnya
11if ckpt["arch"] == "convnext_tiny":
12 model = convnext_tiny(weights=None)
13 model.classifier[2] = nn.Linear(model.classifier[2].in_features, ckpt["num_classes"])
14else:
15 model = resnet50(weights=None)
16 model.fc = nn.Linear(model.fc.in_features, ckpt["num_classes"])
17model.load_state_dict(ckpt["state_dict"])
18model.eval()
19
20tf = transforms.Compose([
21 transforms.Resize(int(ckpt["img_size"]*1.14)), transforms.CenterCrop(ckpt["img_size"]), transforms.ToTensor(),
22 transforms.Normalize(ckpt["mean"], ckpt["std"]),
23])
24img = Image.open("mobil.jpg").convert("RGB")
25probs = model(tf(img).unsqueeze(0)).softmax(-1)[0]
26print(ckpt["class_names"][int(probs.argmax())], float(probs.max()))