Изменения

Перейти к: навигация, поиск

Neural Style Transfer

78 байт добавлено, 05:05, 18 апреля 2019
Пример кода на Python
'''Content Loss'''
'''class ''' ContentLoss(nn.Module):
'''def ''' __init__(self, target,):
super(ContentLoss, self).__init__()
<font color="green"># we 'detach' the target content from the tree used</font>
self.target = target.detach()
'''def ''' forward(self, input):
self.loss = F.mse_loss(input, self.target)
return input
'''Style Loss'''
'''def ''' gram_matrix(input):
a, b, c, d = input.size() # a=batch size(=1)
<font color="green"># b=number of feature maps</font>
return G.div(a * b * c * d)
'''class ''' StyleLoss(nn.Module):
'''def ''' __init__(self, target_feature):
super(StyleLoss, self).__init__()
self.target = gram_matrix(target_feature).detach()
'''def ''' forward(self, input):
G = gram_matrix(input)
self.loss = F.mse_loss(G, self.target)
<font color="green"># create a module to normalize input image so we can easily put it in a</font>
<font color="green"># nn.Sequential</font>
'''class ''' Normalization(nn.Module): '''def ''' __init__(self, mean, std):
super(Normalization, self).__init__()
<font color="green"># .view the mean and std to make them [C x 1 x 1] so that they can</font>
self.std = torch.tensor(std).view(-1, 1, 1)
'''def ''' forward(self, img):
<font color="green"># normalize img</font>
return (img - self.mean) / self.std
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
'''def ''' get_style_model_and_losses(cnn, normalization_mean, normalization_std,
style_img, content_img,
content_layers=content_layers_default,
'''Gradient Descent'''
'''def ''' get_input_optimizer(input_img):
<font color="green"># this line to show that input is a parameter that requires a gradient</font>
optimizer = optim.LBFGS([input_img.requires_grad_()])
'''Run algorithm'''
'''def ''' run_style_transfer(cnn, normalization_mean, normalization_std,
content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1):
Анонимный участник

Навигация