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 = 8
#计算一共有多ti少个批次,//为整除
n_batch = mnist.train.num_examples // batch_size
#定义两个占位符,784是28*28的size,把图像拉长为784的向量,None是批次
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
#test_x = mnist.test.images
#test_y = mnist.test.labels
#创建一个简单的神经网络
W1 = tf.Variable(tf.truncated_normal([784,1000],stddev=0.1))
b1 = tf.Variable(tf.zeros([1,1000]) + 0.1)
L1_output = tf.nn.tanh(tf.matmul(x,W1)+b1)
#keep_prob是有多少概率的神经元在工作
L1_dropout = tf.nn.dropout(L1_output,keep_prob)
W2 = tf.Variable(tf.truncated_normal([1000,10],stddev=0.1))
b2 = tf.Variable(tf.zeros([1,10]) + 0.1)
#分类问题一般需要在输出之后加上一个softmax,让输出的概率相加为1
output = tf.nn.softmax(tf.matmul(L1_dropout,W2)+b2)
#定义二次代价函数
#loss = tf.reduce_mean(tf.square(y-output))
#适合于softmax的对数似然交叉熵函数
loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=output))
lr=0.5
#梯度下降
train = tf.train.GradientDescentOptimizer(lr).minimize(loss)
#初始化
init = tf.global_variables_initializer()
#结果存放在一个布尔型列表中
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(output,1))
#求准确率,cast函数是转换类型从布尔到浮点型,然后求平均
acc = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
with tf.Session() as sess:
sess.run(init)
#每一个epoch都要把所有的图片喂到网络里面
for epoch in range(41):
#每次喂多少个图片
for batch in range(n_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
sess.run(train,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.8})
#train_accuracy = sess.run(acc,feed_dict={x:mnist.train.images,y:mnist.train.labels,keep_prob:1.0})
#print("iter = " + str(epoch) + ",train_acc = " + str(train_accuracy))
#每个epoch结束看下准确率
#if epoch%10 ==0:
test_accuracy = sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
print("iter = " + str(epoch) + ",test_acc = " + str(test_accuracy))
#if epoch%10 == 0:
# lr = 0.1*lr
tensorflow 12 -dropout
最新推荐文章于 2024-01-29 13:53:57 发布