Tensorflow1.0 第三集:Dropout
防止过拟合的方法:
- 增加数据集
- 正则化方法: C = C 0 + λ 2 n ∑ w w 2 C = C_{0} + \frac{\lambda}{2n}\sum_{w}w^{2} C=C0+2nλ∑ww2,减少了网络的复杂程度
- Dropout:训练的时候只用部分的神经元进行训练,测试的时候再将所有神经元激活
还是之前的手写数字集,继续加上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 = 50
# 计算一共有多少个批次
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32, [None, 784]) #每张图像有784个像素块 28*28的
y = tf.placeholder(tf.float32, [None, 10])
keep_prob = tf.placeholder(tf.float32) #dropout
# 一个神经网络
W = tf.Variable(tf.random_normal([784, 2000]))
b = tf.Variable(tf.zeros([1, 2000]))
L = tf.nn.tanh(tf.matmul(x, W) + b)
L_drop = tf.nn.dropout(L, keep_prob)
W1 = tf.Variable(tf.random_normal([2000, 2000]))
b1 = tf.Variable(tf.zeros([1, 2000]))
L1 = tf.nn.tanh(tf.matmul(L_drop, W1) + b1)
L1_drop = tf.nn.dropout(L1, keep_prob)
W2 = tf.Variable(tf.random_normal([2000, 10]))
b2 = tf.Variable(tf.random_normal([1, 10]))
L2 = tf.nn.tanh(tf.matmul(L1_drop, W2) + b2)
L2_drop = tf.nn.dropout(L2, keep_prob)
prediction = tf.nn.softmax(L2_drop)
# loss = tf.reduce_mean(tf.square(prediction - y))
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))
train_step = tf.train.GradientDescentOptimizer(learning_rate=0.2).minimize(loss)
init = tf.global_variables_initializer()
# 求准确率
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(prediction, 1)) #布尔型列表
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #tf.cast 把布尔型转换为浮点型
with tf.Session() as sess:
sess.run(init)
for epoch in range(30):
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: 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))