timm documentation
빠른 시작
빠른 시작
이 빠른 시작은 코드를 바로 다루고 timm를 모델 학습 워크플로에 통합하는 방법을 예시로 보고 싶은 개발자를 위한 것입니다.
먼저 timm을 설치해야 합니다. 설치에 대한 자세한 내용은 설치를 참고하세요.
pip install timm
Load a Pretrained Model
사전 학습된 모델은 create_model()을 사용하여 로드할 수 있습니다.
여기서는 사전 학습된 mobilenetv3_large_100 모델을 로드합니다.
>>> import timm
>>> m = timm.create_model('mobilenetv3_large_100', pretrained=True)
>>> m.eval()Note: The returned PyTorch model is set to train mode by default, so you must call .eval() on it if you plan to use it for inference.
사전 학습된 가중치가 있는 모델 나열
timm에 패키징된 모델을 나열하려면 list_models()를 사용할 수 있습니다. pretrained=True를 지정하면 이 함수는 사전 학습된 가중치가 사용 가능한 모델 이름만 반환합니다.
>>> import timm
>>> from pprint import pprint
>>> model_names = timm.list_models(pretrained=True)
>>> pprint(model_names)
[
'adv_inception_v3',
'cspdarknet53',
'cspresnext50',
'densenet121',
'densenet161',
'densenet169',
'densenet201',
'densenetblur121d',
'dla34',
'dla46_c',
]이름에 특정 패턴이 포함된 모델을 나열할 수도 있습니다.
>>> import timm
>>> from pprint import pprint
>>> model_names = timm.list_models('*resne*t*')
>>> pprint(model_names)
[
'cspresnet50',
'cspresnet50d',
'cspresnet50w',
'cspresnext50',
...
]사전 학습된 모델 미세 조정
…
>>> model = timm.create_model('mobilenetv3_large_100', pretrained=True, num_classes=NUM_FINETUNE_CLASSES)자체 데이터셋으로 fine-tuning을 하려면 PyTorch 학습 루프를 작성하거나 timm의 training script를 데이터셋에 맞게 수정해야 합니다.
입력 채널이 다른 경우, in_chans를 모델의 대상 채널 수로 설정하십시오. 사전 학습된 구성은 소스 가중치를 설명해야 합니다. 채널 변환 및 현재 구성을 가진 적응된 모델의 저장에 대해서는 모델 적응 및 내보내기를 참조하십시오.
Pretrained Model을 사용하여 Feature Extraction 수행
model.forward_features(input)을 호출하여 네트워크를 수정하지 않고도 model(input) 대신 임의의 모델에 대해 헤드 분류기 및 네트워크의 전역 풀링을 우회할 수 있습니다.
timm를 활용한 특징 추출에 대한 더 자세한 가이드는 Feature Extraction을 참고하세요.
>>> import timm
>>> import torch
>>> x = torch.randn(1, 3, 224, 224)
>>> model = timm.create_model('mobilenetv3_large_100', pretrained=True)
>>> features = model.forward_features(x)
>>> print(features.shape)
torch.Size([1, 960, 7, 7])이미지 증강
모델에 유효한 입력으로 이미지를 변환하려면, 모델이 기대하는 input_size를 지정하여 timm.data.create_transform()를 사용할 수 있습니다.
…
>>> timm.data.create_transform((3, 224, 224))
Compose(
Resize(size=256, interpolation=bilinear, max_size=None, antialias=True)
CenterCrop(size=(224, 224))
MaybeToTensor()
Normalize(mean=tensor([0.4850, 0.4560, 0.4060]), std=tensor([0.2290, 0.2240, 0.2250]))
)Pretrained models에는 학습 시 모델에 입력된 이미지에 적용되던 특정 transforms가 있습니다. 이미지에 잘못된 transform을 적용하면 모델이 무엇을 보고 있는지 이해하지 못합니다!
주어진 사전 학습 모델에 어떤 변환이 사용되었는지 확인하려면 pretrained_cfg를 살펴보는 것부터 시작할 수 있습니다.
>>> model.pretrained_cfg
{'url': 'https://github.com/rwightman/pytorch-image-models/releases/download/v0.1-weights/mobilenetv3_large_100_ra-f55367f5.pth',
'hf_hub_id': 'timm/mobilenetv3_large_100.ra_in1k',
'architecture': 'mobilenetv3_large_100',
'tag': 'ra_in1k',
'custom_load': False,
'input_size': (3, 224, 224),
'fixed_input_size': False,
'interpolation': 'bicubic',
'crop_pct': 0.875,
'crop_mode': 'center',
'mean': (0.485, 0.456, 0.406),
'std': (0.229, 0.224, 0.225),
'num_classes': 1000,
'pool_size': (7, 7),
'first_conv': 'conv_stem',
'classifier': 'classifier',
'license': 'apache-2.0'}이후 timm.data.resolve_model_data_config()를 사용하여 데이터 관련 구성만 해결할 수 있습니다.
>>> timm.data.resolve_model_data_config(model)
{'input_size': (3, 224, 224),
'interpolation': 'bicubic',
'mean': (0.485, 0.456, 0.406),
'std': (0.229, 0.224, 0.225),
'crop_pct': 0.875,
'crop_mode': 'center'}이 데이터 구성을 timm.data.create_transform()에 전달하여 모델에 연결된 변환을 초기화할 수 있습니다.
>>> data_cfg = timm.data.resolve_model_data_config(model)
>>> transform = timm.data.create_transform(**data_cfg)
>>> transform
Compose(
Resize(size=256, interpolation=bicubic, max_size=None, antialias=True)
CenterCrop(size=(224, 224))
MaybeToTensor()
Normalize(mean=tensor([0.4850, 0.4560, 0.4060]), std=tensor([0.2290, 0.2240, 0.2250]))
)Note: Here, the pretrained model's config happens to be the same as the generic config we made earlier. This is not always the case. So, it's safer to use the data config to create the transform as we did here instead of using the generic transform.
추론을 위한 사전 학습 모델 사용
여기서 우리는 위 섹션들을 조합하고 사전 학습된 모델을 추론에 사용할 것입니다.
먼저 추론을 수행할 이미지가 필요합니다. 여기서는 웹에서 잎사귀 사진을 로드합니다:
>>> import requests
>>> from PIL import Image
>>> from io import BytesIO
>>> url = 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/timm/cat.jpg'
>>> image = Image.open(requests.get(url, stream=True).raw)
>>> image…
이제 모델을 변환과 함께 다시 생성합니다. 이번에는 모델을 평가 모드로 설정하는 것을 확인합니다.
>>> model = timm.create_model('mobilenetv3_large_100', pretrained=True).eval()
>>> transform = timm.data.create_transform(
**timm.data.resolve_model_data_config(model)
)transform에 이미지를 전달하여 모델을 위한 이 이미지를 준비할 수 있습니다.
>>> image_tensor = transform(image)
>>> image_tensor.shape
torch.Size([3, 224, 224])이제 해당 이미지를 모델에 전달하여 예측 결과를 얻을 수 있습니다. 모델이 배치 차원을 기대하므로 이 경우 unsqueeze(0)를 사용합니다.
>>> output = model(image_tensor.unsqueeze(0))
>>> output.shape
torch.Size([1, 1000])예측 확률을 얻으려면 출력에 softmax를 적용합니다. 그러면 (num_classes,) 모양의 텐서가 생성됩니다.
>>> probabilities = torch.nn.functional.softmax(output[0], dim=0)
>>> probabilities.shape
torch.Size([1000])이제 torch.topk를 사용하여 상위 5개의 예측 클래스 인덱스와 값을 찾습니다.
>>> values, indices = torch.topk(probabilities, 5)
>>> indices
tensor([281, 282, 285, 673, 670])top index에 해당하는 imagenet 라벨을 확인하면 모델이 예측한 내용을 볼 수 있습니다…
>>> IMAGENET_1k_URL = 'https://storage.googleapis.com/bit_models/ilsvrc2012_wordnet_lemmas.txt'
>>> IMAGENET_1k_LABELS = requests.get(IMAGENET_1k_URL).text.strip().split('\n')
>>> [{'label': IMAGENET_1k_LABELS[idx], 'value': val.item()} for val, idx in zip(values, indices)]
[{'label': 'tabby, tabby_cat', 'value': 0.5101025700569153},
{'label': 'tiger_cat', 'value': 0.22490699589252472},
{'label': 'Egyptian_cat', 'value': 0.1835290789604187},
{'label': 'mouse, computer_mouse', 'value': 0.006752475164830685},
{'label': 'motor_scooter, scooter', 'value': 0.004942195490002632}]