import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
x=tf.placeholder(tf.float32,[None,784],name="x-input")
y=tf.placeholder(tf.float32,[None,10],name="y-input")
drop_place=tf.placeholder(tf.float32)
w1=tf.Variable(tf.truncated_normal([784,100],stddev=0.1))
b1=tf.Variable(tf.zeros([100])+0.1)
layer1=tf.tanh(tf.matmul(x,w1)+b1)
drop1=tf.nn.dropout(layer1,drop_place)
w2=tf.Variable(tf.truncated_normal([100,200],stddev=0.1),name="w2")
b2=tf.Variable(tf.zeros([200])+0.1,name="b2")
layer2=tf.nn.tanh(tf.matmul(drop1,w2)+b2)
drop2=tf.nn.dropout(layer2,drop_place)
w3=tf.Variable(tf.truncated_normal([200,10],stddev=0.1),name="w3")
b3=tf.Variable(tf.zeros([10])+0.1)
logit=tf.nn.softmax(tf.add(tf.matmul(drop2,w3),b3))
loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=logit))
precise=tf.reduce_mean(tf.cast(tf.equal(tf.argmax(logit,1),tf.argmax(y,1)),dtype=tf.float32))
train_step=tf.train.GradientDescentOptimizer(0.01).minimize(loss)
batch_size=1000
mnist=input_data.read_data_sets("MNIST_data",one_hot=True)
n_batch=mnist.train.num_examples // batch_size
with tf.Session() as sess:
init=tf.global_variables_initializer()
sess.run(init)
for i in range(100):
for _ in range(n_batch):
batch_x,batch_y=mnist.train.next_batch(batch_size)
sess.run(train_step,feed_dict={x:batch_x,y:batch_y,drop_place:1.0})
t_loss=sess.run(loss,feed_dict={x:batch_x,y:batch_y,drop_place:1.0})
t_precise=sess.run(precise,feed_dict={x:batch_x,y:batch_y,drop_place:1.0})
print("each-batch-loss:"+str(t_loss))
print("each-batch-precise:"+str(t_precise))
tensorflow中dropout实现手写数字识别
最新推荐文章于 2021-02-26 00:59:00 发布