TensorFlow2.0常用激活函数

激活函数是神经网络中一个十分重要的组成部分,它可以对神经元的接收信息进行非线性变换,将变换后的信息输出到下一层神经元

激活函数给神经元引入了非线性因素,使得神经网络可以任意逼近任何非线性函数,这样神经网络就可以应用到众多的非线性模型中


构造数据

import tensorflow as tf
import matplotlib.pyplot as plt

x = tf.linspace(-5., 5., 100)	# 构造一段连续的数据
x_np = x.numpy()	# 转换为 ndarray 的类型,画图时 x 和 x_np 都可以使用

Relu

ReLU 对小于 0 的值全部抑制为 0;对于正数则直接输出,具有单侧抑制、相对宽松的兴奋边界等特性

表达式:
r ( x ) = m a x ( 0 , x ) r(x )=max(0, x)
代码:

y_relu = tf.nn.relu(x)    # 使用 Relu 函数运算

plt.plot(x, y_relu, c='red', label='relu')    # 画折线图
plt.ylim((-1, 6))
plt.legend(loc='best')

plt.show()

形状如图:
在这里插入图片描述


Sigmoid

Sigmoid 能够把 x R x \in R 的输入“压缩”到 x ( 0 , 1 ) x \in (0, 1) 区间

表达式:
σ ( z ) = 1 1 + e x \sigma(z)=\frac{1}{1+e^{-x}}
代码:

y_sigmoid = tf.nn.sigmoid(x)	# 使用 Sigmoid 函数运算

plt.plot(x, y_sigmoid, c='red', label='sigmoid')	# 画折线图
plt.ylim((-0.2, 1.2))
plt.legend(loc='best')

plt.show()

形状如图:
在这里插入图片描述


Tanh

Tanh 函数能够将 x R x \in R 的输入“压缩”到 ( 1 , 1 ) (−1,1) 区间

表达式:
t a n h ( x ) = e x e x e x + e x tanh(x)=\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}
代码:

y_tanh = tf.nn.tanh(x)    # 使用 Tanh 函数运算

plt.plot(x, y_tanh, c='red', label='tanh')    # 画折线图
plt.ylim((-1.2, 1.2))
plt.legend(loc='best')

plt.show()

形状如图:
在这里插入图片描述


Softplus

表达式:
ζ ( x ) = l o g ( 1 + e x ) \zeta(x)=log(1+e^x)
代码:

y_softplus = tf.nn.softplus(x)    # 使用 Softplus 函数运算

plt.plot(x, y_softplus, c='red', label='softplus')    # 画折线图
plt.ylim((-0.2, 6))
plt.legend(loc='best')

plt.show()

形状如图:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_44613063/article/details/104078391