Views
No views yet

1from timm.layers.helpers import to_2tuple
2import timm
3import torch.nn as nn
4
5class ConvStem(nn.Module):
6 """Custom Patch Embed Layer.
7
8 Adapted from https://github.com/Xiyue-Wang/TransPath/blob/main/ctran.py#L6-L44
9 """
10
11 def __init__(self, img_size=224, patch_size=4, in_chans=3, embed_dim=768, norm_layer=None, **kwargs):
12 super().__init__()
13
14 # Check input constraints
15 assert patch_size == 4, "Patch size must be 4"
16 assert embed_dim % 8 == 0, "Embedding dimension must be a multiple of 8"
17
18 img_size = to_2tuple(img_size)
19 patch_size = to_2tuple(patch_size)
20
21 self.img_size = img_size
22 self.patch_size = patch_size
23 self.grid_size = (img_size[0] // patch_size[0], img_size[1] // patch_size[1])
24 self.num_patches = self.grid_size[0] * self.grid_size[1]
25
26 # Create stem network
27 stem = []
28 input_dim, output_dim = 3, embed_dim // 8
29 for l in range(2):
30 stem.append(nn.Conv2d(input_dim, output_dim, kernel_size=3, stride=2, padding=1, bias=False))
31 stem.append(nn.BatchNorm2d(output_dim))
32 stem.append(nn.ReLU(inplace=True))
33 input_dim = output_dim
34 output_dim *= 2
35 stem.append(nn.Conv2d(input_dim, embed_dim, kernel_size=1))
36 self.proj = nn.Sequential(*stem)
37
38 # Apply normalization layer (if provided)
39 self.norm = norm_layer(embed_dim) if norm_layer else nn.Identity()
40
41 def forward(self, x):
42 B, C, H, W = x.shape
43
44 # Check input image size
45 assert H == self.img_size[0] and W == self.img_size[1], \
46 f"Input image size ({H}*{W}) doesn't match model ({self.img_size[0]}*{self.img_size[1]})."
47
48 x = self.proj(x)
49 x = x.permute(0, 2, 3, 1) # BCHW -> BHWC
50 x = self.norm(x)
51 return x1from urllib.request import urlopen
2from PIL import Image
3import timm
4
5# get example histology image
6img = Image.open(
7 urlopen(
8 "https://github.com/owkin/HistoSSLscaling/raw/main/assets/example.tif"
9 )
10)
11
12# load model from the hub
13model = timm.create_model(
14 model_name="hf-hub:1aurent/swin_tiny_patch4_window7_224.CTransPath",
15 embed_layer=ConvStem, # defined above
16 pretrained=True,
17).eval()
18
19# get model specific transforms (normalization, resize)
20data_config = timm.data.resolve_model_data_config(model)
21transforms = timm.data.create_transform(**data_config, is_training=False)
22
23data = transforms(img).unsqueeze(0) # input is (batch_size, num_channels, img_size, img_size) shaped tensor
24output = model(data) # output is (batch_size, num_features) shaped tensor1@article{WANG2022102559,
2 title = {Transformer-based unsupervised contrastive learning for histopathological image classification},
3 journal = {Medical Image Analysis},
4 volume = {81},
5 pages = {102559},
6 year = {2022},
7 issn = {1361-8415},
8 doi = {https://doi.org/10.1016/j.media.2022.102559},
9 url = {https://www.sciencedirect.com/science/article/pii/S1361841522002043},
10 author = {Xiyue Wang and Sen Yang and Jun Zhang and Minghui Wang and Jing Zhang and Wei Yang and Junzhou Huang and Xiao Han},
11 keywords = {Histopathology, Transformer, Self-supervised learning, Feature extraction},
12 abstract = {A large-scale and well-annotated dataset is a key factor for the success of deep learning in medical image analysis. However, assembling such large annotations is very challenging, especially for histopathological images with unique characteristics (e.g., gigapixel image size, multiple cancer types, and wide staining variations). To alleviate this issue, self-supervised learning (SSL) could be a promising solution that relies only on unlabeled data to generate informative representations and generalizes well to various downstream tasks even with limited annotations. In this work, we propose a novel SSL strategy called semantically-relevant contrastive learning (SRCL), which compares relevance between instances to mine more positive pairs. Compared to the two views from an instance in traditional contrastive learning, our SRCL aligns multiple positive instances with similar visual concepts, which increases the diversity of positives and then results in more informative representations. We employ a hybrid model (CTransPath) as the backbone, which is designed by integrating a convolutional neural network (CNN) and a multi-scale Swin Transformer architecture. The CTransPath is pretrained on massively unlabeled histopathological images that could serve as a collaborative local–global feature extractor to learn universal feature representations more suitable for tasks in the histopathology image domain. The effectiveness of our SRCL-pretrained CTransPath is investigated on five types of downstream tasks (patch retrieval, patch classification, weakly-supervised whole-slide image classification, mitosis detection, and colorectal adenocarcinoma gland segmentation), covering nine public datasets. The results show that our SRCL-based visual representations not only achieve state-of-the-art performance in each dataset, but are also more robust and transferable than other SSL methods and ImageNet pretraining (both supervised and self-supervised methods). Our code and pretrained model are available at https://github.com/Xiyue-Wang/TransPath.}
13}