標籤:

TensorFlow下簡單的卷積網路實現

import tensorflow as tfnfrom tensorflow.examples.tutorials.mnist import input_datannmnist = input_data.read_data_sets("MINIST_data/",one_hot=True)nsess = tf.InteractiveSession()nndef weight_variable(shape):ntinital = tf.truncated_normal(shape,stddev=0.1)ntreturn initalntndef bias_variable(shape):ntinital = tf.constant(0.1,shape=shape)ntreturn tf.Variable(inital)ntndef conv2d(x,W):ntreturn tf.nn.conv2d(x,W,strides=[1,1,1,1],padding=SAME)ntndef max_pool_2x2(x):ntreturn tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding=SAME)ntnif __name__ == "__main__":ntx = tf.placeholder(tf.float32,[None,784])nty_ = tf.placeholder(tf.float32,[None,10])ntx_image = tf.reshape(x,[-1,28,28,1]) # 28*28ntnt# first floorntw_conv1 = weight_variable([5,5,1,32])ntb_conv1 = bias_variable([32])nth_conv1 = tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)t# 28*28*32nth_pool1 = max_pool_2x2(h_conv1) #14*14*32ntnt# second floorntw_conv2 = weight_variable([5,5,32,64]) ntb_conv2 = bias_variable([64])nth_conv2 = tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2) # 14*14*64nth_pool2 = max_pool_2x2(h_conv2) # 7*7*64ntnt# full connectionntw_fc1 = weight_variable([7*7*64,1024]) ntb_fc1 = bias_variable([1024])nth_bool2_flat = tf.reshape(h_pool2,[-1,7*7*64])nth_fc1 = tf.nn.relu(tf.matmul(h_bool2_flat,w_fc1)+b_fc1)ntnt# dropoutntkeep_prob = tf.placeholder(tf.float32)nth_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)ntnt# softmaxntw_fc2 = weight_variable([1024,10])ntb_fc2 = bias_variable([10])nty_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)ntnt# cost functionntcross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y_conv),reduction_indices=[1]))nttrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)nty_conv = tf.nn.softmax(tf.matmul(h_fc1_drop,w_fc2)+b_fc2)ntntcorrect_prediction = tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))ntaccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))ntnttf.global_variables_initializer().run()ntntfor i in range(20000):nttbatch = mnist.train.next_batch(50)nttif i%50 == 0:nttttrain_accuracy = accuracy.eval(feed_dict={x:batch[0],y_:batch[1],keep_prob:1})ntttprint("step %d,training accuracy %g" % (i,train_accuracy))ntttrain_step.run(feed_dict={x:batch[0],y_:batch[1],keep_prob:0.5})ntntprint("test accuracy %g" % accuracy.eval(feed_dict={x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))n


推薦閱讀:

如何看待Face++出品的小型化網路ShuffleNet?
用tf.placeholder構建features, labels容器
為什麼在windows下用不了tensorflow?
深度卷積GAN之圖像生成
深入淺出Tensorflow(四):卷積神經網路

TAG:TensorFlow |