注意
here下载完整的示例代码
使用 PyTorch 进行 Neural Transfer¶
作者:Alexis Jacq
简介|
本教程介绍如何实现由Leon A. Gatys、Alexander S. Ecker 和 Matthias Bethge 开发的 Neural-Style 算法。 Neural-Style 或 Neural-Transfer 允许你拍摄一张图像,并以一个新的艺术风格再现它。 该算法接受三张图像,一张输入图像、一张内容图像和一张样式图像,并将输入更改为类似于内容图像的内容和样式图像的艺术风格。
基本原则|
原理很简单:我们定义两个距离,一个用于内容 (\(D_C\)),一个用于样式 (\(D_S\))。 \(D_C\) 测量两个图像之间的内容差异,而 \(D_S\) 测量两个图像之间风格的不同程度。 然后,我们获取第三个图像作为输入并转换它,以最小化其与内容图像的内容距离和风格图像的风格距离。 现在,我们可以导入必要的软件包并开始 neural transfer。
导入包并选择设备|
下面是实现神经转移所需的包的列表。
torch
、torch.nn
、numpy
(使用 PyTorch 的神经网络必不可少的软件包)torch.optim
(高效的梯度下降)PIL
、PIL.Image
、matplotlib.pyplot
(加载并显示图像)torchvision.transforms
(将 PIL 图像转换为张量)torchvision.models
(训练或加预训练模型)copy
(用于深层复制模型;系统软件包)
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from PIL import Image
import matplotlib.pyplot as plt
import torchvision.transforms as transforms
import torchvision.models as models
import copy
接下来,我们需要选择在哪个设备上运行网络,并导入内容和样式图像。 在大图像上运行神经传输算法需要更长的时间,在 GPU 上运行时速度会更快。 我们可以使用torch.cuda.is_available()
来检测是否有可用的 GPU。
接下来,我们将torch.device
设置为在整个教程中使用。 同时.to(device)
方法用于将张量或模型移动到所需的设备。
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
加载图像|
现在,我们将导入风格图像和内容图像。 原始 PIL 图像的值介于 0 和 255 之间,但当转换为 torch 张量时,它们的值将转换为介于 0 和 1 之间。 图像还需要调整大小,以具有相同的尺寸。 需要注意的一个重要细节是,来自割炬库的神经网络经过训练,张数值从 0 到 1 不等。 如果尝试向网络提供 0 到 255 张量图像,则激活的要素映射将无法感知预期的内容和样式。 但是,Caffe 库中的预训练网络经过 0 到 255 张条图像的训练。
注意
这里是下载运行教程所需的图像的链接:picasso.jpg 和 dancing.jpg。
下载这两个图像,并将它们添加到当前工作目录下名为images
的目录中。
# desired size of the output image
imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu
loader = transforms.Compose([
transforms.Resize(imsize), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
def image_loader(image_name):
图像 = Image.open(image_name)
# fake batch dimension required to fit network's input dimensions
图像 = loader(image).unsqueeze(0)
return image.to(device, torch.float)
style_img = image_loader("./data/images/neural-style/picasso.jpg")
content_img = image_loader("./data/images/neural-style/dancing.jpg")
assert style_img.size() == content_img.size(), \
"we need to import style and content images of the same size"
现在,让我们创建一个函数,通过将图像的副本重新转换为 PIL 格式并使用plt.imshow
显示副本来显示图像。 我们将尝试显示内容和样式图像,以确保它们被正确导入。
unloader = transforms.ToPILImage() # reconvert into PIL image
plt.ion()
def imshow(tensor, title=None):
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
image = image.squeeze(0) # remove the fake batch dimension
image = unloader(image)
plt.imshow(image)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
plt.figure()
imshow(style_img, title='Style Image')
plt.figure()
imshow(content_img, title='Content Image')
损失函数¶
内容损失¶
内容丢失是表示单个图层的内容距离的加权版本的函数。 The function takes the feature
maps \(F_{XL}\) of a layer \(L\) in a network processing input \(X\) and returns the
weighted content distance \(w_{CL}.D_C^L(X,C)\) between the image \(X\) and the
content image \(C\). 内容图像([(F_[CL]) )的要素映射必须由函数知道,以便计算内容距离。 我们将此函数实现为一个割炬模块,其构造函数以[(F_[CL])作为输入。 距离[(]F_{XL} - F_{CL}{2})是两组要素映射之间的均方误差,可以使用 nn 计算nn.MSELoss
.
我们将在用于计算内容距离的卷积层之后直接添加此内容丢失模块。 这样,每次向网络馈送输入图像时,内容损耗将在所需的图层上计算,并且由于自动渐变,将计算所有梯度。 现在,为了使内容丢失图层透明,我们必须定义一个forward
方法,计算内容丢失,然后返回图层的输入。 计算的损失将保存为模块的参数。
class ContentLoss(nn.Module):
def __init__(self, target,):
super(ContentLoss, self).__init__()
# we 'detach' the target content from the tree used
# to dynamically compute the gradient: this is a stated value,
# not a variable. Otherwise the forward method of the criterion
# will throw an error.
self.target = target.detach()
def forward(self, input):
self.loss = F.mse_loss(input, self.target)
return input
注意
重要细节:虽然这个模块被命名为ContentLoss
,但它不是一个真正的PyTorchLOSS函数。 如果要将内容丢失定义为 PyTorch LOSS 函数,必须创建 PyTorch 自动分级函数,以在backward
方法中手动重新计算/实现渐变。
风格损失¶
样式丢失模块的实现与内容丢失模块类似。 它将作为网络中的透明图层,用于计算该图层的样式丢失。 为了计算样式损耗,我们需要计算克矩阵[(G_[XL])。 克矩阵是将给定矩阵乘以其转置矩阵的结果。 在此应用程序中,给定矩阵是图层的要素映射的重形版本[(F_[XL])。 \(F_{XL})被重新塑造为形\((帽子\F_XL_),一个\(K_)x[(N])矩阵,其中[(K])是图层[(L])处的要素映射数,而 "[(N])是任何矢量化要素映射的长度 [(F_[XL]k)。 例如,[(帽子]F_{XL})的第一行对应于第一个矢量化要素映射[(F_{XL}{1})。
最后,克矩阵必须通过将每个元素除以矩阵中的元素总数来规范化。 此规范化是为了抵消以下事实:具有较大\(n})维度的[(f_XL])矩阵在 Gram 矩阵中生成较大的值。 这些较大的值将导致第一个图层(在池层之前)在渐变下降期间产生更大的影响。 样式特征往往位于网络的更深层,因此此规范化步骤至关重要。
def gram_matrix(input):
a, b, c, d = input.size() # a=batch size(=1)
# b=number of feature maps
# (c,d)=dimensions of a f. map (N=c*d)
features = input.view(a * b, c * d) # resise F_XL into \hat F_XL
G = torch.mm(features, features.t()) # compute the gram product
# we 'normalize' the values of the gram matrix
# by dividing by the number of element in each feature maps.
return G.div(a * b * c * d)
现在,样式丢失模块看起来几乎与内容丢失模块完全一样。 样式距离也使用[(G_[XL])和[(G_[SL])之间的平均平方误差计算。
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)
return input
导入模型|
现在我们需要导入一个预先训练的神经网络。 我们将使用 19 层 VGG 网络,就像本文中使用的网络一样。
PyTorch 的 VGG 实现是一个模块,分为两个子Sequential
模块:features
(包含卷积和池层)和classifier
(包含完全连接的图层)。 我们将使用features
模块,因为我们需要各个卷积图层的输出来测量内容和样式丢失。 某些层在训练过程中的行为与评估不同,因此必须使用.eval()
网络设置为评估模式。
cnn = models.vgg19(pretrained=True).features.to(device).eval()
此外,VGG 网络在图像上接受培训,每个通道均值[0.485,0.456,0.406] 和 std=0.229、0.224、0.225]。 在将映像发送到网络之前,我们将使用它们对其进行规范化。
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
# create a module to normalize input image so we can easily put it in a
# nn.Sequential
class Normalization(nn.Module):
def __init__(self, mean, std):
super(Normalization, self).__init__()
# .view the mean and std to make them [C x 1 x 1] so that they can
# directly work with image Tensor of shape [B x C x H x W].
# B is batch size. C is number of channels. H is height and W is width.
self.mean = torch.tensor(mean).view(-1, 1, 1)
self.std = torch.tensor(std).view(-1, 1, 1)
def forward(self, img):
# normalize img
return (img - self.mean) / self.std
Sequential
模块包含子模块的有序列表。 例如vgg19.features
包含按正确深度顺序对齐的序列(Conv2d、ReLU、MaxPool2d、Conv2d、ReLU...)。 我们需要在它们检测到的卷积层后立即添加内容丢失和样式丢失图层。 为此,我们必须创建一个新的Sequential
模块,该模块正确插入了内容丢失和样式丢失模块。
# desired depth layers to compute style/content losses :
content_layers_default = ['conv_4']
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,
style_layers=style_layers_default):
cnn = copy.deepcopy(cnn)
# normalization module
normalization = Normalization(normalization_mean, normalization_std).to(device)
# just in order to have an iterable access to or list of content/syle
# losses
content_losses = []
style_losses = []
# assuming that cnn is a nn.Sequential, so we make a new nn.Sequential
# to put in modules that are supposed to be activated sequentially
model = nn.Sequential(normalization)
i = 0 # increment every time we see a conv
for layer in cnn.children():
if isinstance(layer, nn.Conv2d):
i += 1
name = 'conv_{}'.format(i)
elif isinstance(layer, nn.ReLU):
name = 'relu_{}'.format(i)
# The in-place version doesn't play very nicely with the ContentLoss
# and StyleLoss we insert below. So we replace with out-of-place
# ones here.
layer = nn.ReLU(inplace=False)
elif isinstance(layer, nn.MaxPool2d):
name = 'pool_{}'.format(i)
elif isinstance(layer, nn.BatchNorm2d):
name = 'bn_{}'.format(i)
else:
raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
model.add_module(name, layer)
if name in content_layers:
# add content loss:
target = model(content_img).detach()
content_loss = ContentLoss(target)
model.add_module("content_loss_{}".format(i), content_loss)
content_losses.append(content_loss)
if name in style_layers:
# add style loss:
target_feature = model(style_img).detach()
style_loss = StyleLoss(target_feature)
model.add_module("style_loss_{}".format(i), style_loss)
style_losses.append(style_loss)
# now we trim off the layers after the last content and style losses
for i in range(len(model) - 1, -1, -1):
if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
break
model = model[:(i + 1)]
return model, style_losses, content_losses
接下来,我们选择输入图像。 您可以使用内容图像的副本或白噪声。
input_img = content_img.clone()
# if you want to use white noise instead uncomment the below line:
# input_img = torch.randn(content_img.data.size(), device=device)
# add the original input image to the figure:
plt.figure()
imshow(input_img, title='Input Image')
梯度下降¶
正如该算法的作者莱昂·加茨(LeonGatys)在这里建议的那样,我们将使用L-BFGS算法来运行梯度下降。 与培训网络不同,我们希望训练输入图像,以尽量减少内容/样式损失。 我们将创建一个 PyTorch L-BFGS 优化器optim.LBFGS
并将我们的图像传递给它作为张数进行优化。
def get_input_optimizer(input_img):
# this line to show that input is a parameter that requires a gradient
optimizer = optim.LBFGS([input_img.requires_grad_()])
return optimizer
最后,我们必须定义一个执行神经转移的函数。 对于网络的每次迭代,都会馈送更新的输入并计算新的损耗。 我们将运行每个损耗模块的backward
方法,以动态地计算它们的梯度。 优化器需要一个"闭合"函数,该函数重新评估 modul 并返回损失。
我们还有最后一个约束需要解决。 网络可能会尝试使用超过图像 0 到 1 张量范围的值来优化输入。 每次运行网络时,我们可以通过将输入值校正为 0 到 1 来解决此问题。
def run_style_transfer(cnn, normalization_mean, normalization_std,
content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1):
"""Run the style transfer."""
print('Building the style transfer model..')
model, style_losses, content_losses = get_style_model_and_losses(cnn,
normalization_mean, normalization_std, style_img, content_img)
optimizer = get_input_optimizer(input_img)
print('Optimizing..')
run = [0]
while run[0] <= num_steps:
def closure():
# correct the values of updated input image
input_img.data.clamp_(0, 1)
optimizer.zero_grad()
model(input_img)
style_score = 0
content_score = 0
for sl in style_losses:
style_score += sl.loss
for cl in content_losses:
content_score += cl.loss
style_score *= style_weight
content_score *= content_weight
loss = style_score + content_score
loss.backward()
run[0] += 1
if run[0] % 50 == 0:
print("run {}:".format(run))
print('Style Loss : {:4f} Content Loss: {:4f}'.format(
style_score.item(), content_score.item()))
print()
return style_score + content_score
optimizer.step(closure)
# a last correction...
input_img.data.clamp_(0, 1)
return input_img
最后,我们可以运行该算法。
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
content_img, style_img, input_img)
plt.figure()
imshow(output, title='Output Image')
# sphinx_gallery_thumbnail_number = 4
plt.ioff()
plt.show()
输出:
Building the style transfer model..
Optimizing..
run [50]:
Style Loss : 88.119675 Content Loss: 17.800974
run [100]:
Style Loss : 24.404888 Content Loss: 16.099791
run [150]:
Style Loss : 9.770405 Content Loss: 14.170073
run [200]:
Style Loss : 5.173123 Content Loss: 12.407548
run [250]:
Style Loss : 3.333839 Content Loss: 10.971821
run [300]:
Style Loss : 2.607504 Content Loss: 9.926169
脚本总运行时间: (37分8.325秒)