PyTorch 1.3 Tutorials : 画像 : PyTorch を利用した画風変換 (翻訳/解説)
翻訳 : (株)クラスキャット セールスインフォメーション
作成日時 : 12/20/2019 (1.3.1)
* 本ページは、PyTorch 1.3 Tutorials の以下のページを翻訳した上で適宜、補足説明したものです:
- Image : Neural Transfer Using PyTorch
* サンプルコードの動作確認はしておりますが、必要な場合には適宜、追加改変しています。
* ご自由にリンクを張って頂いてかまいませんが、sales-info@classcat.com までご一報いただけると嬉しいです。

画像 : PyTorch を利用した画風変換
イントロダクション
このチュートリアルは Leon A. Gatys, Alexander S. Ecker と Matthias Bethge により開発された 画風変換アルゴリズム をどのように実装するか説明します。画風変換は画像を取りそれを新しい芸術的なスタイルで再生成することを可能にします。アルゴリズムは 3 つの画像を取ります、入力画像、コンテンツ画像そしてスタイル画像です、そして入力をコンテンツ画像のコンテンツ (内容) とスタイル画像の芸術的なスタイルに似るように変更します。

基本原理
原理は単純です : 2 つの距離を定義します、一つなコンテンツのため ($D_c$) そして一つはスタイルのため ($D_s$) です。$D_c$ は 2 つの画像間でコンテンツがどのくらい異なるかを測定し、その一方で $D_s$ は 2 つの画像間でスタイルがどのくらい異なるかを測定します。それから、3 番目の画像、入力を取りそれをコンテンツ画像とのコンテンツ距離とスタイル画像とのスタイル距離の両者を最小化するように変換します。今は必要なパッケージをインポートして画風変換を始めることができます。
パッケージをインポートしてデバイスを選択する
下は画風変換を実装するために必要なパッケージのリストです。
- torch, torch.nn, numpy (PyTorch によるニューラルネットワークのための必須パッケージ)
- torch.optim (効率的な勾配降下)
- PIL, PIL.Image, matplotlib.pyplot (画像をロードして表示する)
- torchvision.transforms (PIL 画像を tensor に変換します)
- torchvision.models (事前訓練されたモデルを訓練またはロードする)
- copy (モデルを deep コピーするため; システムパッケージ)
from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from PIL import Image import matplotlib.pyplot as plt import torchvision.transforms as transforms import torchvision.models as models import copy
次に、ネットワークを実行するデバイスを選択してコンテンツとスタイル画像をインポートする必要があります。巨大な画像上での画風変換アルゴリズムの実行はより長くかかり GPU 上で実行するとき遥かに高速に進みます。利用可能な GPU があるかを検出するために torch.cuda.is_available() を使用できます。次にチュートリアルを通して使用するための torch.device を設定します。また tensor かモジュールを望まれるデバイスに移動するために .to(device) メソッドが使用されます。
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
画像をロードする
今はスタイルとコンテンツ画像をインポートします。元の PIL 画像は 0 と 255 の間の値を持ちますが、torch tensor に変換されるとき、それらの値は 0 と 1 の間に変換されます。画像はまた同じ次元を持つようにリサイズされる必要があります。注意すべき重要な細部は torch ライブラリからのニューラルネットワークは 0 から 1 の範囲の tensor 値で訓練されていることです。ネットワークに 0 から 255 tensor 画像を供給しようとすれば、活性化された特徴マップは意図されたコンテンツとスタイルを感知できないでしょう。けれども、Caffe ライブラリからの事前訓練されたネットワークは 0 から 255 tensor 画像で訓練されています。
Note: チュートリアルを実行するために必要な画像をダウンロードするリンクがここにあります : picasso.jpg と dancing.jpg。これら 2 つの画像をダウンロードしてそれらを現在の作業デレクトリで名前 images を持つディレクトリに追加してください。
# desired size of the output image
imsize = 512 if torch.cuda.is_available() else 128 # use small size if no gpu
loader = transforms.Compose([
transforms.Resize(imsize), # scale imported image
transforms.ToTensor()]) # transform it into a torch tensor
def image_loader(image_name):
image = Image.open(image_name)
# fake batch dimension required to fit network's input dimensions
image = loader(image).unsqueeze(0)
return image.to(device, torch.float)
style_img = image_loader("./data/images/neural-style/picasso.jpg")
content_img = image_loader("./data/images/neural-style/dancing.jpg")
assert style_img.size() == content_img.size(), \
"we need to import style and content images of the same size"
さて、それのコピーを PIL フォーマットに再変換して plt.imshow を使用してコピーを表示することにより画像を表示する関数を作成しましょう。コンテンツとスタイル画像をそれらが正しくインポートされているかを確かめるために表示してみます。
unloader = transforms.ToPILImage() # reconvert into PIL image
plt.ion()
def imshow(tensor, title=None):
image = tensor.cpu().clone() # we clone the tensor to not do changes on it
image = image.squeeze(0) # remove the fake batch dimension
image = unloader(image)
plt.imshow(image)
if title is not None:
plt.title(title)
plt.pause(0.001) # pause a bit so that plots are updated
plt.figure()
imshow(style_img, title='Style Image')
plt.figure()
imshow(content_img, title='Content Image')
| ![]() |
損失関数
コンテンツ損失
コンテンツ損失は個々の層のためのコンテンツ距離の重み付けられたバージョンを表わす関数です。関数は入力 $X$ を処理するネットワークの層 $L$ の特徴マップ $F_{XL}$ を取りそして画像 $X$ とコンテンツ画像 $C$ の間の重み付けられたコンテンツ距離 $w_{CL}.D_C^L(X,C)$ を返します。コンテンツ画像 $F_{CL}$ の特徴マップはコンテンツ距離を計算するために関数により知られなければなりません。この関数を、入力として $F_{CL}$ を取るコンストラクタを持つ torch モジュールとして実装します。距離 $\|F_{XL} – F_{CL}\|^2$ は特徴マップの 2 つのセット間の平均二乗誤差 (= mean square error) で、nn.MSELoss を使用して計算できます。
このコンテンツ損失モジュールをコンテンツ距離を計算するために使用されている畳み込み層 (s) の後に直接的に追加します。このようにしてネットワークに入力画像が供給されるたびにコンテンツ損失は望まれる層で計算され、そして auto grad ゆえに、総ての勾配が計算されます。今、コンテンツ損失層を透過にするためにコンテンツ損失を計算してから層の入力を返す forward メソッドを定義しなければなりません。計算された損失はモジュールのパラメータとしてセーブされます。
class ContentLoss(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
# will throw an error.
self.target = target.detach()
def forward(self, input):
self.loss = F.mse_loss(input, self.target)
return input
Note: 重要な細目: このモジュールは ContentLoss と名前付けられていますが、それは真の PyTorch 損失関数ではありません。貴方のコンテンツ損失を PyTorch 損失関数として定義することを望む場合、backward メソッドで勾配を手動で再計算/実装するために PyTorch autograd 関数を作成しなければなりません。
スタイル損失
スタイル損失モジュールはコンテンツ損失モジュールと同様に実装されます。それは層のスタイル損失を計算するネットワークの透過層として機能します。スタイル損失を計算するために、グラム行列 $G_{XL}$ を計算する必要があります。グラム行列は与えられた行列をその転置行列により乗算した結果です。このアプリケーションでは与えられた行列は 層 $L$ の特徴マップ $F_{XL}$ の reshape されたバージョンです。$F_{XL}$ は $\hat{F}_{XL}$、$K$ x $N$ 行列を形成するために reshape されます、ここで $K$ は層 $L$ の特徴マップの数で $N$ は任意のベクトル化された特徴マップ $F_{XL}^k$ の長さです。例えば、$\hat{F}_{XL}$ の最初の行は最初のベクトル化された特徴マップ $F_{XL}^1$ に対応します。
最後に、グラム行列は各要素を行列の要素の総数により除算することで正規化されなければなりません。この正規化は巨大な $N$ 次元を持つ $\hat{F}_{XL}$ 行列がグラム行列でより大きな値を生成するという事実を妨げます。これらのより巨大な値は勾配降下の間に (プーリング層の前の) 最初の層により大きなインパクトを持つこと引き起こします。スタイル特徴はネットワークのより深い層にありがちですのでこの正規化ステップは重要です。
def gram_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) # resise F_XL into \hat F_XL
G = 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.
return G.div(a * b * c * d)
さてスタイル損失モジュールはコンテンツ損失モジュールのように殆ど正確に (同じに) 見えます。スタイル距離はまた $G_{XL}$ と $G_{SL}$ 間の平均二乗誤差 (= mean square error) を使用して計算されます。
class StyleLoss(nn.Module):
def __init__(self, target_feature):
super(StyleLoss, self).__init__()
self.target = gram_matrix(target_feature).detach()
def forward(self, input):
G = gram_matrix(input)
self.loss = F.mse_loss(G, self.target)
return input
モデルをインポートする
今は事前訓練されたニューラルネットワークをインポートする必要があります。ペーパーで使用されたもののような 19 層 VGG ネットワークを使用します。
VGG の PyTorch の実装は 2 つのチャイルド Sequential モジュールに分割されたモジュールです : (畳み込みとプーリング層を含む) 特徴、そして (完全結合層を含む) 分類器です。私達は特徴モジュールを使用します、何故ならばコンテンツとスタイル損失を計測するために個々の畳み込み層の出力が必要だからです。幾つかの層は訓練の間に評価とは異なる動作を持ちますので、ネットワークを .eval() を使用して評価モードに設定しなければなりません。
cnn = models.vgg19(pretrained=True).features.to(device).eval()
更に、VGG ネットワークは各チャネルが mean=[0.485, 0.456, 0.406] と std=[0.229, 0.224, 0.225] で正規化された画像上で訓練されます。(画像を) ネットワークに送る前に画像を正規化するためにそれらを使用します。
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
# create a module to normalize input image so we can easily put it in a
# nn.Sequential
class Normalization(nn.Module):
def __init__(self, mean, std):
super(Normalization, self).__init__()
# .view the mean and std to make them [C x 1 x 1] so that they can
# directly work with image Tensor of shape [B x C x H x W].
# B is batch size. C is number of channels. H is height and W is width.
self.mean = torch.tensor(mean).view(-1, 1, 1)
self.std = torch.tensor(std).view(-1, 1, 1)
def forward(self, img):
# normalize img
return (img - self.mean) / self.std
Sequential モジュールはチャイルド・モジュールの順序付けられたリストを含みます。例えば、vgg19.features は深さの正しい順序で整列されたシークエンス (Conv2d, ReLU, MaxPool2d, Conv2d, ReLU…) を含みます。コンテンツ損失とスタイル損失層を (それらが検出している) 畳み込み層直後に追加する必要があります。これを行なうために正しく挿入されたコンテンツ損失とスタイル損失モジュールを持つ新しい Sequential モジュールを作成しなければなりません。
# 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']
def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
style_img, content_img,
content_layers=content_layers_default,
style_layers=style_layers_default):
cnn = copy.deepcopy(cnn)
# normalization module
normalization = Normalization(normalization_mean, normalization_std).to(device)
# just in order to have an iterable access to or list of content/syle
# losses
content_losses = []
style_losses = []
# assuming that cnn is a nn.Sequential, so we make a new nn.Sequential
# to put in modules that are supposed to be activated sequentially
model = nn.Sequential(normalization)
i = 0 # increment every time we see a conv
for layer in cnn.children():
if isinstance(layer, nn.Conv2d):
i += 1
name = 'conv_{}'.format(i)
elif isinstance(layer, nn.ReLU):
name = 'relu_{}'.format(i)
# The in-place version doesn't play very nicely with the ContentLoss
# and StyleLoss we insert below. So we replace with out-of-place
# ones here.
layer = nn.ReLU(inplace=False)
elif isinstance(layer, nn.MaxPool2d):
name = 'pool_{}'.format(i)
elif isinstance(layer, nn.BatchNorm2d):
name = 'bn_{}'.format(i)
else:
raise RuntimeError('Unrecognized layer: {}'.format(layer.__class__.__name__))
model.add_module(name, layer)
if name in content_layers:
# add content loss:
target = model(content_img).detach()
content_loss = ContentLoss(target)
model.add_module("content_loss_{}".format(i), content_loss)
content_losses.append(content_loss)
if name in style_layers:
# add style loss:
target_feature = model(style_img).detach()
style_loss = StyleLoss(target_feature)
model.add_module("style_loss_{}".format(i), style_loss)
style_losses.append(style_loss)
# now we trim off the layers after the last content and style losses
for i in range(len(model) - 1, -1, -1):
if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
break
model = model[:(i + 1)]
return model, style_losses, content_losses
次に、入力画像を選択します。コンテンツ画像のコピーかホワイトノイズを使用できます。
input_img = content_img.clone() # if you want to use white noise instead uncomment the below line: # input_img = torch.randn(content_img.data.size(), device=device) # add the original input image to the figure: plt.figure() imshow(input_img, title='Input Image')

勾配降下
Leon Gatys、アルゴリズムの立案者が ここ で提案したように、勾配降下を実行するために L-BFGS アルゴリズムを使用します。ネットワークの訓練とは違い、コンテンツ/スタイル損失を最小化するために入力画像を訓練することを望みます。PyTorch L-BFGS optimizer optim.LBFGS を作成して画像を最適化するための tensor としてそれに渡します。
def get_input_optimizer(input_img):
# this line to show that input is a parameter that requires a gradient
optimizer = optim.LBFGS([input_img.requires_grad_()])
return optimizer
最後に、画風変換を遂行する関数を定義しなければなりません。ネットワークの各反復について、それは更新された入力が供給されて新しい損失を計算します。各損失モジュールの backward メソッドをそれらの勾配を動的に計算するために実行します。optimizer は “closure” 関数を必要とします、これはモデルを再評価して損失を返します。
依然として処理すべき一つの最後の制約があります。ネットワークは画像のために 0 と 1 tensor 範囲を超える値を持つ入力を最適化しようとするかもしれません。これをネットワークが実行されるたびに入力値を 0 と 1 の間にあるように正すことで対処できます。
def run_style_transfer(cnn, normalization_mean, normalization_std,
content_img, style_img, input_img, num_steps=300,
style_weight=1000000, content_weight=1):
"""Run the style transfer."""
print('Building the style transfer model..')
model, style_losses, content_losses = get_style_model_and_losses(cnn,
normalization_mean, normalization_std, style_img, content_img)
optimizer = get_input_optimizer(input_img)
print('Optimizing..')
run = [0]
while run[0] <= num_steps:
def closure():
# correct the values of updated input image
input_img.data.clamp_(0, 1)
optimizer.zero_grad()
model(input_img)
style_score = 0
content_score = 0
for sl in style_losses:
style_score += sl.loss
for cl in content_losses:
content_score += cl.loss
style_score *= style_weight
content_score *= content_weight
loss = style_score + content_score
loss.backward()
run[0] += 1
if run[0] % 50 == 0:
print("run {}:".format(run))
print('Style Loss : {:4f} Content Loss: {:4f}'.format(
style_score.item(), content_score.item()))
print()
return style_score + content_score
optimizer.step(closure)
# a last correction...
input_img.data.clamp_(0, 1)
return input_img
最後に、アルゴリズムを実行できます。
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
content_img, style_img, input_img)
plt.figure()
imshow(output, title='Output Image')
# sphinx_gallery_thumbnail_number = 4
plt.ioff()
plt.show()

Building the style transfer model.. Optimizing.. run [50]: Style Loss : 4.169304 Content Loss: 4.235329 run [100]: Style Loss : 1.145476 Content Loss: 3.039176 run [150]: Style Loss : 0.716769 Content Loss: 2.663749 run [200]: Style Loss : 0.476047 Content Loss: 2.500893 run [250]: Style Loss : 0.347092 Content Loss: 2.410895 run [300]: Style Loss : 0.263698 Content Loss: 2.358449
以上
