プリンキピア

第14章コンピュータビジョン

14.12.6. Initializing the Synthesized Image14.12.6 合成画像を初期化する

In style transfer, the synthesized image is the only variable that needs to be updated during training. Thus, we can define a simple model, SynthesizedImage, and treat the synthesized image as the model parameters. In this model, forward propagation just returns the model parameters.
英語のヒント
スタイル変換では、合成画像は訓練のあいだに更新する必要のある唯一の変数である。したがって、単純なモデルSynthesizedImageを定義し、合成画像をモデルのパラメータとして扱える。このモデルでは、順伝播は単にモデルのパラメータを返す。
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
Next, we define the get_inits function. This function creates a synthesized image model instance and initializes it to the image X. Gram matrices for the style image at various style layers, styles_Y_gram, are computed prior to training.
英語のヒント
次に、get_inits関数を定義する。この関数は、合成画像のモデルのインスタンスを作り、それを画像Xに初期化する。さまざまなスタイル層でのスタイル画像のグラム行列styles_Y_gramは、訓練の前に計算される。
def get_inits(X, device, lr, styles_Y):
    gen_img = SynthesizedImage(X.shape).to(device)
    gen_img.weight.data.copy_(X.data)
    trainer = torch.optim.Adam(gen_img.parameters(), lr=lr)
    styles_Y_gram = [gram(Y) for Y in styles_Y]
    return gen_img(), styles_Y_gram, trainer