tensorflow中dropout实现手写数字识别

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))



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值