概念
神经元模型
用数学公式表示为: f(∑ i x i w i + b), f 为激活函数。神经网络是以神经元为基本单元构成的。
激活函数
引入非线性激活因素,提高模型的表达力。
常用的激活函数有 relu、sigmoid、tanh 等。
激活函数 relu: 在 Tensorflow 中,用 tf.nn.relu()表示。
relu()数学表达式
relu()数学图形
激活函数 sigmoid:在 Tensorflow 中,用 tf.nn.sigmoid()表示。
sigmoid ()数学表达式
sigmoid()数学图形
激活函数 tanh:在 Tensorflow 中,用 tf.nn.tanh()表示。
tanh()数学表达式
tanh()数学图形
神经网络的复杂度
可用神经网络的层数和神经网络中待优化参数个数表示。
神经网路的层数
一般不计入输入层,层数 = n 个隐藏层 + 1 个输出层。
神经网路待优化的参数
神经网络中所有参数 w 的个数 + 所有参数 b 的个数。
损失函数(loss)
用来表示预测值(y)与已知答案(y_)的差距。在训练神经网络时,通过不断改变神经网络中所有参数,使损失函数不断减小,从而训练出更高准确率的神经网络模型。
常用的损失函数有均方误差、自定义和交叉熵等。
均方误差 mse
n 个样本的预测值 y 与已知答案 y_之差的平方和,再求平均值。
在 Tensorflow 中用 loss_mse = tf.reduce_mean(tf.square(y_ - y))
自定义损失函数
根据问题的实际情况,定制合理的损失函数。
交叉熵
交叉熵(Cross Entropy):表示两个概率分布之间的距离。交叉熵越大,两个概率分布距离越远,两个概率分布越相异;交叉熵越小,两个概率分布距离越近,两个概率分布越相似。
交叉熵计算公式:H(y_ , y) = −∑y_ ∗ log y
用 Tensorflow 函数表示为ce= -tf.reduce_mean(y_* tf.log(tf.clip_by_value(y, 1e-12, 1.0)))
代码
#coding:utf-8
#0导入模块,生成模拟数据集。
import tensorflow as tf
import numpy as np
BATCH_SIZE = 8
seed = 23455
COST = 1
PROFIT = 9
#基于seed产生随机数
rng = np.random.RandomState(seed)
#随机数返回32行2列的矩阵 表示32组 销量影响因素x1,x2 作为输入数据集
X = rng.rand(32,2)
Y = [[x1+x2+(rng.rand()/10.0-0.05)] for (x1, x2) in X]
#1定义神经网络的输入、参数和输出,定义前向传播过程。
x = tf.placeholder(tf.float32, shape=(None, 2))
y_= tf.placeholder(tf.float32, shape=(None, 1))
w1 = tf.Variable(tf.random_normal([2,1], stddev=1, seed=1))
y = tf.matmul(x, w1)
#2定义损失函数及反向传播方法。
#定义损失函数为MSE,反向传播方法为梯度下降。
#loss_mse = tf.reduce_mean(tf.square(y-y_))
loss_mse = tf.reduce_sum(tf.where(tf.greater(y,y_), COST*(y-y_),PROFIT*(y_-y)))
train_step = tf.train.GradientDescentOptimizer(0.001).minimize(loss_mse)
#train_step = tf.train.MomentumOptimizer(0.001,0.9).minimize(loss)
#train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
#3生成会话,训练STEPS轮
with tf.Session() as sess:
init_op = tf.global_variables_initializer()
sess.run(init_op)
STEPS = 20000
for i in range(STEPS):
start = (i*BATCH_SIZE) % 32
end = start + BATCH_SIZE
sess.run(train_step, feed_dict={x: X[start:end], y_: Y[start:end]})
if i % 500 == 0:
print("After %d training step(s), w1 is: " % (i))
print(sess.run(w1), "\n")
total_loss = sess.run(loss_mse, feed_dict={x: X, y_: Y})
print("loss on all data is %g" % (total_loss))
print("Final w1 is: \n", sess.run(w1))