提交 8d9884e7 编写于 作者: W wizardforcel

2021-01-16 21:24:30

上级 41452a31
......@@ -39,7 +39,7 @@
以下是解决样式转换问题时要遵循的步骤的简要说明:
1. **馈入输入**:内容和样式图像都将馈入模型,并且它们必须具有相同的形状。 这里的常见做法是调整样式图像的大小,以使其与内容图像具有相同的形状。
2. **Loading the model**: Oxford's VGG created a model architecture that performs outstandingly well on style transfer problems, known as the VGG network. They also made the model's parameters available to anyone so that the training process of the model could be shortened or skipped (this is what a pretrained model is for).
2. **加载模型**:牛津大学的VGG创建了一个模型架构,该模型在样式转换问题上表现出色,被称为VGG网络。 他们还将模型的参数提供给任何人,以便可以缩短或跳过模型的训练过程(这就是预训练模型的目的)。
注意
......@@ -48,7 +48,7 @@
因此,可以使用 PyTorch 的**模型**子包加载预训练的模型,以执行样式转换任务,而无需训练大量图像的网络。
3. **确定层的功能**:鉴于手头有两项主要任务(识别图像的内容并区分另一幅图像的样式),不同的层将具有不同的功能来提取不同的特征。 对于样式图像,重点应该放在颜色和纹理上,对于内容图像,重点应该放在边缘和形状上。 在此步骤中,将不同的层分为不同的任务。
4. **Defining the optimization problem**: As with any other supervised problem, it is necessary to define a loss function, which will have the responsibility of measuring the difference between the output and inputs. Unlike other supervised problems, the task of style transfer requires you to define three different loss functions, all of which should be minimized during the training process. The three loss functions are explained here:
4. **定义优化问题**:与其他任何监督问题一样,有必要定义一个损失函数,该函数将负责测量输出和输入之间的差异。 与其他受监督的问题不同,样式转移的任务要求您定义三个不同的损失函数,在训练过程中应将所有这些损失最小化。 这里介绍了三种损失函数:
**内容损失**:这仅在考虑与内容相关的特征的情况下测量内容图像与输出之间的距离。
......@@ -127,7 +127,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
在本书的 [GitHub 存储库](https://packt.live/2yiR97z)中,您将能够找到在本章中用于不同练习和活动的不同图像。
1. Import all the packages that will be required to perform style transfer:
1. 导入执行样式转换所需的所有软件包:
```py
import numpy as np
......@@ -145,7 +145,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
device
```
2. Set the image size to be used for both images. Also, set the transformations to be performed over the images, which should include resizing the images, converting them into tensors, and normalizing them:
2. 设置用于两个图像的图像尺寸。 另外,设置要在图像上执行的转换,这应该包括调整图像的大小,将它们转换为张量以及对其进行规范化:
```py
imsize = 224
......@@ -162,7 +162,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
使用规范化图像训练 VGG 网络,其中每个通道的平均值分别为 0.485、0.456 和 0.406,标准差分别为 0.229、0.224 和 0.225。
3. Define a function that will receive the image path as input and use **PIL** to open the image. Next, it should apply the transformations to the image:
3. 定义一个函数,该函数将接收图像路径作为输入,并使用`PIL`打开图像。 接下来,应将转换应用于图像:
```py
def image_loader(image_name):
......@@ -171,7 +171,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
    return image
```
4. Call the function to load the content and style images. Use the dog image as the content image and the Matisse image as the style image, both of which are available in this book's GitHub repository:
4. 调用该函数以加载内容和样式图像。 将狗图像用作内容图像,将Matisse图像用作样式图像,这两者都可以在本书的GitHub存储库中找到:
```py
content_img = image_loader("images/dog.jpg")
......@@ -187,7 +187,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
前面的代码片段将保存图像的变量分配给 GPU,以便使用这些变量的所有操作都由 GPU 处理。
5. To display the images, convert them back into PIL images and revert the normalization process. Define these transformations in a variable:
5. 调用该函数以加载内容和样式图像。 将狗图像用作内容图像,将Matisse图像用作样式图像,这两者都可以在本书的GitHub存储库中找到:...
```py
unloader = transforms.Compose([\
......@@ -198,7 +198,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
           transforms.ToPILImage()])
```
6. Create a function that clones the tensor, squeezes it, and applies the transformations defined in the previous step to the tensor:
6. 创建一个函数来克隆张量,压缩张量,并将上一步中定义的转换应用于张量:
```py
def tensor2image(tensor):
......@@ -220,7 +220,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
前面的代码片段将图像分配回 CPU,以便我们可以绘制它们。
7. Call the function for both images and plot the results:
7. 调用两个图像的函数并绘制结果:
```py
plt.figure()
......@@ -260,7 +260,7 @@ transforms.Compose([transforms.Normalize((-0.5/0.25, \
如前所述,用于执行样式转换任务的架构是 19 层 VGG 网络的架构,也称为 VGG-19。 在`torchvision``model`子程序包下提​​供了预训练的模型。 在 PyTorch 中保存的模型分为两部分:
1. `vgg19.features`:这包括网络的所有卷积和池化层以及参数。 这些层负责从图像中提取特征。 有些层专门用于样式功能(例如颜色),而另一些层则专门用于内容功能(例如边缘)。
2. `vgg19.classifier`: This refers to the linear layers (also known as fully connected layers) that are located at the end of the network, including their parameters. These layers are the ones that perform the classification of the image into one of the label classes, for instance, recognizing the type of animal in an image.
2. `vgg19.classifier`:这是指位于网络末端的线性层(也称为完全连接层),包括其参数。 这些层是将图像分类为标签类别之一的层,例如,识别图像中的动物类型。
注意
......@@ -286,7 +286,7 @@ for param in model.parameters():
使用与上一练习相同的笔记本,本练习旨在加载预先训练的模型,该模型将在后续练习中使用我们先前加载的图像执行样式转换任务。
1. 打开上一个练习中的笔记本。
2. Load the VGG-19 pre-trained model from PyTorch:
2. 从PyTorch加载VGG-19预训练模型:
```py
model = models.vgg19(pretrained=True).feature
......@@ -294,7 +294,7 @@ for param in model.parameters():
如前所述,选择模型的特征部分。 这将使您能够访问模型的所有卷积和池化层,这些层将用于在本章的后续练习中提取特征。
3. Perform a **for** loop through the parameters of the previously loaded model. Set each parameter so that it doesn't require gradients calculations:
3. 通过先前加载的模型的参数执行`for`循环。 设置每个参数,使其不需要进行梯度计算:
```py
for param in model.parameters():
......@@ -365,13 +365,13 @@ for index, layer in model._modules.items():
使用上一练习的网络架构和本章第一练习的图像,我们将创建几个函数,这些函数能够从输入图像中提取特征并为样式特征创建语法矩阵。
1. 打开上一个练习中的笔记本。
2. Print the architecture of the model we loaded in the previous exercise. This will help us identify the relevant layers so that we can perform the style transfer task:
2. 打印我们在上一个练习中加载的模型的体系结构。 这将帮助我们识别相关层,以便我们可以执行样式转换任务:
```py
print(model)
```
3. Create a dictionary for mapping the index of the relevant layers (keys) to a name (values). This will facilitate the process of calling relevant layers in the future:
3. 创建一个字典,用于将相关层的索引(键)映射到名称(值)。这将方便将来调用相关层的过程。
```py
relevant_layers = {'0': 'conv1_1', '5': 'conv2_1', '10': \
......@@ -381,7 +381,7 @@ for index, layer in model._modules.items():
要创建字典,我们使用上一步的输出,该输出显示网络中的每个层。 在那里,可以观察到第一堆叠的第一层标记为`0`,而第二堆叠的第一层标记为`5`,依此类推。
4. Create a function that will extract the relevant features (features extracted from the relevant layers only) from an input image. Name it **features_extractor** and make sure it takes the image, the model, and the dictionary we created previously as inputs:
4. 创建一个函数,从输入图像中提取相关特征(仅从相关图层中提取的特征)。将其命名为`features_extractor`,并确保它将图像、模型和我们之前创建的字典作为输入。
```py
def features_extractor(x, model, layers):
......@@ -395,7 +395,7 @@ for index, layer in model._modules.items():
输出应该是字典,键是层的名称,值是该层的输出要素。
5. Call the **features_extractor** function over the content and style images we loaded in the first exercise of this chapter:
5. 在我们在本章第一个练习中加载的内容和样式图片上调用`features_extractor`函数。
```py
content_features = features_extractor(content_img, model, \
......@@ -404,7 +404,7 @@ style_features = features_extractor(style_img, model, \
relevant_layers)
```
6. Perform the gram matrix calculation over the style features. Consider that the style features were obtained from different layers, which is why different gram matrices should be created, one for each layer's output:
6. 在风格特征上进行 Gram 矩阵计算。考虑到风格特征是从不同的层中获得的,这就是为什么要创建不同的克矩阵,每个层的输出都有一个。
```py
style_grams = {}
......@@ -418,7 +418,7 @@ style_features = features_extractor(style_img, model, \
对于每一层,都将获得样式特征矩阵的形状以对其进行向量化。 接下来,通过将向量化输出乘以其转置版本来创建 gram 矩阵。
7. Create an initial target image. This image will be compared against the content and style images later and be changed until the desired similarity is achieved:
7. 创建一个初始目标图像。该图像将在以后与内容和风格图像进行比较,并进行更改,直到达到所需的相似度。
```py
target_img = content_img.clone().requires_grad_(True)
......@@ -432,7 +432,7 @@ style_features = features_extractor(style_img, model, \
target_img = content_img.clone().requires_grad_(True).to(device)
```
8. Using the **tensor2image** function we created during the first exercise of this chapter, plot the target image, which should look the same as the content image:
8. 使用我们在本章第一个练习中创建的`tensor2image`函数,绘制目标图像,它看起来应该和内容图像一样。
```py
plt.figure()
......@@ -527,7 +527,7 @@ style_features = features_extractor(style_img, model, \
在 GPU 上运行此代码时,需要进行一些更改。 请访问本书的 GitHub 存储库以修改此代码的 GPU 版本。
1. 打开上一个练习中的笔记本。
2. Define a dictionary containing the weights for each of the layers in charge of extracting style features:
2. 定义一个字典,包含负责提取风格特征的每个层的权重。
```py
style_weights = {'conv1_1': 1., 'conv2_1': 0.8, 'conv3_1': 0.6, \
......@@ -536,14 +536,14 @@ style_features = features_extractor(style_img, model, \
确保使用与上一个练习中的层相同的名称作为键。
3. Define the weights associated with the content and style losses:
3. 定义与内容和风格损失相关的权重。
```py
alpha = 1
beta = 1e5
```
4. Define the number of iteration steps, as well as the optimization algorithm. We can also set the number of iterations if we want to see a plot of the image that has been created at that point:
4. 定义迭代步数,以及优化算法。如果我们想看到当时已经创建的图像的图,也可以设置迭代次数。
```py
print_statement = 200
......@@ -559,7 +559,7 @@ style_features = features_extractor(style_img, model, \
为了使您理解每次迭代中目标图像发生的变化,可以进行几次迭代,但是建议您尝试更长的训练时间。
5. Define the **for** loop where all three loss functions will be calculated and the optimization process will be performed:
5. 定义`for`循环,在这个循环中,将计算所有三个损失函数,并执行优化过程。
```py
for i in range(1, iterations+1):
......@@ -597,7 +597,7 @@ style_features = features_extractor(style_img, model, \
        plt.show()
```
6. Plot both the content and target images to compare the results. This can be achieved by using the **tensor2image** function, which we created in the previous exercises, in order to convert the tensors into PIL images that can be printed using **matplotlib**:
6. 绘制内容和目标图像来比较结果。这可以通过使用`tensor2image`函数来实现,我们在之前的练习中创建了这个函数,以便将张量转换为可以使用`matplotlib`打印的PIL图像。
```py
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 10))
......@@ -642,7 +642,7 @@ style_features = features_extractor(style_img, model, \
7. 创建一个字典,将相关层(键)的索引映射到名称(值)。 然后,创建一个函数以提取相关层的特征图。 使用它们提取两个输入图像的特征。
8. 计算样式特征的克矩阵。 另外,创建初始目标图像。
9. 设置不同样式层的权重以及内容和样式损失的权重。
10. Run the model for 500 iterations. Define the Adam optimization algorithm before starting to train the model, using 0.001 as the learning rate.
10. 运行模型500次迭代。在开始训练模型之前,定义Adam优化算法,以0.001作为学习率。
注意
......@@ -650,7 +650,7 @@ style_features = features_extractor(style_img, model, \
本章中显示的结果是通过运行大约 5,000 次迭代而获得的,如果不使用 GPU,则将花费很长时间(在本书的 GitHub 存储库中也找到了使用 GPU 的活动的解决方案)。 但是,仅看到一些小的更改,就可以按照本活动的建议运行它几百次迭代就足够了(500)。
11. Plot the content, style, and target images to compare the results.
11. 绘制内容、风格、目标图片,比较结果。
5,000 次迭代后的输出应如下所示:
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册