Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import tensorflow as tf
- from tensorflow.examples.tutorials.mnist import input_data
- keep_prob=tf.placeholder(tf.float32)
- def evaluation(logits, labels):
- correct = tf.nn.in_top_k(logits, labels, 1)
- return tf.reduce_sum(tf.cast(correct, tf.int32))
- mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
- xs=tf.placeholder(tf.float32,[None,784])
- ys=tf.placeholder(tf.float32,[None,10])
- x_image = tf.reshape(xs,[-1,28,28,1])
- #===================================================
- def weight_v(shape):
- initial = tf.truncated_normal(shape,stddev=0.1)
- return tf.Variable(initial)
- def bias_v(shape):
- initial = tf.constant(0.1,shape=shape)
- return tf.Variable(initial)
- def conv2d(x,W):
- return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
- def max_pool_2x2(x):
- return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
- #----------------------L1--------------------------
- W_conv1 = weight_v([5,5,1,64])
- b_conv1 = bias_v([64])
- hid_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)
- hid_pool1 = max_pool_2x2(hid_conv1)
- #----------------------L2---------------------------
- W_conv2 = weight_v([5,5,64,128])
- b_conv2 = bias_v([128])
- hid_conv2 = tf.nn.relu(conv2d(hid_pool1,W_conv2)+b_conv2)
- hid_pool2 = max_pool_2x2(hid_conv2)
- #---------------------------------------------------
- W_fc1 = weight_v([7*7*128,1024])
- b_fc1 = bias_v([1024])
- hid_pool2flat = tf.reshape(hid_pool2,[-1,7*7*128])
- hid_fc1 = tf.nn.relu(tf.matmul(hid_pool2flat,W_fc1)+b_fc1)
- hid_fc1_dropout = tf.nn.dropout(hid_fc1,keep_prob=1.0)
- #---------------------------------------------------
- W_fc2 = weight_v([1024,10])
- b_fc2 = bias_v([10])
- prediction = tf.nn.softmax(tf.matmul(hid_fc1_dropout,W_fc2)+b_fc2)
- #=================================================================
- cross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))
- #loss
- train=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
- #saver = tf.train.Saver()
- #===================================================
- def accuracy(v_xs,v_ys):
- global prediction
- y_pre=sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1.0})
- judge=tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))
- acc=tf.reduce_mean(tf.cast(judge,tf.float32))
- result=sess.run(acc,feed_dict={xs:v_xs,ys:v_ys,keep_prob:1.0})
- return result
- #===================================================
- with tf.Session() as sess:
- sess.run(tf.global_variables_initializer())
- for i in range(0,1000):
- batch_xs,batch_ys=mnist.train.next_batch(50)
- sess.run(train,feed_dict={xs:batch_xs,ys:batch_ys,keep_prob:0.5})
- if i%20==0:
- print(i,accuracy(mnist.test.images[:1000],mnist.test.labels[:1000]))
- # save_path = saver.save(sess,"/home/ky/test/model/cnn.ckpt")
Add Comment
Please, Sign In to add comment