Views
No views yet
1import types
2import torch
3from torchvision.models import ResNet
4from torchvision.models import resnet50
5
6def _forward_impl(self, x: torch.Tensor) -> torch.Tensor:
7 x = self.conv1(x)
8 x = self.bn1(x)
9 x = self.relu(x)
10 x = self.maxpool(x)
11
12 x = self.layer1(x)
13 x = self.layer2(x)
14 x = self.layer3(x)
15
16 x = self.avgpool(x)
17 x = x.view(x.size(0), -1)
18
19 return x
20
21model = resnet50(weights=None)
22del model.layer4, model.fc
23
24model._forward_impl = types.MethodType(_forward_impl, model)
25
26state_dict = torch.hub.load_state_dict_from_url(
27 "https://download.pytorch.org/models/resnet50-19c8e357.pth"
28)
29# Remove truncated keys.
30state_dict = {k: v for k, v in state_dict.items() if not k.startswith("layer4.") and not k.startswith("fc.")}
31
32model.load_state_dict(state_dict, strict=True)
33model.eval()1from urllib.request import urlopen
2from PIL import Image
3import torch
4
5img = Image.open(urlopen(
6 'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/beignets-task-guide.png'
7))
8
9# See above for how to load the model. Or load a TorchScript version of the model,
10# which can be loaded automatically with
11# model = torch.jit.load("torchscript_model.bin")
12model = model.eval()
13
14transform = transforms.Compose([
15 # Depending on the pipeline, this may be 256x256 or a different value.
16 transforms.Resize((224, 224)),
17 transforms.ToTensor(),
18 transforms.Normalize(
19 mean=(0.485, 0.456, 0.406),
20 std=(0.229, 0.224, 0.225)),
21])
22
23with torch.no_grad():
24 output = model(transform(img).unsqueeze(0)) # unsqueeze single image into batch of 1
25output.shape # 1x10241@article{He2015,
2 author = {Kaiming He and Xiangyu Zhang and Shaoqing Ren and Jian Sun},
3 title = {Deep Residual Learning for Image Recognition},
4 journal = {arXiv preprint arXiv:1512.03385},
5 year = {2015}
6}
7@article{lu2021data,
8 title={Data-efficient and weakly supervised computational pathology on whole-slide images},
9 author={Lu, Ming Y and Williamson, Drew FK and Chen, Tiffany Y and Chen, Richard J and Barbieri, Matteo and Mahmood, Faisal},
10 journal={Nature Biomedical Engineering},
11 volume={5},
12 number={6},
13 pages={555--570},
14 year={2021},
15 publisher={Nature Publishing Group}
16}