1. 程式人生 > >神經網絡2:卷積神經網絡學習 1

神經網絡2:卷積神經網絡學習 1

常量 兩個 acc reduce 大小 ges 需要 tutorial 但是

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets(MNIST_data, one_hot=True)

sess = tf.Session()
# 定義 tensorflow 特有的占位符
# xs 定義為 【行數未定,但784列】;
# 原理在於圖片是28*28=784 即把二維形式的圖片,用一維向量表示,None 表示圖片的個數,即一行代表一個圖片
xs = tf.placeholder(dtype=tf.float32, shape=[None, 784])
# xs 定義為 【行數未定,但10列】 # 10 列表示0到9 這幾個數,None 表示圖片的個數,即每行代表一個圖片對應的label ys = tf.placeholder(dtype=tf.float32, shape=[None, 10]) keep_prob = tf.placeholder(dtype=tf.float32) # 定義計算預測準確度的函數 def compute_accuracy(v_xs, v_ys): global prediction ‘‘‘本函數由兩個sess.run()構成‘‘‘ """該部分計算預測值""" y_re = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1})
"""該部分計算預測的準確度""" # tf.argmax() 返回最大值的索引,axis =1 表示行方向的 # 因為 y_pre 是預測值,v_ys 是實際值 所以通過argmax 返回行方向上的最大值, # 使用tf.equal 比較同一位置的值是否相等 返回的是[True,True,False,True ...] correct_prediction = tf.equal(tf.argmax(input=y_re, axis=1), tf.argmax(input=v_ys, axis=1)) # 使用tf.cast將tf.equal的返回值轉為float [1.0,1.0,0.0,1.0 ...]
# 再使用tf.reduce_mean 計算平均值 accuracy = tf.reduce_mean(tf.cast(x=correct_prediction, dtype=tf.float32)) result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1}) return result # 定義一個初始化權值的函數 def weight_variable(shape): # 截尾正太分布 的隨機數 stddev 標準差 initial = tf.truncated_normal(shape=shape, stddev=0.1) return tf.Variable(initial) # 定義一個初始化偏置量的函數 def bias_variable(shape): # 值為0.1 的常量 initial = tf.constant(value=0.1, shape=shape) return tf.Variable(initial) # 定義卷積層函數 def conv2d(input, Weight): # input 為輸入的數據 # Weight 為權值, filter # strides 為步長,四個值的意思分別是:樣本的步長,1 表示每個樣本都作為輸入 # 高度的步長,1 表示每次在高度上移動一個單位 # 寬度的步長,1 表示每次在寬度上移動一個單位 # 通道的步長,或者說是厚度上的步長,1,表示每次移動一個 # padding 有兩種取值 SAME VALID,使用SAME會對輸入的數據進行0補,也就是移動的步數不會丟失 # 取VALID,則不進行補0,可能會導致移動步數丟失 # 如 長度為10的,用一個長度為3的在上面每次移動一個 # 使用SAME,因為需要補0,所以最後需要移動10次 # 使用VALID,則移動8次就無法再移動【出界了】 return tf.nn.conv2d(input=input, filter=Weight, strides=[1, 1, 1, 1], padding=SAME) # 定義池化層函數 def max_pool_2x2(input): # 池化層的目的是在降低數據量,就是用一顆數據來表示一整塊數據 # 這裏使用最大值池化 # ksize 表示池化範圍的大小;四個參數的意義與上述相同 # strides 步長 return tf.nn.max_pool(value=input, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=SAME) ‘‘‘‘‘‘ # 將數據xs reshape 成個數未定,長寬28*28,厚度 為1 的數據類型 x_input = tf.reshape(tensor=xs, shape=[-1, 28, 28, 1]) """第一層卷積計算 start""" ‘‘‘先初始化權值和偏置參數‘‘‘ # shape = [5,5,1,32] 的意思是 filter 的大小是5*5的,用於輸入厚度為1,輸出厚度為32 W_conv1 = weight_variable(shape=[5, 5, 1, 32]) b_conv1 = bias_variable([32]) ‘‘‘真正的計算‘‘‘ # 輸入 x_input 28*28*1 # 輸出的 h_conv1 28*28*32 # 使用了relu 激活函數;激活函數有很多種,其作用是為了去線性化 h_conv1 = tf.nn.relu(conv2d(x_input, W_conv1) + b_conv1) # 池化層 # 使用最大值池化 輸入為28*28*32 # 輸出為14*14*32 池化層的目的就是為了縮小特征的(個人理解) h_pool1 = max_pool_2x2(h_conv1) """第一層卷積計算 end""" """第二層卷積計算 start""" # 因為第二層卷積的輸入為第一層的輸出,14*14*32 # 因此 權值為5*5 輸入為32厚度,輸出為64 厚度 W_conv2 = weight_variable(shape=[5, 5, 32, 64]) b_conv2 = bias_variable(shape=[64]) # 輸入為14*14*32 # 輸出為 14*14*64 h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) # 輸出為 7*7*64 h_pool2 = max_pool_2x2(h_conv2) """第二層卷積計算 end""" """全連接層1 start""" # 7*7*64 是要輸入的數數據 # 1024 是神經元的個數 # 也就是經過上次池化層最後的結果為7*7*64 的圖片,與1024個神經元的全連接 需要的權值矩陣,其權值個數為矩陣中元素的個數 W_fc1 = weight_variable([7 * 7 * 64, 1024]) # 每個神經元需要一個偏置 b_fc1 = bias_variable([1024]) # reshape 未知行數,每行代表一個圖片全部的特征,7*7*64 h_pool2_flat = tf.reshape(tensor=h_pool2, shape=[-1, 7 * 7 * 64]) # 輸入 n*(7*7*64) (7*7*64)*1024 # 輸出 n*1024 h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # 防止過擬合的dropout方法 h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob) """全連接層2 start""" W_fc2 = weight_variable(shape=[1024, 10]) b_fc2 = bias_variable([10]) # matmul 輸入:n*1024 2014*10 # 輸出:n*10 # softmax 的輸入為:n*10 # 輸出為: prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2) """全連接層2 end""" ‘‘‘ 上述已將網絡搭建完成 但是尚不能進行持續性的學習 原因:學習需要有一個學習的目標,在機器學習中也需要刻畫一個目標 常用的刻畫方式就是:找到一個損失函數,學習的目標就是不斷的最小化損失函數值 或者找到一個效用函數,不斷的最大化效用函數值 ‘‘‘ cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1])) # loss train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) sess.run(tf.global_variables_initializer()) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5}) if i % 50 == 0: print(compute_accuracy( mnist.test.images, mnist.test.labels))

神經網絡2:卷積神經網絡學習 1