Neural style transfer optimises an image x against the energy
L(x∣xs,xc)=λTVTV(x)+λcLcontent(x,xc)+λsLstyle(x,xs)(14.33)
built from feature maps ϕℓ of a fixed CNN. Feature maps are arrays of shape (H, W, C). Implement:
gram(phi): Gc,d=HW1∑h,wϕh,w,cϕh,w,d, a (C, C) array.
content_loss(phi_x, phi_c): CHW1∥ϕ(x)−ϕ(xc)∥2.
style_loss(phis_x, phis_s): lists of feature maps, one per style layer (spatial sizes may differ between x and xs); returns ∑ℓ∥G(ϕℓ(x))−G(ϕℓ(xs))∥F2.
tv(img): for an (H, W, K) image, ∑i,j,k(xi,j,k−xi+1,j,k)2+(xi,j,k−xi,j+1,k)2 over all pairs inside the image.
total_loss(img, phi_x, phi_c, phis_x, phis_s, lam_tv, lam_c, lam_s): the three-term style-transfer energy.
style_grad(phi, G_target): the gradient of ∥G(ϕ)−Gtarget∥F2 with respect to ϕ, shape (H, W, C).