Neural Style Transfer


In [100]:
import time
import numpy as np
from scipy.misc import imsave
from scipy.optimize import fmin_l_bfgs_b
from keras.preprocessing.image import load_img, img_to_array
from keras.applications import vgg19
from keras import backend as K

In [102]:
base_image_path = 'data/blue-moon-lake.jpg'
style_image_path = 'data/starry_night.jpg'
result_prefix = 'results'
iterations = 10
content_weight = 0.025
style_weight = 1.0
tv_weight = 1.0  # total variation

In [7]:
width, height = load_img(base_image_path).size
img_nrows = 400
img_ncols = int(width * img_nrows / height)

In [8]:
img_nrows, img_ncols


Out[8]:
(400, 640)

In [15]:
def preprocess_image(image_path):
    img = load_img(image_path, target_size=(img_nrows, img_ncols))
    img = img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = vgg19.preprocess_input(img)
    return img

def deprocess_image(x):
    x = x.reshape((img_nrows, img_ncols, 3))
    x[:, :, 0] += 103.939
    x[:, :, 1] += 116.779
    x[:, :, 2] += 123.68
    x = x[:, :, ::-1]
    x = np.clip(x, 0, 255).astype('uint8')
    return x

In [32]:
base_image = K.variable(preprocess_image(base_image_path))  # コンテンツ画像
style_image = K.variable(preprocess_image(style_image_path))  # スタイル画像
combination_image = K.placeholder((1, img_nrows, img_ncols, 3))  # 出力画像(コンテンツとスタイルの結合)
print(base_image)
print(style_image)
print(combination_image)


<tf.Variable 'Variable_9:0' shape=(1, 400, 640, 3) dtype=float32_ref>
<tf.Variable 'Variable_10:0' shape=(1, 400, 640, 3) dtype=float32_ref>
Tensor("Placeholder_3:0", shape=(1, 400, 640, 3), dtype=float32)

In [42]:
# コンテンツ画像、スタイル画像、出力画像を1つのテンソルにまとめる(3枚の画像のバッチになる)
# こうしておくと各画像を入れたときの層の出力がまとめて計算できる!
input_tensor = K.concatenate([base_image, style_image, combination_image], axis=0)
print(input_tensor)


Tensor("concat_3:0", shape=(3, 400, 640, 3), dtype=float32)

In [36]:
model = vgg19.VGG19(input_tensor=input_tensor, weights='imagenet', include_top=False)

In [37]:
model.summary()


_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_1 (InputLayer)         (None, None, None, 3)     0         
_________________________________________________________________
block1_conv1 (Conv2D)        (None, None, None, 64)    1792      
_________________________________________________________________
block1_conv2 (Conv2D)        (None, None, None, 64)    36928     
_________________________________________________________________
block1_pool (MaxPooling2D)   (None, None, None, 64)    0         
_________________________________________________________________
block2_conv1 (Conv2D)        (None, None, None, 128)   73856     
_________________________________________________________________
block2_conv2 (Conv2D)        (None, None, None, 128)   147584    
_________________________________________________________________
block2_pool (MaxPooling2D)   (None, None, None, 128)   0         
_________________________________________________________________
block3_conv1 (Conv2D)        (None, None, None, 256)   295168    
_________________________________________________________________
block3_conv2 (Conv2D)        (None, None, None, 256)   590080    
_________________________________________________________________
block3_conv3 (Conv2D)        (None, None, None, 256)   590080    
_________________________________________________________________
block3_conv4 (Conv2D)        (None, None, None, 256)   590080    
_________________________________________________________________
block3_pool (MaxPooling2D)   (None, None, None, 256)   0         
_________________________________________________________________
block4_conv1 (Conv2D)        (None, None, None, 512)   1180160   
_________________________________________________________________
block4_conv2 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block4_conv3 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block4_conv4 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block4_pool (MaxPooling2D)   (None, None, None, 512)   0         
_________________________________________________________________
block5_conv1 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block5_conv2 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block5_conv3 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block5_conv4 (Conv2D)        (None, None, None, 512)   2359808   
_________________________________________________________________
block5_pool (MaxPooling2D)   (None, None, None, 512)   0         
=================================================================
Total params: 20,024,384
Trainable params: 20,024,384
Non-trainable params: 0
_________________________________________________________________

In [55]:
# layer名 => layer出力の辞書を作成
outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])

In [56]:
outputs_dict


Out[56]:
{'block1_conv1': <tf.Tensor 'block1_conv1/Relu:0' shape=(3, 400, 640, 64) dtype=float32>,
 'block1_conv2': <tf.Tensor 'block1_conv2/Relu:0' shape=(3, 400, 640, 64) dtype=float32>,
 'block1_pool': <tf.Tensor 'block1_pool/MaxPool:0' shape=(3, 200, 320, 64) dtype=float32>,
 'block2_conv1': <tf.Tensor 'block2_conv1/Relu:0' shape=(3, 200, 320, 128) dtype=float32>,
 'block2_conv2': <tf.Tensor 'block2_conv2/Relu:0' shape=(3, 200, 320, 128) dtype=float32>,
 'block2_pool': <tf.Tensor 'block2_pool/MaxPool:0' shape=(3, 100, 160, 128) dtype=float32>,
 'block3_conv1': <tf.Tensor 'block3_conv1/Relu:0' shape=(3, 100, 160, 256) dtype=float32>,
 'block3_conv2': <tf.Tensor 'block3_conv2/Relu:0' shape=(3, 100, 160, 256) dtype=float32>,
 'block3_conv3': <tf.Tensor 'block3_conv3/Relu:0' shape=(3, 100, 160, 256) dtype=float32>,
 'block3_conv4': <tf.Tensor 'block3_conv4/Relu:0' shape=(3, 100, 160, 256) dtype=float32>,
 'block3_pool': <tf.Tensor 'block3_pool/MaxPool:0' shape=(3, 50, 80, 256) dtype=float32>,
 'block4_conv1': <tf.Tensor 'block4_conv1/Relu:0' shape=(3, 50, 80, 512) dtype=float32>,
 'block4_conv2': <tf.Tensor 'block4_conv2/Relu:0' shape=(3, 50, 80, 512) dtype=float32>,
 'block4_conv3': <tf.Tensor 'block4_conv3/Relu:0' shape=(3, 50, 80, 512) dtype=float32>,
 'block4_conv4': <tf.Tensor 'block4_conv4/Relu:0' shape=(3, 50, 80, 512) dtype=float32>,
 'block4_pool': <tf.Tensor 'block4_pool/MaxPool:0' shape=(3, 25, 40, 512) dtype=float32>,
 'block5_conv1': <tf.Tensor 'block5_conv1/Relu:0' shape=(3, 25, 40, 512) dtype=float32>,
 'block5_conv2': <tf.Tensor 'block5_conv2/Relu:0' shape=(3, 25, 40, 512) dtype=float32>,
 'block5_conv3': <tf.Tensor 'block5_conv3/Relu:0' shape=(3, 25, 40, 512) dtype=float32>,
 'block5_conv4': <tf.Tensor 'block5_conv4/Relu:0' shape=(3, 25, 40, 512) dtype=float32>,
 'block5_pool': <tf.Tensor 'block5_pool/MaxPool:0' shape=(3, 12, 20, 512) dtype=float32>,
 'input_1': <tf.Tensor 'concat_2:0' shape=(3, 400, 640, 3) dtype=float32>}

In [67]:
def gram_matrix(x):
    assert K.ndim(x) == 3
    features = K.batch_flatten(K.permute_dimensions(x, (2, 0, 1)))
    gram = K.dot(features, K.transpose(features))
    return gram

def content_loss(base, combination):
    return K.sum(K.square(combination - base))

def style_loss(style, combination):
    assert(K.ndim(style) == 3)
    assert(K.ndim(combination) == 3)
    S = gram_matrix(style)
    C = gram_matrix(combination)
    channels = 3
    size = img_nrows * img_ncols
    # 論文と同じ式
    return K.sum(K.square(S - C)) / (4.0 * (channels ** 2) * (size ** 2))

def total_variation_loss(x):
    assert K.ndim(x) == 4
    a = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, 1:, :img_ncols - 1, :])
    b = K.square(x[:, :img_nrows - 1, :img_ncols - 1, :] - x[:, :img_nrows - 1, 1:, :])
    return K.sum(K.pow(a + b, 1.25))

In [78]:
# lossの定義
loss = K.variable(0.)

# 途中のレイヤの出力を得る
# コンテンツ画像、スタイル画像、生成画像をまとめて計算できる
layer_features = outputs_dict['block5_conv2']
print(layer_features)

base_image_features = layer_features[0, :, :, :]
combination_features = layer_features[2, :, :, :]

# content loss
loss += content_weight * content_loss(base_image_features, combination_features)

# style loss
# style lossは複数のレイヤの出力を使って計算する
feature_layers = ['block1_conv1', 'block2_conv1', 'block3_conv1',
                  'block4_conv1', 'block5_conv1']
for layer_name in feature_layers:
    layer_features = outputs_dict[layer_name]
    print(layer_name, layer_features)
    style_features = layer_features[1, :, :, :]
    combination_features = layer_features[2, :, :, :]
    s_loss = style_loss(style_features, combination_features)
    loss += (style_weight / len(feature_layers)) * s_loss

# total variation loss
# 生成画像を滑らかにする
loss += tv_weight * total_variation_loss(combination_image)

print(loss)


Tensor("block5_conv2/Relu:0", shape=(3, 25, 40, 512), dtype=float32)
block1_conv1 Tensor("block1_conv1/Relu:0", shape=(3, 400, 640, 64), dtype=float32)
block2_conv1 Tensor("block2_conv1/Relu:0", shape=(3, 200, 320, 128), dtype=float32)
block3_conv1 Tensor("block3_conv1/Relu:0", shape=(3, 100, 160, 256), dtype=float32)
block4_conv1 Tensor("block4_conv1/Relu:0", shape=(3, 50, 80, 512), dtype=float32)
block5_conv1 Tensor("block5_conv1/Relu:0", shape=(3, 25, 40, 512), dtype=float32)
Tensor("add_42:0", shape=(), dtype=float32)

In [79]:
# lossの生成イメージに対する勾配を得る
grads = K.gradients(loss, combination_image)

In [89]:
outputs = [loss]
outputs += grads

In [91]:
outputs  # lossシンボルとgradsシンボルのリスト


Out[91]:
[<tf.Tensor 'add_42:0' shape=() dtype=float32>,
 <tf.Tensor 'gradients_1/AddN_16:0' shape=(1, 400, 640, 3) dtype=float32>]

In [95]:
# ノイズ画像(生成画像)を入力して、lossとgradsを返す関数
f_outputs = K.function([combination_image], outputs)
print(f_outputs)


<keras.backend.tensorflow_backend.Function object at 0x12e216828>

In [109]:
def eval_loss_and_grads(x):
    # xはflat化されているので画像に戻す
    x = x.reshape((1, img_nrows, img_ncols, 3))
    outs = f_outputs([x])
#     print("###", outs[0], outs[1].shape)
    loss_value = outs[0]
    grad_values = outs[1].flatten().astype('float64')
    return loss_value, grad_values

In [110]:
class Evaluator(object):
    
    def __init__(self):
        self.loss_value = None
        self.grads_values = None
    
    def loss(self, x):
        assert self.loss_value is None
        # lossとgradはまとめて計算されるのでloss()を呼び出したときに両方計算しておく
        loss_value, grad_values = eval_loss_and_grads(x)
        self.loss_value = loss_value
        self.grad_values = grad_values
        return self.loss_value
    
    def grads(self, x):
        # grads()はloss()のあとに呼ばれるのですでにloss()で計算済みのgradを返す
        assert self.loss_value is not None
        grad_values = np.copy(self.grad_values)
        self.loss_value = None
        self.grad_values = None
        return grad_values

evaluator = Evaluator()

In [111]:
# xは更新対象の生成イメージ
# 生成画像の初期値はノイズ画像ではなくてコンテンツ画像か?
# TODO: ノイズ画像に変えたらどうなる?
x = preprocess_image(base_image_path)

for i in range(iterations):
    print('Start of iteration', i)
    start_time = time.time()
    
    # lossが最小化する値、xが入力、fprimeが勾配
    x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),
                                     fprime=evaluator.grads, maxfun=20)
    print('Current loss value:', min_val)
    
    # 生成画像を保存
    img = deprocess_image(x.copy())
    fname = result_prefix + '_at_iteration_%d.png' % i
    imsave(fname, img)
    end_time = time.time()
    print('Image saved as', fname)
    print('Iteration %d completed in %ds' % (i, end_time - start_time))


Start of iteration 0
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
<ipython-input-111-fa09e2b78eea> in <module>()
     10     # lossが最小化する値、xが入力、fprimeが勾配
     11     x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(),
---> 12                                      fprime=evaluator.grads, maxfun=20)
     13     print('Current loss value:', min_val)
     14 

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py in fmin_l_bfgs_b(func, x0, fprime, args, approx_grad, bounds, m, factr, pgtol, epsilon, iprint, maxfun, maxiter, disp, callback, maxls)
    191 
    192     res = _minimize_lbfgsb(fun, x0, args=args, jac=jac, bounds=bounds,
--> 193                            **opts)
    194     d = {'grad': res['jac'],
    195          'task': res['message'],

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py in _minimize_lbfgsb(fun, x0, args, jac, bounds, disp, maxcor, ftol, gtol, eps, maxfun, maxiter, iprint, callback, maxls, **unknown_options)
    326             # until the completion of the current minimization iteration.
    327             # Overwrite f and g:
--> 328             f, g = func_and_grad(x)
    329         elif task_str.startswith(b'NEW_X'):
    330             # new iteration

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/scipy/optimize/lbfgsb.py in func_and_grad(x)
    276     else:
    277         def func_and_grad(x):
--> 278             f = fun(x, *args)
    279             g = jac(x, *args)
    280             return f, g

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/scipy/optimize/optimize.py in function_wrapper(*wrapper_args)
    290     def function_wrapper(*wrapper_args):
    291         ncalls[0] += 1
--> 292         return function(*(wrapper_args + args))
    293 
    294     return ncalls, function_wrapper

<ipython-input-110-0b8cadfacebf> in loss(self, x)
      8         assert self.loss_value is None
      9         # lossとgradはまとめて計算されるのでloss()を呼び出したときに両方計算しておく
---> 10         loss_value, grad_values = eval_loss_and_grads(x)
     11         self.loss_value = loss_value
     12         self.grad_values = grad_values

<ipython-input-109-48bf307ea177> in eval_loss_and_grads(x)
      2     # xはflat化されているので画像に戻す
      3     x = x.reshape((1, img_nrows, img_ncols, 3))
----> 4     outs = f_outputs([x])
      5 #     print("###", outs[0], outs[1].shape)
      6     loss_value = outs[0]

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/keras/backend/tensorflow_backend.py in __call__(self, inputs)
   2266         updated = session.run(self.outputs + [self.updates_op],
   2267                               feed_dict=feed_dict,
-> 2268                               **self.session_kwargs)
   2269         return updated[:len(self.outputs)]
   2270 

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/tensorflow/python/client/session.py in run(self, fetches, feed_dict, options, run_metadata)
    787     try:
    788       result = self._run(None, fetches, feed_dict, options_ptr,
--> 789                          run_metadata_ptr)
    790       if run_metadata:
    791         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
    995     if final_fetches or final_targets:
    996       results = self._do_run(handle, final_targets, final_fetches,
--> 997                              feed_dict_string, options, run_metadata)
    998     else:
    999       results = []

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
   1130     if handle is None:
   1131       return self._do_call(_run_fn, self._session, feed_dict, fetch_list,
-> 1132                            target_list, options, run_metadata)
   1133     else:
   1134       return self._do_call(_prun_fn, self._session, handle, feed_dict,

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/tensorflow/python/client/session.py in _do_call(self, fn, *args)
   1137   def _do_call(self, fn, *args):
   1138     try:
-> 1139       return fn(*args)
   1140     except errors.OpError as e:
   1141       message = compat.as_text(e.message)

/Users/koichiro.mori/.pyenv/versions/anaconda3-4.2.0/lib/python3.5/site-packages/tensorflow/python/client/session.py in _run_fn(session, feed_dict, fetch_list, target_list, options, run_metadata)
   1119         return tf_session.TF_Run(session, options,
   1120                                  feed_dict, fetch_list, target_list,
-> 1121                                  status, run_metadata)
   1122 
   1123     def _prun_fn(session, handle, feed_dict, fetch_list):

KeyboardInterrupt: 

In [ ]: