timm documentation

Feature Extraction

Hugging Face's logo
Join the Hugging Face community

and get access to the augmented documentation experience

to get started

Feature Extraction

timm의 모든 모델은 분류를 제외한 다른 작업에서 모델을 통해 다양한 유형의 특징을 추출하는 일관된 메커니즘을 제공합니다.

마지막에서 두 번째 레이어 특징(분류기 이전 특징)

마지막 모델 레이어 바로 앞 레이어의 특징은 모델 구조를 수정하지 않고도 여러 방법으로 얻을 수 있습니다(원하시면 구조 수정도 가능합니다). 먼저 풀링된 특징인지 풀링되지 않은 특징인지 결정해야 합니다.

풀링되지 않은

풀링되지 않은 특징을 얻는 방법은 세 가지가 있습니다. 최종 풀링되지 않은 특징은 때때로 마지막 숨겨진 상태(last hidden state)라고도 불립니다. timm에서는 이는 최종 정규화 레이어까지 포함하며(예: ViT 스타일 모델), 풀링/클래스 토큰 선택 및 최종 풀링 후 레이어는 포함하지 않습니다.

네트워크를 수정하지 않고도, 일반적인 model(input) 대신 모든 모델에서 model.forward_features(input)를 호출할 수 있습니다. 이렇게 하면 네트워크의 헤드 분류기 및 글로벌 풀링을 우회합니다.

네트워크를 명시적으로 수정하여 풀링되지 않은 특징을 반환하도록 하려면, 분류기와 풀링 없이 모델을 생성하거나 나중에 이를 제거할 수 있습니다. 두 가지 방법 모두 네트워크에서 분류기와 관련된 매개변수를 제거합니다.

forward_features()

>>> import torch
>>> import timm
>>> m = timm.create_model('xception41', pretrained=True)
>>> o = m(torch.randn(2, 3, 299, 299))
>>> print(f'Original shape: {o.shape}')
>>> o = m.forward_features(torch.randn(2, 3, 299, 299))
>>> print(f'Unpooled shape: {o.shape}')

출력:

Original shape: torch.Size([2, 1000])
Unpooled shape: torch.Size([2, 2048, 10, 10])

클래시파이어와 풀링 없이 생성

>>> import torch
>>> import timm
>>> m = timm.create_model('resnet50', pretrained=True, num_classes=0, global_pool='')
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Unpooled shape: {o.shape}')

출력:

Unpooled shape: torch.Size([2, 2048, 7, 7])

나중에 제거

>>> import torch
>>> import timm
>>> m = timm.create_model('densenet121', pretrained=True)
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Original shape: {o.shape}')
>>> m.reset_classifier(0, '')
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Unpooled shape: {o.shape}')

출력:

Original shape: torch.Size([2, 1000])
Unpooled shape: torch.Size([2, 1024, 7, 7])

풀링되지 않은 출력을 분류기에 체이닝

마지막 hidden state는 forward_head() 함수를 사용하여 모델의 head에 다시 전달할 수 있습니다.

>>> model = timm.create_model('vit_medium_patch16_reg1_gap_256', pretrained=True)
>>> output = model.forward_features(torch.randn(2,3,256,256))
>>> print('Unpooled output shape:', output.shape)
>>> classified = model.forward_head(output)
>>> print('Classification output shape:', classified.shape)

출력:

Unpooled output shape: torch.Size([2, 257, 512])
Classification output shape: torch.Size([2, 1000])

풀링

네트워크를 수정하여 풀링된 특징을 반환하도록 하려면 forward_features()를 사용하고 결과를 직접 풀링/평탄화하거나, 위에서와 같이 네트워크를 수정하되 풀링을 그대로 유지할 수 있습니다.

클래시파이어 없이 생성

>>> import torch
>>> import timm
>>> m = timm.create_model('resnet50', pretrained=True, num_classes=0)
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Pooled shape: {o.shape}')

출력:

Pooled shape: torch.Size([2, 2048])

나중에 제거

>>> import torch
>>> import timm
>>> m = timm.create_model('ese_vovnet19b_dw', pretrained=True)
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Original shape: {o.shape}')
>>> m.reset_classifier(0)
>>> o = m(torch.randn(2, 3, 224, 224))
>>> print(f'Pooled shape: {o.shape}')

출력:

Original shape: torch.Size([2, 1000])
Pooled shape: torch.Size([2, 1024])

다중 스케일 특징 맵(Feature Pyramid)

객체 감지, 분할, 키포인트 및 다양한 밀집 픽셀 작업은 백본 네트워크의 여러 스케일에서 특징 맵에 접근할 수 있어야 합니다. 이는 일반적으로 원래의 분류 네트워크를 수정하여 수행합니다. 각 네트워크의 구조가 상당히 다르기 때문에, 특정 객체 감지 또는 분할 라이브러리에서 소수의 백본만 지원하는 경우가 흔합니다.

timm는 포함된 모든 모델을 선택된 레벨의 feature map을 출력하는 feature backbone으로 생성할 수 있도록 일관된 인터페이스를 제공합니다.

features_only=True 인수를 create_model 호출에 추가하여 feature backbone을 생성할 수 있습니다. 기본적으로 feature 계층 구조를 가진 대부분의 모델은 32배 축소까지 최대 5개의 feature를 출력합니다. 그러나 모델에 따라 다르며, 일부 모델은 계층 수준이 적고, ViT와 같은 일부 모델은 계층 구조가 없는 feature map의 수가 더 많으며 기본적으로 마지막 3개를 출력합니다. out_indices 인수를 create_model에 전달하여 원하는 feature를 지정할 수 있습니다.

피처 맵 추출 모델 만들기

>>> import torch
>>> import timm
>>> m = timm.create_model('resnest26d', features_only=True, pretrained=True)
>>> o = m(torch.randn(2, 3, 224, 224))
>>> for x in o:
...     print(x.shape)

출력:

torch.Size([2, 64, 112, 112])
torch.Size([2, 256, 56, 56])
torch.Size([2, 512, 28, 28])
torch.Size([2, 1024, 14, 14])
torch.Size([2, 2048, 7, 7])

기능 정보 조회

feature backbone이 생성된 후에는, 정적 설정이나 하드코딩된 상수 없이 하류 헤드에 채널 또는 해상도 축소 정보를 제공할 수 있도록 쿼리할 수 있습니다. .feature_info 속성은 feature 추출 지점에 대한 정보를 캡슐화하는 클래스입니다.

>>> import torch
>>> import timm
>>> m = timm.create_model('regnety_032', features_only=True, pretrained=True)
>>> print(f'Feature channels: {m.feature_info.channels()}')
>>> o = m(torch.randn(2, 3, 224, 224))
>>> for x in o:
...     print(x.shape)

출력:

Feature channels: [32, 72, 216, 576, 1512]
torch.Size([2, 32, 112, 112])
torch.Size([2, 72, 56, 56])
torch.Size([2, 216, 28, 28])
torch.Size([2, 576, 14, 14])
torch.Size([2, 1512, 7, 7])

…

출력 특징에 영향을 미치는 추가 생성 인수가 두 가지 있습니다.

  • out_indices는 출력할 인덱스를 선택합니다
  • output_stride는 네트워크의 특징 출력 스트라이드를 제한합니다(참고로 분류 모드에서도 작동합니다).

출력 인덱스 선택

out_indices 인수는 모든 모델에서 지원되지만, 모든 모델이 동일한 인덱스-피처 스트라이드 매핑을 갖지는 않습니다. 코드를 확인하거나 feature_info를 확인하여 비교해 보세요. out 인덱스는 일반적으로 C(i+1)th 피처 레벨(2^(i+1) 감소)에 해당합니다. 대부분의 convnet 모델에서 인덱스 0은 스트라이드 2 피처를, 인덱스 4는 스트라이드 32 피처를 나타냅니다. 많은 ViT 또는 ViT-Conv 하이브리드 모델에서는 동일한 모양의 피처 맵이 여러 개이거나, 계층적 피처 맵과 비계층적 피처 맵의 조합이 있을 수 있습니다. 피처의 수, 해당 채널 수 및 감소 레벨을 확인하려면 feature_info 속성을 살펴보는 것이 가장 좋습니다.

out_indices는 음수 인덱싱을 지원하여 마지막,倒数번째 등 특정 feature map을 쉽게 가져올 수 있습니다. out_indices=(-2,)를 사용하면 모든 모델에서倒数번째 feature map을 반환합니다.

Output stride (feature map dilation)

output_stride는 레이어를 dilated convolution을 사용하도록 변환하여 구현됩니다. 이 과정은 항상 간단하지 않으며, 일부 네트워크는 output_stride=32만 지원합니다.

>>> import torch
>>> import timm
>>> m = timm.create_model('ecaresnet101d', features_only=True, output_stride=8, out_indices=(2, 4), pretrained=True)
>>> print(f'Feature channels: {m.feature_info.channels()}')
>>> print(f'Feature reduction: {m.feature_info.reduction()}')
>>> o = m(torch.randn(2, 3, 320, 320))
>>> for x in o:
...     print(x.shape)

출력:

Feature channels: [512, 2048]
Feature reduction: [8, 8]
torch.Size([2, 512, 40, 40])
torch.Size([2, 2048, 40, 40])

유연한 중간 특징 맵 추출

features_only를 모델 팩토리와 함께 사용하는 것 외에도, 모든 모델은 중간 특징 맵과 마지막 숨겨진 상태(헤드에 연결할 수 있음)를 모두 추출하는 유연한 메커니즘을 제공하는 forward_intermediates() 메서드를 지원합니다. 또한 이 메서드는 일부 모델의 경우 클래스 토큰이나 distill 접두사 토큰을 반환하는 등 모델별 특정 기능을 지원합니다.

forward_intermediates 함수와 함께, 모델에서 헤드, 최종 정규화, 그리고 필요하지 않은 후행 블록/스테이지를 포함하여 레이어를 제거할 수 있는 prune_intermediate_layers 함수가 제공됩니다.

indices 인수는 반환할 특징을 선택하거나 제거할 레이어를 선택하기 위해 forward_intermediates()와 prune_intermediate_layers() 모두에 사용됩니다. features_only API의 out_indices와 마찬가지로, indices는 모델에 따라 다르며 반환될 중간 결과를 선택합니다.

ViT와 같은 비계층적 블록 기반 모델에서는 인덱스가 블록에 대응하며, 계층적 단계를 가진 모델에서는 일반적으로 stem + 각 계층적 단계의 출력에 대응합니다. 양수(시작 위치 기준)와 음수(끝 위치 기준) 인덱싱 모두 작동하며, None을 사용하면 모든 중간 결과를 반환합니다.

prune_intermediate_layers() 호출은 인덱스 변수를 반환합니다. 모델이 축소될 때 음수 인덱스는 절대(양수) 인덱스로 변환되어야 하기 때문입니다.

model = timm.create_model('vit_medium_patch16_reg1_gap_256', pretrained=True)
output, intermediates = model.forward_intermediates(torch.randn(2,3,256,256))
for i, o in enumerate(intermediates):
    print(f'Feat index: {i}, shape: {o.shape}')
Feat index: 0, shape: torch.Size([2, 512, 16, 16])
Feat index: 1, shape: torch.Size([2, 512, 16, 16])
Feat index: 2, shape: torch.Size([2, 512, 16, 16])
Feat index: 3, shape: torch.Size([2, 512, 16, 16])
Feat index: 4, shape: torch.Size([2, 512, 16, 16])
Feat index: 5, shape: torch.Size([2, 512, 16, 16])
Feat index: 6, shape: torch.Size([2, 512, 16, 16])
Feat index: 7, shape: torch.Size([2, 512, 16, 16])
Feat index: 8, shape: torch.Size([2, 512, 16, 16])
Feat index: 9, shape: torch.Size([2, 512, 16, 16])
Feat index: 10, shape: torch.Size([2, 512, 16, 16])
Feat index: 11, shape: torch.Size([2, 512, 16, 16])
model = timm.create_model('vit_medium_patch16_reg1_gap_256', pretrained=True)
print('Original params:', sum([p.numel() for p in model.parameters()]))

indices = model.prune_intermediate_layers(indices=(-2,), prune_head=True, prune_norm=True)  # prune head, norm, last block
print('Pruned params:', sum([p.numel() for p in model.parameters()]))

intermediates = model.forward_intermediates(torch.randn(2,3,256,256), indices=indices, intermediates_only=True)  # return penultimate intermediate
for o in intermediates:    
    print(f'Feat shape: {o.shape}')
Original params: 38880232
Pruned params: 35212800
Feat shape: torch.Size([2, 512, 16, 16])
Update on GitHub