1. 程式人生 > >TensorFlow實現基礎CNN,兩層卷積+2層全連線網路demo

TensorFlow實現基礎CNN,兩層卷積+2層全連線網路demo

import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data
#載入資料集mnist=input_data.read_data_sets('MNIST_data',one_hot=True)
#每個批次的大小batch_size=50
#共有xx個批次n_batch=mnist.train.num_examples//batch_size
#初始化權重def weight_variable(shape): #生成shape結構的變數,方差=0.1 initial=tf.truncated_normal(shape,stddev
=0.1) return tf.Variable(initial)
#初始化偏置def bias_variable(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')


#定義變數等x=tf.placeholder(tf.float32,[None,784])y=tf.placeholder(tf.float32,[None,10])
#將一維的圖片資料轉化為2維/張x_image=tf.reshape(x,[-1,28,28,1])
#開始寫我們的第一層卷積層#初始化第一層的權重,第一層的權重應該為5*5*32的,在一通道的影象上採集#初始化第一層的偏置,第一層的偏置應與第一層卷積核數一致#得到第一層的卷積輸出,=用32個卷積核分別對其迴圈相乘在相加#進行第一層的池化,池化採用2*2的卷積核,採用samepadding的方式進行池化
W_conv1=weight_variable([5,5,1,32])B_conv1=bias_variable([32])h_conv1=tf.nn.relu(conv2d(x_image,W_conv1)+B_conv1)h_pool1=max_pool_2x2(h_conv1)
#第2層的卷積W_conv2=weight_variable([5,5,32,64])B_conv2=bias_variable([64])h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+B_conv2)h_pool2=max_pool_2x2(h_conv2)

#使用全連線神經網路進行訓練#經過第一層卷積池化之後得到14*14*32#經過第二層卷積池化之後得到7*7*64,通道數為64
#定義神經網路,輸入為7*7*64,第一層隱藏層採用1024個神經元#初始化第一層的權重W_nn1=weight_variable([7*7*64,1024])B_nn1=bias_variable([1024])
#此時將我們的輸出展開為1維,以方便神經網路進行計算h_x_flat=tf.reshape(h_pool2,[-1,7*7*64])
#進行神經網路計算,h_nn1為第一層隱藏層的輸出h_nn1=tf.nn.relu(tf.matmul(h_x_flat,W_nn1)+B_nn1)

#進行dropout處理keep_props=tf.placeholder(tf.float32)h_nn1=tf.nn.dropout(h_nn1,keep_props)

#第二層神經層W_nn2=weight_variable([1024,10])B_nn2=bias_variable([10])h_nn2=tf.nn.relu(tf.matmul(h_nn1,W_nn2)+B_nn2)
#得到神經網路的預測結果h_nn2
#定義神經網路代價函式cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=h_nn2))
#定義優化器train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#預測結果和正確結果的比對correct_prediction=tf.equal(tf.argmax(h_nn2,1),tf.argmax(y,1))
#求準確率accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

#進行迴圈反向傳遞
with tf.Session() as sess: sess.run(tf.global_variables_initializer()) for i in range(21): for batch in range(n_batch): x_batch,y_batch=mnist.train.next_batch(batch_size) sess.run(train_step,feed_dict={x:x_batch,y:y_batch,keep_props:0.7}) acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_props:1}) print('iter {0}, acc={1}'.format(i,acc))