TensorFlow之激活函数(8)

如何使用激活函数?

它的主要作用: 加入非线性

常用的激活函数:

(补充)

 1 # -*- encoding:utf-8 -*-
 2 
 3 import numpy as np
 4 import matplotlib.pyplot as plt
 5 import tensorflow as tf
 6 
 7 # 创建输入数据
 8 X = np.linspace(-7, 7, 180)  #(-7, 7)之间的等间隔的180个点
 9 
10 #激活函数的原始实现
11 def sigmoid(inputs):
12     y = [1 / float(1 + np.exp(-x)) for x in inputs]
13     return y
14     
15 def relu(inputs):
16     y = [x * (x > 0) for x in inputs]
17     return y
18     
19 def tanh(inputs):
20     y = [(np.exp(x) - np.exp(-x)) / float(np.exp(x) + np.exp(-x)) for x in inputs]
21     return y
22     
23 def softplus(inputs):
24     y = [np.log(1 + np.exp(x)) for x in inputs]
25     return y
26     
27 #经过 TensorFlow 的激活函数处理的各个的 Y 值
28 y_sigmoid = tf.nn.sigmoid(X)
29 y_relu    = tf.nn.relu(X)
30 y_tanh    = tf.nn.tanh(X)
31 y_softplus= tf.nn.softplus(X)
32 
33 # 创建会话
34 sess = tf.Session()
35 
36 # 运行
37 y_sigmoid, y_relu, y_tanh, y_softplus = sess.run([y_sigmoid, y_relu, y_tanh, y_softplus])
38 
39 # 创建各个激活函数的图像
40 plt.subplot(221)
41 plt.plot(x, y_sigmoid, c="red", label="Sigmoid")
42 plt.ylim(-0.2, 1.2)      #Y轴的取值范围极限
43 plt.legend(loc="best")   #显示图像,放在最佳位置
44 
45 plt.subplot(222)
46 plt.plot(x, y_relu, c="red", label="Relu")
47 plt.ylim(-1, 6)      #Y轴的取值范围极限
48 plt.legend(loc="best")   #显示图像,放在最佳位置
49 
50 plt.subplot(223)
51 plt.plot(x, y_tanh, c="red", label="Tanh")
52 plt.ylim(-1.3, 1.3)      #Y轴的取值范围极限
53 plt.legend(loc="best")   #显示图像,放在最佳位置
54 
55 plt.subplot(224)
56 plt.plot(x, y_softplus, c="red", label="Softplus")
57 plt.ylim(-1, 6)      #Y轴的取值范围极限
58 plt.legend(loc="best")   #显示图像,放在最佳位置
59 
60 #显示图像
61 plt.show()
62 
63 #关闭会话
64 sess.close()

猜你喜欢

转载自www.cnblogs.com/xyqiu90-365/p/9774219.html