TensorFlow学习(三)

mac2025-06-07  56

TensorFlow学习(三)

TensorFlow学习(三)代价函数二次代价函数交叉熵代价函数对数释然代价函数 过拟合Dropout优化器

TensorFlow学习(三)

代价函数

二次代价函数

其中C为代价函数,x为样本,y为实际值,a为输出值,n表示样本总数。 如果使用梯度下降法:

交叉熵代价函数

其中C为代价函数,x为样本,y为实际值,a为输出值,n表示样本总数。 如果使用梯度下降法:

对数释然代价函数

对数释然函数在二分类时可以简化成交叉熵代价函数

对数释然代价函数常用来作为softmax回归的代价函数 交叉熵代价函数常用来作为sigmoid函数的代价函数

过拟合

为了防止过拟合,有三种方法: 1.增加数据集; 2.正则化; 3.Dropout;

Dropout

采用Dropout方法 在一次迭代中让部分神经元工作,部分神经元不工作,下一次迭代换另一部分神经元工作。 代码:

############一个隐藏层,隐藏层为700 ############激活函数为tf.nn.tanh ############使用dropout,训练为%70,测试为%100 ############代价函数使用二次代价函数,优化器使用梯度下降法 import tensorflow as tf import numpy as np 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 = tf.placeholder(tf.float32) #创建一个简单的神经网络 W1 = tf.Variable(tf.truncated_normal([784,700],stddev=0.1)) b1 = tf.Variable(tf.zeros([1,700]) + 0.1) L1 = tf.matmul(x,W1)+b1 LL1 = tf.nn.tanh(L1) L1_d = tf.nn.dropout(LL1,keep) W2 = tf.Variable(tf.truncated_normal([700,10],stddev=0.1)) b2 = tf.Variable(tf.zeros([10]) + 0.1) L2 = tf.matmul(L1_d,W2)+b2 #LL2 = tf.nn.sigmoid(L2) prediction = tf.nn.softmax(L2) #二次代价函数 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.3).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(20): 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:0.7}) #用百分之70的神经元训练 acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep:1.0}) #用全部的神经元测试 acc1 = sess.run(accuracy,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep:1.0}) print("Iter " + str(epoch) + ",Testing Accuracy " + str(acc)+",Training Accuracy " + str(acc1))

结果为:

优化器

最新回复(0)