【TF2-03】神经网络

文章目录

*
全连接层
神经网络

+ 概念
+ 层方式实现神经网络
+ Sequential
激活函数

+ Sigmoid
+ ReLU
+ LeakyReLU
+ Tanh
输出方式
误差计算

+ MSE
+ 交叉熵

全连接层

全连通层本质上是矩阵的乘法和加法运算,实现起来并不复杂。

[En]

The fully connected layer is essentially the multiplication and addition operation of matrices, and the implementation is not complicated.

但是作为最常用的网络层之一,TensorFlow 中有更高层、使用更方便的层实现方式:
tf.keras.layers.Dense(units, activation)

通过layer.Dense 类,只需要指定 输出节点数Units激活函数类型activation 即可。需要注意的是, 输入节点数会根据第一次运算时的输入shape 确定,同时根据输入、输出节点数自动创建并初始化权值张量𝑾和偏置张量𝒃,因此在新建类Dense 实例时,并不会立即创建权值张量𝑾和偏置张量𝒃,而是需要调用build 函数或者直接进行一次前向计算,才能完成网络参数的创建。

其中activation 参数指定当前层的激活函数,可以为常见的激活函数或自定义激活函数,也可以指定为None,即无激活函数。

from tensorflow.keras import layers

fc = layers.Dense(512, activation=tf.nn.relu)

我们可以通过类内部的成员名 kernelbias 来获取权值张量𝑾和偏置张量𝒃对象:

fc.kernel

<tf.Variable 'dense_1/kernel:0' shape=(784, 512) dtype=float32, numpy=
array([[-0.04067389, 0.05240148, 0.03931375, ..., -0.01595572,
-0.01075954, -0.06222073],

fc.bias

<tf.Variable 'dense_1/bias:0' shape=(512,) dtype=float32, numpy=
array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,

在优化参数时,需要获得网络的所有待优化的张量参数列表,可以通过类的 trainable_variables 来返回待优化参数列表,代码如下:

fc.trainable_variables

[<tf.Variable 'dense_1/kernel:0' shape=(784, 512) dtype=float32,...,
<tf.Variable 'dense_1/bias:0' shape=(512,) dtype=float32, numpy=...]

神经网络

概念

通过层层堆叠图中的全连接层,保证前一层的输出节点数与当前层的输入节点数匹配,即可堆叠出任意层数的网络。我们把这种由神经元相互连接而成的网络叫做神经网络。如图 6.5 所示,通过堆叠4 个全连接层,可以获得层数为4 的神经网络,由于每层均为全连接层,称为全连接网络。其中第1~3 个全连接层在网络中间,称之为隐藏层1、2、3,最后一个全连接层的输出作为网络的输出,称为输出层。隐藏层1、2、3 的输出节点数分别为[256,128,64],输出层的输出节点数为10。

【TF2-03】神经网络
在设计全连通网络时,可以根据经验法则自由设置网络结构配置等超级参数,只需遵循少量约束即可。
[En]

When designing a fully connected network, the network structure configuration and other super parameters can be set freely according to the rule of thumb, and only a small number of constraints need to be followed.

例如,

  • 隐藏层1 的输入节点数需和数据的实际特征长度匹配
  • 每层的输入层节点数与上一层输出节点数匹配
  • *输出层的激活函数和节点数需要根据任务的具体设定进行设计

总的来说,神经网络模型的结构设计自由度较大,如图 层中每层的输出节点数不一定要设计为[256,128,64,10],可以自由搭配,如[256,256,64,10]或[512,64,32,10]等都是可行的。至于与哪一组超参数是最优的,这需要很多的领域经验知识和大量的实验尝试,或者可以通过AutoML 技术搜索出较优设定。

; 层方式实现神经网络

对于传统的网络层,通过分层的方式更加简洁和高效。首先,创建每个网络层类,并为每个层指定激活函数的类型:

[En]

For the conventional network layer, it is more concise and efficient through the layer way. First, create each network layer class and specify the type of activation function for each layer:


from tensorflow.keras import layers,Sequential

fc1 = layers.Dense(256, activation=tf.nn.relu)
fc2 = layers.Dense(128, activation=tf.nn.relu)
fc3 = layers.Dense(64, activation=tf.nn.relu)
fc4 = layers.Dense(10, activation=None)

在正向计算中,您可以按顺序遍历每个网络层。代码如下:

[En]

In the forward calculation, you can go through each network layer in order. The code is as follows:

x = tf.random.normal([4,28*28])
h1 = fc1(x)
h2 = fc2(h1)
h3 = fc3(h2)
h4 = fc4(h3)

Sequential

对于这种数据依次向前传播的网络,也可以通过 Sequential 容器封装成一个网络大类对象,调用大类的前向计算函数一次即可完成所有层的前向计算,使用起来更加方便,实现如下:


from tensorflow.keras import layers,Sequential

model = Sequential([
    layers.Dense(256, activation=tf.nn.relu) ,
    layers.Dense(128, activation=tf.nn.relu) ,
    layers.Dense(64, activation=tf.nn.relu) ,
    layers.Dense(10, activation=None) ,
])

在正向计算中,只需调用一次网络大类对象,即可完成所有层的顺序计算:

[En]

In the forward calculation, you only need to call the network large class object once to complete the sequential calculation of all layers:

out = model(x)

激活函数

Sigmoid

Sigmoid 函数也叫Logistic 函数,定义为

【TF2-03】神经网络
【TF2-03】神经网络
它的一个优良特性就是能够把𝑥 ∈ 𝑅的输入”压缩”到𝑥 ∈ (0,1)区间。
tf.nn.sigmoid(x)

ReLU

ReLU(REctified Linear Unit,修正线性单元)激活函数

【TF2-03】神经网络
【TF2-03】神经网络
tf.nn.relu(x)

LeakyReLU

ReLU 函数在𝑥 < 0时导数值恒为0,也可能会造成梯度弥散现象,为了克服这个问题,LeakyReLU 函数被提出,LeakyReLU 的表达式为:

【TF2-03】神经网络
【TF2-03】神经网络
tf.nn.leaky_relu(x, alpha=0.1)

Tanh

Tanh 函数能够将𝑥 ∈ 𝑅的输入”压缩”到(−1,1)区间,定义为:

【TF2-03】神经网络
【TF2-03】神经网络
tf.nn.tanh(x)

输出方式

  • 比如正弦函数曲线的预测、年龄的预测、股票走势的预测都属于整个或部分连续实空间,输出层不能增加激活函数。
    [En]

    for example, the prediction of sine function curve, the prediction of age and the prediction of stock trend all belong to the whole or part of continuous real space, and the output layer can not add activation function.*

  • 输出值属于[0, 1]区间也比较常见,比如图片的生成、二分类问题等。为了让像素的值范围映射到[0,1]的有效实数空间,需要在输出层后添加某个合适的激活函数𝜎,其中 Sigmoid 函数刚好具有此功能。
  • 输出值𝑜𝑖 ∈ [0,1],且所有输出值之和为1,这种设定以多分类问题最为常见。满足所有类别概率之和为1 。 Softmax 函数不仅可以将输出值映射到[0,1]区间,还满足所有的输出值之和为1 的特性。
  • 如果希望输出值的范围分布在(−1, 1)区间,可以简单地使用 tanh 激活函数。

误差计算

MSE

均方差(Mean Squared Error,简称MSE)误差函数把输出向量和真实向量映射到笛卡尔坐标系的两个点上,通过计算这两个点之间的欧式距离(准确地说是欧式距离的平方)来衡量两个向量之间的差距:

【TF2-03】神经网络
MSE 误差函数的值总是大于等于0,当MSE 函数达到最小值0 时,输出等于真实标签,此时神经网络的参数达到最优状态。
loss = tf.losses.MSE(y_onehot, o)

loss = tf.reduce_mean(loss)

交叉熵

【TF2-03】神经网络
  • 计算多分类问题的交叉信息熵
    [En]

    calculate the cross information entropy of multi-classification problems*

 tf.losses.categorical_crossentropy(y_true, y_pred, from_logits=True)
  • 计算二分分类问题的交叉信息熵
    [En]

    calculate the cross information entropy of binary classification problems*

tf.losses.binary_crossentropy(y_true, y_prob)

Original: https://blog.csdn.net/iiinoname/article/details/121799161
Author: 不知道在干嘛每天
Title: 【TF2-03】神经网络

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/514630/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球