文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
本文主要是介绍tensorflow中dropout的作用,dropout主要是用来防止过拟合,即提供模型的泛化能力。
#!/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
测试误差与训练误差的损失差的较大,说明模型更拟合训练数据。
- 有dropout
测试误差与训练误差相差不大,说明模型泛化能力较好。