This tutorial explains how to implement the Neural-Style algorithm
developed by Leon A. Gatys, Alexander S. Ecker and Matthias Bethge.
Neural-Style, or Neural-Transfer, allows you to take an image and
reproduce it with a new artistic style. The algorithm takes three images,
an input image, a content-image, and a style-image, and changes the input
to resemble the content of the content-image and the artistic style of the style-image.
Underlying Principle
The principle is simple: we define two distances, one for the content
(DC) and one for the style (DS). DC measures how different the content
is between two images while DS measures how different the style is
between two images. Then, we take a third image, the input, and
transform it to minimize both its content-distance with the
content-image and its style-distance with the style-image. Now we can
import the necessary packages and begin the neural transfer.
Importing Packages and Selecting a Device
Below is a list of the packages needed to implement the neural transfer.
torch, torch.nn, numpy (indispensables packages for
neural networks with PyTorch)
torch.optim (efficient gradient descents)
PIL, PIL.Image, matplotlib.pyplot (load and display
images)
torchvision.transforms (transform PIL images into tensors)
torchvision.models (train or load pretrained models)
Next, we need to choose which device to run the network on and import the
content and style images. Running the neural transfer algorithm on large
images takes longer and will go much faster when running on a GPU. We can
use torch.cuda.is_available() to detect if there is a GPU available.
Next, we set the torch.device for use throughout the tutorial. Also the .to(device)
method is used to move tensors or modules to a desired device.
Now we will import the style and content images. The original PIL images have values between 0 and 255, but when
transformed into torch tensors, their values are converted to be between
0 and 1. The images also need to be resized to have the same dimensions.
An important detail to note is that neural networks from the
torch library are trained with tensor values ranging from 0 to 1. If you
try to feed the networks with 0 to 255 tensor images, then the activated
feature maps will be unable to sense the intended content and style.
However, pretrained networks from the Caffe library are trained with 0
to 255 tensor images.
# desired size of the output imageimsize=512iftorch.cuda.is_available()else128# use small size if no GPUloader=transforms.Compose([transforms.Resize(imsize),# scale imported imagetransforms.ToTensor()])# transform it into a torch tensordefimage_loader(image_name):image=Image.open(image_name)# fake batch dimension required to fit network's input dimensionsimage=loader(image).unsqueeze(0)returnimage.to(device,torch.float)style_img=image_loader("./data/images/neural-style/picasso.jpg")content_img=image_loader("./data/images/neural-style/dancing.jpg")assertstyle_img.size()==content_img.size(), \
"we need to import style and content images of the same size"
Now, let’s create a function that displays an image by reconverting a
copy of it to PIL format and displaying the copy using
plt.imshow. We will try displaying the content and style images
to ensure they were imported correctly.
unloader=transforms.ToPILImage()# reconvert into PIL imageplt.ion()defimshow(tensor,title=None):image=tensor.cpu().clone
Loss Functions
Content Loss
The content loss is a function that represents a weighted version of the
content distance for an individual layer. The function takes the feature
maps FXL of a layer L in a network processing input X and returns the
weighted content distance wCL.DCL(X,C) between the image X and the
content image C. The feature maps of the content image(FCL) must be
known by the function in order to calculate the content distance. We
implement this function as a torch module with a constructor that takes
FCL as an input. The distance ∥FXL−FCL∥2 is the mean square error
between the two sets of feature maps, and can be computed using nn.MSELoss.
We will add this content loss module directly after the convolution
layer(s) that are being used to compute the content distance. This way
each time the network is fed an input image the content losses will be
computed at the desired layers and because of auto grad, all the
gradients will be computed. Now, in order to make the content loss layer
transparent we must define a forward method that computes the content
loss and then returns the layer’s input. The computed loss is saved as a
parameter of the module.
classContentLoss(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
Style Loss
The style loss module is implemented similarly to the content loss
module. It will act as a transparent layer in a
network that computes the style loss of that layer. In order to
calculate the style loss, we need to compute the gram matrix GXL. A gram
matrix is the result of multiplying a given matrix by its transposed
matrix. In this application the given matrix is a reshaped version of
the feature maps FXL of a layer L. is reshaped to form , a x
matrix, where is the number of feature maps at layer and is the
length of any vectorized feature map . For example, the first line
of corresponds to the first vectorized feature map .
Importing the Model
Now we need to import a pretrained neural network. We will use a 19
layer VGG network like the one used in the paper.
PyTorch’s implementation of VGG is a module divided into two child
Sequential modules: features (containing convolution and pooling layers),
and classifier (containing fully connected layers). We will use the
features module because we need the output of the individual
convolution layers to measure content and style loss. Some layers have
different behavior during training than evaluation, so we must set the
network to evaluation mode using .eval().
Additionally, VGG networks are trained on images with each channel
normalized by mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225].
We will use them to normalize the image before sending it into the network.
A Sequential module contains an ordered list of child modules. For
instance, vgg19.features contains a sequence (Conv2d, ReLU, MaxPool2d,
Conv2d, ReLU…) aligned in the right order of depth. We need to add our
content loss and style loss layers immediately after the convolution
layer they are detecting. To do this we must create a new Sequential
module that has content loss and style loss modules correctly inserted.
# 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']defget_style_model_and_losses(cnn,normalization_mean,normalization_std,
Next, we select the input image. You can use a copy of the content image
or white noise.
input_img=content_img.clone()# if you want to use white noise by using the following code:## .. code-block:: python## input_img = torch.randn(content_img.data.size())# add the original input image to the figure:plt.figure()imshow(input_img,title='Input Image')
Gradient Descent
As Leon Gatys, the author of the algorithm, suggested here, we will use
L-BFGS algorithm to run our gradient descent. Unlike training a network,
we want to train the input image in order to minimize the content/style
losses. We will create a PyTorch L-BFGS optimizer optim.LBFGS and pass
our image to it as the tensor to optimize.
defget_input_optimizer(input_img):# this line to show that input is a parameter that requires a gradientoptimizer=optim.LBFGS([input_img])returnoptimizer
Finally, we must define a function that performs the neural transfer. For
each iteration of the networks, it is fed an updated input and computes
new losses. We will run the backward methods of each loss module to
dynamically compute their gradients. The optimizer requires a “closure”
function, which reevaluates the module and returns the loss.
We still have one final constraint to address. The network may try to
optimize the input with values that exceed the 0 to 1 tensor range for
the image. We can address this by correcting the input values to be
between 0 to 1 each time the network is run.
Building the style transfer model../usr/local/lib/python3.12/dist-packages/torch/utils/_device.py:122:UserWarning:To copy construct from a tensor, it is recommended to use sourceTensor.detach().clone()or sourceTensor.detach().clone().requires_grad_(True rather than torchsourceTensor
Total running time of the script: (0 minutes 14.071 seconds)
Finally, the gram matrix must be normalized by dividing each element by
the total number of elements in the matrix. This normalization is to
counteract the fact that F^XL matrices with a large N dimension yield
larger values in the Gram matrix. These larger values will cause the
first layers (before pooling layers) to have a larger impact during the
gradient descent. Style features tend to be in the deeper layers of the
network so this normalization step is crucial.
defgram_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)# resize F_XL into \hat F_XLG=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.returnG.div(a*b*c*d)
Now the style loss module looks almost exactly like the content loss
module. The style distance is also computed using the mean square
error between GXL and GSL.