一、定义
1、使用卷积神经网络,自动将一个图像中的风格应用在另一图像之上,即风格迁移;两张输入图像:一张是内容图像,另一张是风格图像。
2、训练一些样本使得样本在一些cnn的特征上跟样式图片很相近,在一些cnn的特征上跟内容图片很像,关键在于该怎么样定义内容是一样的,样式是一样的
3、方法:
(1)我们初始化合成图像,例如将其初始化为内容图像
(2)该合成图像是风格迁移过程中唯一需要更新的变量,即风格迁移所需迭代的模型参数
(3)选择一个预训练的卷积神经网络来抽取图像的特征,其中的模型参数在训练中无须更新(VGG系列对于抽取特征效果不错)

4、风格迁移常用的损失函数组成:
(1)内容损失使合成图像与内容图像在内容特征上接近;
(2)风格损失使合成图像与风格图像在风格特征上接近;
(3)全变分损失则有助于减少合成图像中的噪点。
5、样式就是通道里面的像素的统计信息和通道之间的统计信息。假设两张图片它的样式是一样的,那么他们卷积层的一些输出,他们通道之间的统计分布和通道里面统计分布是差不多匹配的;
6、样式损失是指匹配通道内的统计信息和通道之间的统计信息(可以理解为匹配一阶二阶三阶的统计信息,一阶可以是均值,二阶可以是协方差),把feature map里通道作为一维,然后将通道里面的像素拉成一个向量,然后做协方差矩阵,去计算一个多维度的随机变量的二阶信息去匹配分布。
二、代码
1、内容及样式读取
d2l.set_figsize()
#读取内容图片(风景照片)
content_img = d2l.Image.open('../img/rainier.jpg')
#读取样式图片(油画)
style_img = d2l.Image.open('../img/autumn-oak.jpg')
2、预处理与后处理
预处理函数preprocess对输入图像在RGB三个通道分别做标准化,并将结果变换成卷积神经网络接受的输入格式。 后处理函数postprocess则将输出图像中的像素值还原回标准化之前的值。
#将一张图片转化为可以训练的tensor
def preprocess(img, image_shape):
transforms = torchvision.transforms.Compose([
torchvision.transforms.Resize(image_shape),
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize(mean=rgb_mean, std=rgb_std)])
#对输入图像应用之前定义的变换序列,得到一个张量,并在0维度上添加一个新的维度(通道)
return transforms(img).unsqueeze(0)
#将一个训练好的tensor转化为图片
def postprocess(img):
img = img[0].to(rgb_std.device)
img = torch.clamp(img.permute(1, 2, 0) * rgb_std + rgb_mean, 0, 1)
return torchvision.transforms.ToPILImage()(img.permute(2, 0, 1))
3、抽取图像特征
#使用基于ImageNet数据集预训练的VGG-19模型来抽取图像特征
pretrained_net = torchvision.models.vgg19(pretrained=True)
#浅层是局部,越接近输出层越全局;样式既想要一些局部的信息,也想要一些全局的信息
style_layers, content_layers = [0, 5, 10, 19, 28], [25]
#要的是28层以内的层(为啥老师写的是(max(content_layers + style_layers))
net = nn.Sequential(*[pretrained_net.features[i] for i in
range(max(content_layers , style_layers) + 1)])
def extract_features(X, content_layers, style_layers):
contents = []
styles = []
for i in range(len(net)):
X = net[i](X)
if i in style_layers:
styles.append(X)
if i in content_layers:
contents.append(X)
return contents, styles
#对内容图像抽取内容特征
def get_contents(image_shape, device):
content_X = preprocess(content_img, image_shape).to(device)
contents_Y, _ = extract_features(content_X, content_layers, style_layers)
return content_X, contents_Y
#对风格图像抽取风格特征
def get_styles(image_shape, device):
style_X = preprocess(style_img, image_shape).to(device)
_, styles_Y = extract_features(style_X, content_layers, style_layers)
return style_X, styles_Y
4、定义损失函数
# 内容损失
def content_loss(Y_hat, Y):
# 我们从动态计算梯度的树中分离目标:
# 这是一个规定的值,而不是一个变量。
return torch.square(Y_hat - Y.detach()).mean()
#风格损失
def gram(X):
# X图像的特征,形状为(batch_size, num_channels, height, width);n特征图的元素总数除以通道数(高度和宽度的乘积)
num_channels, n = X.shape[1], X.numel() // X.shape[1]
#将特征图的每个通道展开成一个一维的向量
X = X.reshape((num_channels, n))
#通过计算特征图中所有通道对的内积,每个元素表示两个通道的相关性
return torch.matmul(X, X.T) / (num_channels * n)
def style_loss(Y_hat, gram_Y):
return torch.square(gram(Y_hat) - gram_Y.detach()).mean()
# 全变分损失
def tv_loss(Y_hat):
return 0.5 * (torch.abs(Y_hat[:, :, 1:, :] - Y_hat[:, :, :-1, :]).mean() +
torch.abs(Y_hat[:, :, :, 1:] - Y_hat[:, :, :, :-1]).mean())
#损失函数
content_weight, style_weight, tv_weight = 1, 1e3, 10
def compute_loss(X, contents_Y_hat, styles_Y_hat, contents_Y, styles_Y_gram):
# 分别计算内容损失、风格损失和全变分损失
contents_l = [content_loss(Y_hat, Y) * content_weight for Y_hat, Y in zip(
contents_Y_hat, contents_Y)]
styles_l = [style_loss(Y_hat, Y) * style_weight for Y_hat, Y in zip(
styles_Y_hat, styles_Y_gram)]
tv_l = tv_loss(X) * tv_weight
# 对所有损失求和
l = sum(10 * styles_l + contents_l + [tv_l])
return contents_l, styles_l, tv_l, l
5、初始化合成图像
将合成的图像视为模型参数。模型的前向传播只需返回模型参数即可
class SynthesizedImage(nn.Module):
def __init__(self, img_shape, **kwargs):
super(SynthesizedImage, self).__init__(**kwargs)
self.weight = nn.Parameter(torch.rand(*img_shape))
def forward(self):
return self.weight
创建了合成图像的模型实例,并将其初始化为图像X,风格图像在各个风格层的格拉姆矩阵styles_Y_gram将在训练前预先计算好。
def get_inits(X, device, lr, styles_Y):
#生成图像的起始状态就是 X 的值,这样训练快一点
gen_img = SynthesizedImage(X.shape).to(device)
gen_img.weight.data.copy_(X.data)
#Adam 优化器,用于优化生成图像的参数,目的是最小化损失函数,从而生成符合目标风格和内容的图像
trainer = torch.optim.Adam(gen_img.parameters(), lr=lr)
#对每张样式图像 Y 计算 Gram 矩阵,用于衡量风格特征
styles_Y_gram = [gram(Y) for Y in styles_Y]
return gen_img(), styles_Y_gram, trainer
6、训练模型
def train(X, contents_Y, styles_Y, device, lr, num_epochs, lr_decay_epoch):
X, styles_Y_gram, trainer = get_inits(X, device, lr, styles_Y)
scheduler = torch.optim.lr_scheduler.StepLR(trainer, lr_decay_epoch, 0.8)
animator = d2l.Animator(xlabel='epoch', ylabel='loss',
xlim=[10, num_epochs],
legend=['content', 'style', 'TV'],
ncols=2, figsize=(7, 2.5))
for epoch in range(num_epochs):
trainer.zero_grad()
contents_Y_hat, styles_Y_hat = extract_features(
X, content_layers, style_layers)
contents_l, styles_l, tv_l, l = compute_loss(
X, contents_Y_hat, styles_Y_hat, contents_Y, styles_Y_gram)
l.backward()
trainer.step()
scheduler.step()
if (epoch + 1) % 10 == 0:
animator.axes[1].imshow(postprocess(X))
animator.add(epoch + 1, [float(sum(contents_l)),
float(sum(styles_l)), float(tv_l)])
return X
device, image_shape = d2l.try_gpu(), (300, 450)
net = net.to(device)
content_X, contents_Y = get_contents(image_shape, device)
_, styles_Y = get_styles(image_shape, device)
output = train(content_X, contents_Y, styles_Y, device, 0.3, 500, 50)
三、总结
1、风格迁移常用的损失函数由3部分组成:
(1)内容损失使合成图像与内容图像在内容特征上接近;
(2)风格损失令合成图像与风格图像在风格特征上接近;
(3)全变分损失则有助于减少合成图像中的噪点。
2、我们可以通过预训练的卷积神经网络来抽取图像的特征,并通过最小化损失函数来不断更新合成图像来作为模型参数。
3、我们使用格拉姆矩阵表达风格层输出的风格。



















