# 4.3 Siamese 网络（Siamese network）

函数d的作用是输入两张人脸，然后输出相似度。实现这个功能的一个方式是用**Siamese**网络

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

向量（编号1）是由网络深层的全连接层计算出来的，叫做$$f(x^{(1)})$$。可以把$$f(x^{(1)})$$看作是输入图像$$x^{(1)}$$的编码，即取输入图像（编号2），然后表示成128维的向量

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

如果要比较两个图片，要做的是把第二张图片喂给有同样参数的同样的神经网络，得到一个不同的128维的向量（编号3），第二张图片的编码叫做$$f(x^{(2)})$$

然后定义$$d$$，将$$x^{(1)}$$和$$x^{(2)}$$的距离定义为两幅图片的编码之差的范数：

$$
d( x^{( 1)},x^{( 2)}) =|| f( x^{( 1)}) - f( x^{( 2)})||\_{2}^{2}
$$

对于两个不同的输入，运行相同的卷积神经网络，然后比较它们，就叫做**Siamese**网络架构

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

训练**Siamese**神经网络：不同图片的CNN网络所有结构和参数都是一样的。所以要做的是训练一个网络，利用梯度下降算法不断调整网络参数，使得属于同一人的图片之间$$d(x^{(1)},x^{(2)})$$ 很小，而不同人的图片之间$$d(x^{(1)},x^{(2)})$$很大

即神经网络的参数定义了一个编码函数$$f(x^{(i)})$$，如果给定输入图像$$x^{(i)}$$，这个网络会输出$$x^{(i)}$$的128维的编码。然后要做的就是学习参数

* 使得如果两个图片$$x^{( i)}$$和$$x^{( j)}$$是同一个人，那么得到的两个编码的距离就小
* 如果$$x^{(i)}$$和$$x^{(j)}$$是不同的人，那么编码距离就大

如果改变这个网络所有层的参数，会得到不同的编码结果，要做的是用反向传播来改变这些所有的参数，以确保满足这些条件


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET 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/43-siamese-wang-luo-ff08-siamese-network.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
