r"""Creates a criterion that measures Learned Perceptual Image Patch Similarity (LPIPS). Arguments: net_type (str): the network type to compare the features: 'alex' | 'squeeze' | 'vgg'. Default: 'alex'. version (str): the version of LPIPS. Default: 0
| 6 | |
| 7 | |
| 8 | class LPIPS(nn.Module): |
| 9 | r"""Creates a criterion that measures |
| 10 | Learned Perceptual Image Patch Similarity (LPIPS). |
| 11 | |
| 12 | Arguments: |
| 13 | net_type (str): the network type to compare the features: |
| 14 | 'alex' | 'squeeze' | 'vgg'. Default: 'alex'. |
| 15 | version (str): the version of LPIPS. Default: 0.1. |
| 16 | """ |
| 17 | def __init__(self, net_type: str = 'alex', version: str = '0.1'): |
| 18 | |
| 19 | assert version in ['0.1'], 'v0.1 is only supported now' |
| 20 | |
| 21 | super(LPIPS, self).__init__() |
| 22 | |
| 23 | # pretrained network |
| 24 | self.net = get_network(net_type) |
| 25 | |
| 26 | # linear layers |
| 27 | self.lin = LinLayers(self.net.n_channels_list) |
| 28 | self.lin.load_state_dict(get_state_dict(net_type, version)) |
| 29 | |
| 30 | def forward(self, x: torch.Tensor, y: torch.Tensor): |
| 31 | feat_x, feat_y = self.net(x), self.net(y) |
| 32 | |
| 33 | diff = [(fx - fy) ** 2 for fx, fy in zip(feat_x, feat_y)] |
| 34 | res = [l(d).mean((2, 3), True) for d, l in zip(diff, self.lin)] |
| 35 | |
| 36 | return torch.sum(torch.cat(res, 0), 0, True) |