【tensorflow 深度学习】3.代价函数、过拟合现象、优化器

xiaoxiao2021-02-28  29

1.二次代价函数

      (1)                                 

                                                     

    其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数。为简单起见,同样一个样本为例进行说明,此时二次代价函数为:

                                                        

其中:

    a=σ(z), z=∑Wj*Xj+b

    σ() 是激活函数

        (2)假如我们使用梯度下降法(Gradient descent)来调整权值参数的大小,权值w和偏置b的梯度推导如下:

                                                    

    其中,z表示神经元的输入,σ表示激活函数。 w和b的梯度跟激活函数的梯度成正比,激活函数的梯度越大,w和b的大小调整得越快,训练收敛得就越快。

    假设我们的激活函数是sigmoid函数:

                    

    如果我们目标是收敛到1,A点为0.82,离目标比较远,梯度比较大,权值调整比较大。B点为0.98,离目标比较近,梯度比较小,权值调整比较小。调整方案合理。

    如果我们目标是收敛到0,A点为0.82,离目标比较近,梯度比较大,权值调整比较大。B点为0.98,离目标比较远,梯度比较小,权值调整比较小。调整方案不合理。

    (3)交叉熵代价函数

    换一个思路,我们不改变激活函数,而是改变代价函数,改用交叉熵代价函数:

                                    

    其中,C表示代价函数,x表示样本,y表示实际值,a表示输出值,n表示样本的总数。     a=σ(z), z=∑Wj*Xj+b     

    计算过程:

                            

        所以有:

                                    

    所以我们可以看到,权值和偏置值的调整与无关,另外,梯度公式中的 表示输出值与实际值的误差。所以当误差越大时,梯度就越大,参数w和b的调整就越快,训练的速度也就越快。

    如果输出神经元是线性的,那么二次代价函数就是一种合适的选择。如果输出神经元是S型函数,那么比较适合用交叉熵代价函数。

    (4)对数释然代价函数

    对数释然函数常用来作为softmax回归的代价函数,如果输出层神经元是sigmoid函数,可以采用交叉熵代价函数。而深度学

习中更普遍的做法是将softmax作为最后一层,此时常用的代价函数是对数释然代价函数。

    对数似然代价函数与softmax的组合和交叉熵与sigmoid函数的组合非常相似。对数释然代价函数在二分类时可以化简为交叉

熵代价函数的形式。

    在Tensorflow中用:     tf.nn.sigmoid_cross_entropy_with_logits()来表示跟sigmoid搭配使用的交叉熵。    tf.nn.softmax_cross_entropy_with_logits()来表示跟softmax搭配使用的交叉熵。

    在上一篇博文中用的是二次代价函数,结果如下:

    

    将其改为对数释然代价函数:

    将 loss=tf.reduce_mean(tf.square(y-prediction))

    改为:tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)

    结果:

    

2.拟合

    

(1)防止过拟合

        a. 增加数据集

        b. 正则化方法,让某些权值接近于0的神经元权值越来越小

                                                        

        c.Dropout,让部分神经元工作,部分不工作

    上一篇博文里的神经网络增加层数后会出现过拟合:

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 mnist=input_data.read_data_sets("MNIST_data",one_hot=True) #每个批次的大小 batch_size=100 #计算一共有多少个批次 n_batch=mnist.train.num_examples//batch_size #定义两个placeholder x=tf.placeholder(tf.float32, [None,784]) y=tf.placeholder(tf.float32,[None,10]) keep_prob=tf.placeholder(tf.float32) #创建一个简单的神经网络 W1=tf.Variable(tf.truncated_normal([784,2000],stddev=0.1))    #用截断的正态分布对权值进行初始化 b1=tf.Variable(tf.zeros([2000])+0.1)                          #偏侧值初始化为0.1 L1=tf.nn.tanh(tf.matmul(x,W1)+b1) L1_drop=tf.nn.dropout(L1,keep_prob) W2 = tf.Variable(tf.truncated_normal([2000,2000],stddev=0.1)) b2 = tf.Variable(tf.zeros([2000])+0.1) L2 = tf.nn.tanh(tf.matmul(L1_drop,W2)+b2) L2_drop = tf.nn.dropout(L2,keep_prob) W3 = tf.Variable(tf.truncated_normal([2000,1000],stddev=0.1)) b3 = tf.Variable(tf.zeros([1000])+0.1) L3 = tf.nn.tanh(tf.matmul(L2_drop,W3)+b3) L3_drop = tf.nn.dropout(L3,keep_prob) W4 = tf.Variable(tf.truncated_normal([1000,10],stddev=0.1)) b4 = tf.Variable(tf.zeros([10])+0.1) prediction = tf.nn.softmax(tf.matmul(L3_drop,W4)+b4) #二次代价函数 loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #使用梯度下降法 train_step=tf.train.GradientDescentOptimizer(0.2).minimize(loss) #初始化变量 init=tf.global_variables_initializer() #结果存放在一个布尔型列表中 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置 #求准确率 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): batch_xs,batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:1.0}) test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}) train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep_prob:1.0}) print("Iter " + str(epoch) + ",Testing Accuracy " + str(test_acc) +",Training Accuracy " + str(train_acc))

我们把最后四行改为:

sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7}) test_acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0}) train_acc = sess.run(accuracy,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep_prob:1.0}) print("Iter " + str(epoch) + ",Testing Accuracy " + str(test_acc) +",Training Accuracy " + str(train_acc))

会缓解过拟合现象,复杂网络训练小训练集时现象越明显。

3.优化器

    主要优化器:

    

tf.train.GradientDescentOptimizer

tf.train.AdadeltaOptimizer

tf.train.AdagradOptimizer

tf.train.AdagradDAOptimizer

tf.train.MomentumOptimizer

tf.train.AdamOptimizer

tf.train.FtrlOptimizer

tf.train.ProximalGradientDescentOptimizer

tf.train.ProximalAdagradOptimizer

tf.train.RMSPropOptimizer

    各种优化器在tf中的使用:

上一篇博客的程序改为:

import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 mnist=input_data.read_data_sets("MNIST_data",one_hot=True) import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # In[2]: #载入数据集 mnist = input_data.read_data_sets("MNIST_data",one_hot=True) #每个批次的大小 batch_size = 100 #计算一共有多少个批次 n_batch = mnist.train.num_examples // batch_size #定义两个placeholder x = tf.placeholder(tf.float32,[None,784]) y = tf.placeholder(tf.float32,[None,10]) #创建一个简单的神经网络 W = tf.Variable(tf.zeros([784,10])) b = tf.Variable(tf.zeros([10])) prediction = tf.nn.softmax(tf.matmul(x,W)+b) #二次代价函数 # loss = tf.reduce_mean(tf.square(y-prediction)) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #使用梯度下降法 # train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) train_step = tf.train.AdadeltaOptimizer(1e-2).minimize(loss) #初始化变量 init = tf.global_variables_initializer() #结果存放在一个布尔型列表中 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一维张量中最大的值所在的位置 #求准确率 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) with tf.Session() as sess: sess.run(init) for epoch in range(21): for batch in range(n_batch): batch_xs,batch_ys = mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys}) acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc))
转载请注明原文地址: https://www.6miu.com/read-2621599.html

最新回复(0)