###CNN###
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data'''這些是tf1.*版本,現在我已經升級到2.0版本,上方數據集都用不了了...''''''黑白圖片,因此這里使用的是2D'''mnist=input_data.read_data_sets("MNIST_data",one_hot=True)batch_size=100 n_batch=mnist.train.num_examples//batch_sizetf=tf.compat.v1#初始化權值(這樣初始化真的很重要) def weight_variable(shape):initial=tf.truncated_normal(shape=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):#x:輸入 【batch,in_height,in_width,in_channels(通道數)】#W:濾波器#strides:步長#padding:個人選擇:SAME/VALIDreturn tf.nn.conv2d(x,W,strides=[1,1,1,1],padding="SAME")#池化層 def max_pool_2x2(x):#ksize=[1 x y 1] #步長2return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')#用max_pool2d也是可以的 x=tf.placeholder(tf.float32,[None,784]) y=tf.placeholder(tf.float32,[None,10])#改變x的格式轉為4D的向量[batch,in_height,in_width,in_channels] x_image=tf.reshape(x,[-1,28,28,1])#-1還是那個意思,就是輸入的個數不確定,讓它自行計算是多少#初始化第一個卷積層的權值和偏置 W_conv1=weight_variable([5,5,1,32])#5*5采樣窗口,32個卷積核從1個平面抽取特征(從一個平面提取32個特征平面)【就是生成1D的32個卷積核,分別進行卷積,從而1個平面得到32個卷積特征平面】 b_conv1=bias_variable([32])#給這個卷積核設置一個偏置值#把x_image和權值向量進行卷積,再加上偏置值,然后應用relu激活函數 h_cov1=tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#利用平面(2D)卷積進行卷積,并加一個偏置,得到批次*32個平面的 h_pool1=max_pool_2x2(h_cov1)#進行max-pooling#初始化第二個卷積層的權值和偏置 W_conv2=weight_variable([5,5,32,64])#5*5采樣窗口,64個卷積核從32個平面抽取特征(從32個平面提取64個特征平面)【生成32D的64個卷積核,分別進行卷積,從而得到1個包含64個卷積平面】 b_conv2=bias_variable([64])#么個卷積核設置一個偏置值#把h_pool1和權值向量進行卷積,再加上偏置值,然后應用relu激活函數 h_cov2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2) h_pool2=max_pool_2x2(h_cov2)#進行max-pooling#28*28的圖片第一次卷積后還是28*28,第一次初花后變成14*14 #第二次卷積后14*14,第二次池化后變成7*7 #上方操作完后的得到64張7*7的平面'''下方就是正常的神經網絡(全連接)'''#初始化第一個全連接層的權值 W_fc1=weight_variable([7*7*64,1024])#上一層有7*7*64個神經元,全連接層有1024個神經元 b_cf1=bias_variable([1,1024])#將池化層2的輸出扁平化為1維 h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])#100,7*7*64 #求第一個全連接層的輸出 h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_cf1)#keep_prob用來表示神經元的輸出概率 keep_prob=tf.placeholder(tf.float32) h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)#初始化第二個全連接層 W_fc2=weight_variable([1024,10]) b_cf2=bias_variable([1,10])#計算輸出 prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_cf2)#交叉熵代價函數 cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) #優化器 train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)#結果存放在一個布爾列表中 correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))acc=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):batch_x,batch_y=mnist.train.next_batch(batch_size)sess.run(train_step,feed_dict={x:batch_x,y:batch_y,keep_prob:0.7})accuracy=sess.run(acc,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})print("第"+str(i+1)+"次迭代準確率為:"+str(accuracy))
?
###RNN###
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_datamnist=input_data.read_data_sets("MNIST_data",one_hot=True)tf=tf.compat.v1#輸入圖片是28*28 n_input=28#輸入一行,一行有28個數據 max_time=28#一共28行 lstm_size=100#隱藏單元 n_classes=10#10個分類 batch_size=50#m每個批次50個樣本 n_batch=mnist.train.num_examples//batch_size#一共有多少個批次 x=tf.placeholder(tf.float32,[None,784]) y=tf.placeholder(tf.float32,[None,10])'''下方權重是隱藏層和輸出層之間的權重和偏置''' #初始化權值 weights=tf.Variable(tf.truncated_normal([lstm_size,n_classes],stddev=0.1)) #初始化偏置值 biases=tf.Variable(tf.constant(0.1,shape=[1,n_classes]))#定義RNN網絡 def RNN(x,weights,biases):#inputs=[batch_size,max_time,n_input]>>[batch_size,in_height,in_width]inputs=tf.reshape(x,[-1,max_time,n_input])#定義LSTM基本CELLlstm_Cell=tf.nn.rnn_cell.BasicLSTMCell(lstm_size)#每個隱藏層中都會有一個cell#final_state[0]是cell_state#final_state[1]是hidden_state 由34行可見該形狀為 ?*100(隱藏單元個數) 由返回值prediction可知results它與y形狀相同(50,10) 所以他的形狀為50(batch_size)*100(隱藏單元個數)outputs,final_state=tf.nn.dynamic_rnn(lstm_Cell,inputs,dtype=tf.float32)results=tf.nn.softmax(tf.matmul(final_state[1],weights)+biases)#經過softmax轉化為概率顯示return results#計算RNN返回結果 prediction=RNN(x,weights,biases) #損失函數 cross_entropy=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction,labels=y)) #使用Adam優化器 train_step=tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)correct_prediction=tf.equal(tf.argmax(y,1),tf.argmax(prediction,1)) accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))init=tf.global_variables_initializer()with tf.Session() as sess:sess.run(init)for i in range(21):for j 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})acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels})print("第"+str(i+1)+"次迭代準確率為:"+str(acc))
?