mnist = input_data.read_data_sets('MNIST_data',one_hot=True) batch_size = 100n_batch = mnist.train.num_examples // batch_size x =tf.placeholder(tf.float32,([None,784])) y =tf.placeholder(tf.float32,([None,10])) weight = tf.Variable(tf.truncated_normal([784,100],stddev=0.2)) bias = tf.Variable(tf.zeros([1,100])+0.1) output1 = tf.nn.tanh(tf.matmul(x,weight)+bias) weight3 = tf.Variable(tf.truncated_normal([100,100],stddev=0.2)) bias3 = tf.Variable(tf.zeros([1,100])+0.1) output = tf.nn.relu(tf.matmul(output1,weight3)+bias3) weight2 = tf.Variable(tf.truncated_normal([100,10],stddev=0.2)) bias2 = tf.Variable(tf.zeros([1,10])+0.1)# predict = tf.nn.softmax(tf.matmul(output,weight2)+bias2)predict = tf.matmul(output,weight2)+bias2# loss = tf.reduce_mean(tf.square(predict-y))loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=predict,labels=y)) train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) correct = tf.equal(tf.argmax(y,1),tf.argmax(predict,1)) accuracy = tf.reduce_mean(tf.cast(correct,tf.float32))with tf.Session(config=config) as sess: sess.run(tf.global_variables_initializer()) for epoch in range(21): for i in range(n_batch): x_data,y_data = mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:x_data,y:y_data}) acc = sess.run(accuracy, feed_dict={x: mnist.train.images, y: mnist.train.labels}) print('train-acc' + str(acc)) acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print('test-acc'+str(acc))
测试结果:
train-acc 0.9999273
test-acc 0.9717
版本2:
import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets('./MNIST_data',one_hot=True) batch_size = 100batch = mnist.train.num_examples//batch_size x = tf.placeholder(tf.float32,[None,28*28]) y = tf.placeholder(tf.float32,[None,10]) l1 = tf.layers.dense(x,1000) l2 = tf.nn.sigmoid(l1) l2 = tf.layers.dense(x,500,activation='relu')# l2 = tf.layers.dropout(l2,rate=0.2)l3 = tf.layers.dense(x,50,activation='relu') pre = tf.layers.dense(l3,10) loss = tf.nn.softmax_cross_entropy_with_logits(logits=pre,labels=y) train = tf.train.GradientDescentOptimizer(0.001).minimize(loss) accrate = tf.equal(tf.argmax(y,1),tf.argmax(pre,1)) acc = tf.reduce_mean(tf.cast(accrate,tf.float32))with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for j in range(20): for i in range(batch): x_data,y_data = mnist.train.next_batch(batch_size) sess.run(train,feed_dict={x:x_data,y:y_data}) if i %10 ==0: print('train',sess.run(acc, feed_dict={x: x_data, y: y_data})) # print('test',sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels})) print('test', sess.run(acc, feed_dict={x: mnist.test.images, y: mnist.test.labels}))
结果: test 0.9727
作者:米特尼克大粉丝
链接:https://www.jianshu.com/p/800df125b906
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦