tensorflow的基本用法(八)——dropout的作用

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

本文主要是介绍tensorflow中dropout的作用,dropout主要是用来防止过拟合,即提供模型的泛化能力。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#!/usr/bin/env python
# _*_ coding: utf-8 _*_

import tensorflow as tf
from sklearn.datasets import load_digits
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import LabelBinarizer

# 加载数据
digits = load_digits()
# 输入数据
X = digits.data
# 输出数据
y = digits.target
# 标签变换
y = LabelBinarizer().fit_transform(y)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=.3)

# 创建一个神经网络层
def add_layer(input, in_size, out_size, layer_name, activation_function = None):
"""
:param input:
神经网络层的输入
:param in_zize:
输入数据的大小
:param out_size:
输出数据的大小
:param layer_name
神经网络层的名字
:param activation_function:
神经网络激活函数,默认没有
"""
# 定义神经网络的初始化权重
Weights = tf.Variable(tf.random_normal([in_size, out_size]))
# 定义神经网络的偏置
biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
# 计算w*x+b
W_mul_x_plus_b = tf.matmul(input, Weights) + biases
# 进行dropout,可以注释和不注释来对比dropout的效果
# W_mul_x_plus_b = tf.nn.dropout(W_mul_x_plus_b, keep_prob)
# 根据是否有激活函数进行处理
if activation_function is None:
output = W_mul_x_plus_b
else:
output = activation_function(W_mul_x_plus_b)
# 查看权重变化
tf.summary.histogram(layer_name + '/output', output)
return output


# 定义dropout的placeholder
keep_prob = tf.placeholder(tf.float32)
# 输入数据64个特征
xs = tf.placeholder(tf.float32, [None, 64]) # 8x8
ys = tf.placeholder(tf.float32, [None, 10])

# 添加隐藏层和输出层
l1 = add_layer(xs, 64, 50, 'l1', activation_function=tf.nn.tanh)
prediction = add_layer(l1, 50, 10, 'l2', activation_function=tf.nn.softmax)

# 计算loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))
# 存储loss
tf.summary.scalar('loss', cross_entropy)
# 神经网络训练
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
# 定义Session
sess = tf.Session()
# 收集所有的数据
merged = tf.summary.merge_all()
# 将数据写入到tensorboard中
train_writer = tf.summary.FileWriter("logs/train", sess.graph)
test_writer = tf.summary.FileWriter("logs/test", sess.graph)

# 根据tensorflow版本选择初始化函数
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
# 执行初始化
sess.run(init)
# 进行训练迭代
for i in range(500):
# 执行训练,dropout为1-0.5=0.5
sess.run(train_step, feed_dict={xs: X_train, ys: y_train, keep_prob: 0.5})
if i % 50 == 0:
# 记录损失
train_result = sess.run(merged, feed_dict={xs: X_train, ys: y_train, keep_prob: 1})
test_result = sess.run(merged, feed_dict={xs: X_test, ys: y_test, keep_prob: 1})
train_writer.add_summary(train_result, i)
test_writer.add_summary(test_result, i)

执行结果如下:

  • 没有dropout

no_dropout

测试误差与训练误差的损失差的较大,说明模型更拟合训练数据。

  • 有dropout

dropout

测试误差与训练误差相差不大,说明模型泛化能力较好。

参考资料

  1. https://www.youtube.com/user/MorvanZhou
如果有收获,可以请我喝杯咖啡!