隐藏层
多层感知机在单层神经网络的基础上引入了一到多个隐藏层(hidden layer)。隐藏层位于输入层和输出层之间。图中展示了一个多层感知机的神经网络图,它含有一个隐藏层,该层中有5个隐藏单元。
得到多层感知机的公式:
将两式联立可得:
激活函数
上述问题的根源在于全连接层只是对数据做仿射变换(affine transformation),而多个仿射变换的叠加仍然是一个仿射变换。解决问题的一个方法是引入非线性变换,例如对隐藏变量使用按元素运算的非线性函数进行变换,然后再作为下一个全连接层的输入。这个非线性函数被称为激活函数(activation function)。
共用代码
%matplotlib inline
import tensorflow as tf
from matplotlib import pyplot as plt
import numpy as np
import random
def use_svg_display():
# 用矢量图显示
%config InlineBackend.figure_format = 'svg'
def set_figsize(figsize=(3.5, 2.5)):
use_svg_display()
# 设置图的尺寸
plt.rcParams['figure.figsize'] = figsize
def xyplot(x_vals, y_vals, name):
set_figsize(figsize=(5, 2.5))
plt.plot(x_vals.numpy(), y_vals.numpy())
plt.xlabel('x')
plt.ylabel(name + '(x)')
Relu函数
函数公式
代码实现
x = tf.Variable(tf.range(-8,8,0.1),dtype=tf.float32)
y = tf.nn.relu(x)
xyplot(x, y, 'relu')
输出
导数
# Relu 的导数
with tf.GradientTape() as t:
t.watch(x)
y=y = tf.nn.relu(x)
dy_dx = t.gradient(y, x)
xyplot(x, dy_dx, 'grad of relu')
sigmoid函数
函数公式
代码实现
x = tf.Variable(tf.range(-8,8,0.1),dtype=tf.float32)
y = tf.nn.sigmoid(x)
xyplot(x, y, 'sigmoid')
输出
导数
with tf.GradientTape() as t:
t.watch(x)
y = tf.nn.sigmoid(x)
dy_dx = t.gradient(y, x)
xyplot(x, dy_dx, 'grad of sigmoid')
tanh函数
函数公式
代码实现
x = tf.Variable(tf.range(-8,8,0.1),dtype=tf.float32)
y = tf.nn.tanh(x)
xyplot(x, y, 'tanh')
输出
导数
with tf.GradientTape() as t:
t.watch(x)
y=y = tf.nn.tanh(x)
dy_dx = t.gradient(y, x)
xyplot(x, dy_dx, 'grad of tanh')