激活函数的生成及图像

版权声明:如有转载复制请注明出处,博主QQ715608270,欢迎沟通交流! https://blog.csdn.net/qq_41000891/article/details/84541106

所谓激活函数(Activation Function),就是在人工神经网络的神经元上运行的函数,负责将神经元的输入映射到输出端。

        激活函数(Activation functions)对于人工神经网络模型去学习、理解非常复杂和非线性的函数来说具有十分重要的作用。它们将非线性特性引入到我们的网络中。如下图,在神经元中,输入的 inputs 通过加权,求和后,还被作用了一个函数,这个函数就是激活函数。引入激活函数是为了增加神经网络模型的非线性。没有激活函数的每层都相当于矩阵相乘。就算你叠加了若干层之后,无非还是个矩阵相乘罢了。

        常见的激活函数有很多,如Sigmoid,Relu,Tanh,Softplus,下面我们通过代码生成的方式展示这些激活函数:

# -*- coding: UTF-8 -*-

import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf

# 创建输入数据
x = np.linspace(-7, 7, 180) # (-7, 7)之间的等间隔的180个点

# 经过TensorFlow的激活函数处理的各个Y值
y_sigmoid = tf.nn.sigmoid(x)
y_relu = tf.nn.relu(x)
y_tanh = tf.nn.tanh(x)
y_softplus = tf.nn.softplus(x)

# 创建会话
sess = tf.Session()

# 运行
y_sigmoid, y_relu, y_tanh, y_softplus = sess.run([y_sigmoid, y_relu, y_tanh, y_softplus])

# 创建各个激活函数的图像
plt.subplot(221)
plt.plot(x, y_sigmoid, c="red", label="Sigmoid")
plt.ylim(-0.2, 1.2)
plt.legend(loc="best")

plt.subplot(222)
plt.plot(x, y_relu, c="red", label="Relu")
plt.ylim(-1, 6)
plt.legend(loc="best")

plt.subplot(223)
plt.plot(x, y_tanh, c="red", label="Tanh")
plt.ylim(-1.3, 1.3)
plt.legend(loc="best")

plt.subplot(224)
plt.plot(x, y_softplus, c="red", label="Softplus")
plt.ylim(-1, 6)
plt.legend(loc="best")

# 绘制并显示图像
plt.show()

# 关闭会话
sess.close()

      激活函数模块是需要通过tf.nn进行调用,nn是(neural network)

      运行后我们可以看到其图像:

      上图是通过直接调用tf.nn来绘制的图像,当然我们也可以使用原始的数学方法进行生成,如下代码:

# 激活函数的原始实现
def sigmoid(imputs):
	y = [1 / float(1 + np.exp(-x)) for x in inputs]
	return y

def relu(inputs):
	y = [x * (x > 0) for x in inputs]
	return y

def tanh(inputs):
	y = [(np.exp(x) - np.exp(-x)) / float(np.exp(x) + np.exp(-x)) for x in inputs]
	return y

def softplus(inputs):
	y = [np.log(1 + np.exp(x)) for x in inputs]
	return y

猜你喜欢

转载自blog.csdn.net/qq_41000891/article/details/84541106