> For the complete documentation index, see [llms.txt](https://baozoulin.gitbook.io/neural-networks-and-deep-learning/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://baozoulin.gitbook.io/neural-networks-and-deep-learning/di-si-men-ke-juan-ji-shen-jing-wang-luo-convolutional-neural-networks/convolutional-neural-networks/special-applications/48-dai-jia-han-shu-ff08-cost-function.md).

# 4.7 代价函数（Cost function）

为了实现神经风格迁移，需要定义一个关于$$G$$的代价函数$$J$$用来评判某个生成图像的好坏，使用梯度下降法去最小化$$J(G)$$，以便于生成图像

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/dd9dc6d164ca059f7996a6cbf58997a5.jpg)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/dd9dc6d164ca059f7996a6cbf58997a5.jpg)

代价函数定义为两个部分：

* $$J\_{\text{content}}(C,G)$$，被称作内容代价，是一个关于内容图片和生成图片的函数，用来度量生成图片$$G$$的内容与内容图片$$C$$的内容有多相似
* 然后把结果加上一个风格代价函数$$J\_{\text{style}}(S,G)$$，用来度量图片$$G$$的风格和图片$$S$$的风格的相似度

$$
J( G) = \alpha J\_{\text{content}}( C,G) + \beta J\_{\text{style}}(S,G)
$$

最后用两个超参数$$\alpha$$和$$\beta$$来来确定内容代价和风格代价

对于代价函数$$J(G)$$，为了生成一个新图像，要做的是随机初始化生成图像$$G$$，可能是100×100×3、500×500×3，或任何想要的尺寸

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/b8dafd082111a86c00066dedd1033ef1.png)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/b8dafd082111a86c00066dedd1033ef1.png)

然后使用之前定义的代价函数$$J(G)$$，用梯度下降的方法将其最小化，更新：

$$
G:= G - \frac{\partial}{\partial G}J(G)
$$

即更新图像$$G$$的像素值，也就是100×100×3，比如**RGB**通道的图片

比如从内容图片（编号1）和风格（编号2）图片开始，当随机初始化$$G$$，生成图像就是随机选取像素的白噪声图（编号3）。接下来运行梯度下降算法，最小化代价函数$$J(G)$$，逐步处理像素，慢慢得到一个生成图片（编号4、5、6），越来越像用风格图片的风格画出来的内容图片

[![](https://github.com/fengdu78/deeplearning_ai_books/raw/master/images/dd376e74155008845e96d662cc45493a.png)](https://github.com/fengdu78/deeplearning_ai_books/blob/master/images/dd376e74155008845e96d662cc45493a.png)
