神經(jīng)風(fēng)格遷移是一種優(yōu)化技術(shù),用于將兩個圖像——一個內(nèi)容圖像和一個風(fēng)格參考圖像(如著名畫家的一個作品)——混合在一起,使輸出的圖像看起來像內(nèi)容圖像, 但是用了風(fēng)格參考圖像的風(fēng)格。
這是通過優(yōu)化輸出圖像以匹配內(nèi)容圖像的內(nèi)容統(tǒng)計數(shù)據(jù)和風(fēng)格參考圖像的風(fēng)格統(tǒng)計數(shù)據(jù)來實現(xiàn)的。 這些統(tǒng)計數(shù)據(jù)可以使用卷積網(wǎng)絡(luò)從圖像中提取。
例如,我們選取這張小狗的照片和 Wassily Kandinsky 的作品 7:


瓦西里·康丁斯基(Василий Кандинский,格里歷1866年12月16日-1944年12月13日),出生于俄羅斯的畫家和美術(shù)理論家。與彼?!っ傻吕锇埠婉R列維奇一起,康定斯基認為是抽象藝術(shù)的先驅(qū).
如果 Kandinsky 決定用這種風(fēng)格來專門描繪這只狗會是什么樣子?

import tensorflow as tf
import IPython.display as display
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['figure.figsize'] = (12,12)
mpl.rcParams['axes.grid'] = False
import numpy as np
import PIL.Image
import time
import functools
def tensor_to_image(tensor):
tensor = tensor*255
tensor = np.array(tensor, dtype=np.uint8)
if np.ndim(tensor)>3:
assert tensor.shape[0] == 1
tensor = tensor[0]
return PIL.Image.fromarray(tensor)
# 下載圖像并選擇風(fēng)格圖像和內(nèi)容圖像:
content_path = tf.keras.utils.get_file('YellowLabradorLooking_new.jpg', 'https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg')
# https://commons.wikimedia.org/wiki/File:Vassily_Kandinsky,_1913_-_Composition_7.jpg
style_path = tf.keras.utils.get_file('kandinsky5.jpg','https://storage.googleapis.com/download.tensorflow.org/example_images/Vassily_Kandinsky%2C_1913_-_Composition_7.jpg')
#定義一個加載圖像的函數(shù),并將其最大尺寸限制為 512 像素。
def load_img(path_to_img):
max_dim = 512
img = tf.io.read_file(path_to_img)
img = tf.image.decode_image(img, channels=3)
img = tf.image.convert_image_dtype(img, tf.float32)
shape = tf.cast(tf.shape(img)[:-1], tf.float32)
long_dim = max(shape)
scale = max_dim / long_dim
new_shape = tf.cast(shape * scale, tf.int32)
img = tf.image.resize(img, new_shape)
img = img[tf.newaxis, :]
return img
# 創(chuàng)建一個簡單的函數(shù)來顯示圖像:
def imshow(image, title=None):
if len(image.shape) > 3:
image = tf.squeeze(image, axis=0)
plt.imshow(image)
if title:
plt.title(title)
content_image = load_img(content_path)
style_image = load_img(style_path)
plt.subplot(1, 2, 1)
imshow(content_image, 'Content Image')
plt.subplot(1, 2, 2)
imshow(style_image, 'Style Image')
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/YellowLabradorLooking_new.jpg
90112/83281 [================================] - 0s 3us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/example_images/Vassily_Kandinsky%2C_1913_-_Composition_7.jpg
196608/195196 [==============================] - 0s 2us/step

# 本教程演示了原始的風(fēng)格遷移算法。其將圖像內(nèi)容優(yōu)化為特定風(fēng)格。在進入細節(jié)之前,讓我們看一下 TensorFlow Hub 模塊如何快速風(fēng)格遷移:
import tensorflow_hub as hub
hub_module = hub.load('https://hub.tensorflow.google.cn/google/magenta/arbitrary-image-stylization-v1-256/1')
stylized_image = hub_module(tf.constant(content_image), tf.constant(style_image))[0]
tensor_to_image(stylized_image)

使用模型的中間層來獲取圖像的內(nèi)容和風(fēng)格表示。 從網(wǎng)絡(luò)的輸入層開始,前幾個層的激勵響應(yīng)表示邊緣和紋理等低級 feature (特征)。 隨著層數(shù)加深,最后幾層代表更高級的 feature (特征)——實體的部分,如輪子或眼睛。 在此教程中,我們使用的是 VGG19 網(wǎng)絡(luò)結(jié)構(gòu),這是一個已經(jīng)預(yù)訓(xùn)練好的圖像分類網(wǎng)絡(luò)。 這些中間層是從圖像中定義內(nèi)容和風(fēng)格的表示所必需的。 對于一個輸入圖像,我們嘗試匹配這些中間層的相應(yīng)風(fēng)格和內(nèi)容目標的表示。
# 加載 VGG19 并在我們的圖像上測試它以確保正常運行:
x = tf.keras.applications.vgg19.preprocess_input(content_image*255)
x = tf.image.resize(x, (224, 224))
vgg = tf.keras.applications.VGG19(include_top=True, weights='imagenet')
prediction_probabilities = vgg(x)
prediction_probabilities.shape
predicted_top_5 = tf.keras.applications.vgg19.decode_predictions(prediction_probabilities.numpy())[0]
[(class_name, prob) for (number, class_name, prob) in predicted_top_5]
# 現(xiàn)在,加載沒有分類部分的 VGG19 ,并列出各層的名稱:
vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')
print()
for layer in vgg.layers:
print(layer.name)
# 從網(wǎng)絡(luò)中選擇中間層的輸出以表示圖像的風(fēng)格和內(nèi)容:
# 內(nèi)容層將提取出我們的 feature maps (特征圖)
content_layers = ['block5_conv2']
# 我們感興趣的風(fēng)格層
style_layers = ['block1_conv1',
'block2_conv1',
'block3_conv1',
'block4_conv1',
'block5_conv1']
num_content_layers = len(content_layers)
num_style_layers = len(style_layers)
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels.h5
574717952/574710816 [==============================] - 6509s 11us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/data/imagenet_class_index.json
40960/35363 [==================================] - 0s 4us/step
Downloading data from https://storage.googleapis.com/tensorflow/keras-applications/vgg19/vgg19_weights_tf_dim_ordering_tf_kernels_notop.h5
80142336/80134624 [==============================] - 3212s 40us/step
input_10
block1_conv1
block1_conv2
block1_pool
block2_conv1
block2_conv2
block2_pool
block3_conv1
block3_conv2
block3_conv3
block3_conv4
block3_pool
block4_conv1
block4_conv2
block4_conv3
block4_conv4
block4_pool
block5_conv1
block5_conv2
block5_conv3
block5_conv4
block5_pool
# 使用tf.keras.applications中的網(wǎng)絡(luò)可以讓我們非常方便的利用Keras的功能接口提取中間層的值。
# 在使用功能接口定義模型時,我們需要指定輸入和輸出:
# model = Model(inputs, outputs)
# 以下函數(shù)構(gòu)建了一個 VGG19 模型,該模型返回一個中間層輸出的列表:
def vgg_layers(layer_names):
# 加載我們的模型。 加載已經(jīng)在 imagenet 數(shù)據(jù)上預(yù)訓(xùn)練的 VGG
vgg = tf.keras.applications.VGG19(include_top=False, weights='imagenet')
vgg.trainable = False
outputs = [vgg.get_layer(name).output for name in layer_names]
model = tf.keras.Model([vgg.input], outputs)
return model
# 然后建立模型
style_extractor = vgg_layers(style_layers)
style_outputs = style_extractor(style_image*255)
#查看每層輸出的統(tǒng)計信息
for name, output in zip(style_layers, style_outputs):
print(name)
print(" shape: ", output.numpy().shape)
print(" min: ", output.numpy().min())
print(" max: ", output.numpy().max())
print(" mean: ", output.numpy().mean())
print()
# 圖像的內(nèi)容由中間 feature maps (特征圖)的值表示。
# 事實證明,圖像的風(fēng)格可以通過不同 feature maps (特征圖)上的平均值和相關(guān)性來描述。
# 通過在每個位置計算 feature (特征)向量的外積,并在所有位置對該外積進行平均,可以計算出包含此信息的 Gram 矩陣。
# 這可以使用tf.linalg.einsum函數(shù)來實現(xiàn):
def gram_matrix(input_tensor):
result = tf.linalg.einsum('bijc,bijd->bcd', input_tensor, input_tensor)
input_shape = tf.shape(input_tensor)
num_locations = tf.cast(input_shape[1]*input_shape[2], tf.float32)
return result/(num_locations)
# 構(gòu)建一個返回風(fēng)格和內(nèi)容張量的模型。
class StyleContentModel(tf.keras.models.Model):
def __init__(self, style_layers, content_layers):
super(StyleContentModel, self).__init__()
self.vgg = vgg_layers(style_layers + content_layers)
self.style_layers = style_layers
self.content_layers = content_layers
self.num_style_layers = len(style_layers)
self.vgg.trainable = False
def call(self, inputs):
"Expects float input in [0,1]"
inputs = inputs*255.0
preprocessed_input = tf.keras.applications.vgg19.preprocess_input(inputs)
outputs = self.vgg(preprocessed_input)
style_outputs, content_outputs = (outputs[:self.num_style_layers], outputs[self.num_style_layers:])
style_outputs = [gram_matrix(style_output) for style_output in style_outputs]
content_dict = {content_name:value for content_name, value in zip(self.content_layers, content_outputs)}
style_dict = {style_name:value for style_name, value in zip(self.style_layers, style_outputs)}
return {'content':content_dict, 'style':style_dict}
# 在圖像上調(diào)用此模型,可以返回 style_layers 的 gram 矩陣(風(fēng)格)和 content_layers 的內(nèi)容:
extractor = StyleContentModel(style_layers, content_layers)
results = extractor(tf.constant(content_image))
style_results = results['style']
print('Styles:')
for name, output in sorted(results['style'].items()):
print(" ", name)
print(" shape: ", output.numpy().shape)
print(" min: ", output.numpy().min())
print(" max: ", output.numpy().max())
print(" mean: ", output.numpy().mean())
print()
print("Contents:")
for name, output in sorted(results['content'].items()):
print(" ", name)
print(" shape: ", output.numpy().shape)
print(" min: ", output.numpy().min())
print(" max: ", output.numpy().max())
print(" mean: ", output.numpy().mean())
# 梯度下降
# 使用此風(fēng)格和內(nèi)容提取器,我們現(xiàn)在可以實現(xiàn)風(fēng)格傳輸算法。我們通過計算每個圖像的輸出和目標的均方誤差來做到這一點,然后取這些損失值的加權(quán)和。
# 設(shè)置風(fēng)格和內(nèi)容的目標值:
style_targets = extractor(style_image)['style']
content_targets = extractor(content_image)['content']
# 定義一個 tf.Variable 來表示要優(yōu)化的圖像。
# 為了快速實現(xiàn)這一點,使用內(nèi)容圖像對其進行初始化( tf.Variable 必須與內(nèi)容圖像的形狀相同)
image = tf.Variable(content_image)
# 由于這是一個浮點圖像,因此我們定義一個函數(shù)來保持像素值在 0 和 1 之間:
def clip_0_1(image):
return tf.clip_by_value(image, clip_value_min=0.0, clip_value_max=1.0)
# 創(chuàng)建一個 optimizer 。 本教程推薦 LBFGS,但 Adam 也可以正常工作:
opt = tf.optimizers.Adam(learning_rate=0.02, beta_1=0.99, epsilon=1e-1)
# 為了優(yōu)化它,我們使用兩個損失的加權(quán)組合來獲得總損失:
style_weight=1e-2
content_weight=1e4
def style_content_loss(outputs):
style_outputs = outputs['style']
content_outputs = outputs['content']
style_loss = tf.add_n([tf.reduce_mean((style_outputs[name]-style_targets[name])**2)
for name in style_outputs.keys()])
style_loss *= style_weight / num_style_layers
content_loss = tf.add_n([tf.reduce_mean((content_outputs[name]-content_targets[name])**2)
for name in content_outputs.keys()])
content_loss *= content_weight / num_content_layers
loss = style_loss + content_loss
return loss
# 使用 tf.GradientTape 來更新圖像。
@tf.function()
def train_step(image):
with tf.GradientTape() as tape:
outputs = extractor(image)
loss = style_content_loss(outputs)
grad = tape.gradient(loss, image)
opt.apply_gradients([(grad, image)])
image.assign(clip_0_1(image))
# 現(xiàn)在,我們運行幾個步來測試一下:
train_step(image)
train_step(image)
train_step(image)
tensor_to_image(image)
# 運行正常,我們來執(zhí)行一個更長的優(yōu)化:
import time
start = time.time()
epochs = 10
steps_per_epoch = 100
step = 0
for n in range(epochs):
for m in range(steps_per_epoch):
step += 1
train_step(image)
print(".", end='')
display.clear_output(wait=True)
display.display(tensor_to_image(image))
print("Train step: {}".format(step))
end = time.time()
print("Total time: {:.1f}".format(end-start))

Train step: 1000
Total time: 4710.0