tensorflow基礎學習:CNN(卷積神經網絡)打造手寫數字識別詳細教程

開發平臺:win10+py3.6 64bit + tensorflow-gpu == 1.9.0版本

使用的工具以及庫:

  • pycharm(全宇宙唯一一款專門用做python開發的工具)功能強大
  • tensorflow-gpu 1.9 (win10下配置gpu環境過程多坑,配置教程看我另一篇博客)
  • tensorflow cpu版不太建議,很慢很燙,是真的慢真的燙
    在這裏插入圖片描述

先看看訓練的tensorboard的圖

在這裏插入圖片描述

在這裏插入圖片描述

詳細解釋看代碼註釋

  1. 準備工作
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 載入數據集,路徑要找對自己的,數據集我的博客另外一片有下載鏈接
mnist = input_data.read_data_sets("../../tensorflow_code/mnist/", one_hot=True)

# 設置沒批次的樣本數據大小
batch_size = 50

# 定義一個學習率佔位符,用於後面隨着訓練的次數增加來修改學習率,以便於更加好收斂
learn_rate = tf.placeholder(tf.float32)
# 學習率
# 初始值設置爲0.15
rate = 0.15

# 計算一共有多少個批次, 後面好像也沒有用它
n_batch = mnist.train.num_examples // batch_size
  1. 把隨機生成權重,和偏置封裝成函數
def weight_variable(shape, name=None):
    """
    輸入數據類型,隨機初始化值返回
    :param shape: [] 類型
    :param name: 起的名字
    :return: 隨機初始化的值
    """

    initial = tf.random_normal(shape=shape, stddev=0.1, name=name)
    # 轉化爲tf.的變量類型纔可以跟着訓練改變,優化
    return tf.Variable(initial)



def bias_variable(shape, name):
	''' 初始化偏置 '''
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)

3.第一層:卷積,激活,池化

經過第一層卷積池化:
卷積:就是窗口的每一個像素值乘於窗口的權重
5*5的採樣窗口,32窗口卷積,x,y 步長爲1
對於一張圖片來說: 28 x 28 x 1
最後得到:32張 28 x 28 的圖,因爲步長全部爲1

  • 卷積層
def conv2(x, W):
	'''卷積層,以爲圖片是2維的,所以使用2維的api tf.nn.conv2d()
    x: 輸入的圖片數據的類型[batch(樣本數), height(圖片高), width(圖片寬), channels(圖片RGB通道數)]
    W filter: 卷積內核的shape [filter_height, filter_width, in_channels, out_channels(輸出多少張表)]
    strides[0]:樣本圖片, strides[3]:RGB通道,這兩個一般選1, 一般不會跨圖片,跨通道,去卷積計算得到一張表
    strides[1]代表x方向的步長,strides[2]代表y方向的步長
   padding:  一般選"SAME"(不夠就補零), "VALID"(不夠就跳過)
    '''
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
  • 激活函數選擇relu函數(大於0就是本身,小於0就改爲0)

  • 池化
    max池化:取窗口裏面最大的像素值代替這個區
    ksize: 池化窗口的size [1, 2, 2, 1], 表示,池化窗口爲 2 x 2 池化(一張一張圖片 通道數也是一個一個來, 這兩個絕大部分都是1)
    strides : 類似上面,步長x上面是2, y上面也是2
    2828,池化後就成了 1414 ,也有32張
    也就是傳入第2次卷積你覺得數據爲
    [None, 14, 14, 32]

# 池化層
def max_pool_2x2(x):
    # ksize [1,x,y,1]
    return tf.nn.max_pool(value=x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

開始搭建第一層卷積網絡


with tf.name_scope("input_data"):
    # 定義兩個placeholder
    # 輸入值的特徵值784
    x = tf.placeholder(tf.float32, [None, 784], name="x")
    # 目標值 10個類別
    y = tf.placeholder(tf.float32, [None, 10], name='y')

    with tf.name_scope('x_image'):
        # 改變x的格式轉爲4D的向量[batch, in_height, in_width, in_channels]`
        x_image = tf.reshape(x, [-1, 28, 28, 1], name="x_image")

with tf.name_scope('Conv1'):
    # 初始化第一個卷積層的權值和偏置

    with tf.name_scope('W_conv1'):
        # 隨機生成 5*5的採樣窗口,黑白圖片,一個輸入通道, 16個輸出通道,16個卷積核從1個平面抽取特徵,得到16張特徵表

        W_conv1 = weight_variable([5, 5, 1, 16], name='W_conv1')

    with tf.name_scope('b_conv1'):
        # # 每一個卷積核一個偏置值
        b_conv1 = bias_variable([16], name='b_conv1')

    # 把x_image和權值向量進行卷積,再加上偏置值,然後應用於relu激活函數
    with tf.name_scope('conv2d_1'):
        # conv2d_1 = [None, 28, 28, 16]
        conv2d_1 = conv2(x_image, W_conv1) + b_conv1

    # 使用relu激活函數,激活再經過池化
    with tf.name_scope('relu'):
        # relu: 小於0取0, 大於0取自己,像素值沒有小於0的
        h_conv1 = tf.nn.relu(conv2d_1)

    with tf.name_scope('h_pool1'):
        # 進行max-pooling
        # tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')
        # max_pool.池化就是取小框裏面最大值代替這個框的值
        # ksize: 池化窗口的size [1, 2, 2, 1], 表示,池化窗口爲 2*2 池化(一張一張圖片 通道數也是一個一個來, 這兩個絕大部分都是1)
        # strides : 類似上面,步長x上面是2, y上面也是2
        # h_pool1 = [None, 14, 14, 16]
        h_pool1 = max_pool_2x2(h_conv1)


  1. 第二層卷積
ith tf.name_scope('Conv2'):
    # 初始化第二個卷積層的權值和偏置
    with tf.name_scope('W_conv2'):
        W_conv2 = weight_variable([5, 5, 16, 32], name='W_conv2')  # 5*5的採樣窗口,32個卷積核從16個平面抽取特徵
    with tf.name_scope('b_conv2'):
        b_conv2 = bias_variable([32], name='b_conv2')  # 每一個卷積核一個偏置值

    # 把h_pool1和權值向量進行卷積,再加上偏置值,然後應用於relu激活函數
    with tf.name_scope('conv2d_2'):
        # conv2d_2 = [None, 14, 14, 32]
        conv2d_2 = conv2(h_pool1, W_conv2) + b_conv2
    with tf.name_scope('relu'):
        h_conv2 = tf.nn.relu(conv2d_2)
    with tf.name_scope('h_pool2'):
        # h_pool2 = [None, 7, 7, 32]
        h_pool2 = max_pool_2x2(h_conv2)  # 進行max-pooling

# 28*28的圖片第一次卷積後還是28*28,第一次池化後變爲14*14
# 第二次卷積後爲14*14,第二次池化後變爲了7*7
# 進過上面操作後得到64張7*7的平面
# 輸出的爲[None,7,7,64]
  1. 第一層全連接層網絡
with tf.name_scope("fc1"):
    # 初始化第一個全連接層的權值

    with tf.name_scope('W_fc1'):
        #  輸入爲[None,7,7,64], 用1024個神經元運算
        # 上一層有7*7*64個神經元,全連接層有1024個神經元
        W_fc1 = weight_variable([7 * 7 * 32, 32], name='W_fc1')

    # 1024個神經元就有1024個偏置
    with tf.name_scope('b_fc1'):
        b_fc1 = bias_variable([32], name='b_fc1')  # 1024個節點

    # 把池化層2的輸出扁平化爲1維
    with tf.name_scope('h_pool2_flat'):
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 32], name='h_pool2_flat')

    # 求第一個全連接層的輸出,輸入 X 權值 + bias
    with tf.name_scope('wx_plus_b1'):
        wx_plus_b1 = tf.matmul(h_pool2_flat, W_fc1) + b_fc1

    # 激活函數
    with tf.name_scope('relu'):
        h_fc1 = tf.nn.relu(wx_plus_b1)

    # keep_prob用來表示神經元的輸出概率
    # 控制一部分的神經元在運作
    """
    目的:防止過擬合。
    在數據量很大的時候,每批次都讓所有的權重參加訓練更新數值,
    最後可能有些還沒訓練夠,有些就過擬合了

    讓某個神經元的激活值以一定的概率p,讓其停止工作,這次訓練過程中不更新權值,
    也不參加神經網絡的計算。但是它的權重得保留下來(只是暫時不更新而已),
    因爲下次樣本輸入時它可能又得工作了.
    但在測試及驗證中:每個神經元都要參加運算,但其輸出要乘以概率p。

    """

    # 定義佔位符
    with tf.name_scope('keep_prob'):
        keep_prob = tf.placeholder(tf.float32, name='keep_prob')

    # keep_prob:0.7,就是讓70%的神經元再更新參數
    with tf.name_scope('h_fc1_drop'):
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='h_fc1_drop')

  1. 第二層全連接層

with tf.name_scope("fc2"):
    # 上一層輸入爲 [None, 1024]
    # 這一層要求輸出[None, 10],因爲有 10 個數字類別
    # 故要求weigh = [1024, 10], bias = [10]
    # 初始化第2個全連接層

    with tf.name_scope('w_fc2'):
        w_fc2 = weight_variable([32, 10], name="w_fc2")
        # 收集最後一層的權值分佈
        tf.summary.histogram("w_fc2",w_fc2)

    with tf.name_scope("b_fc2"):
        b_fc2 = bias_variable(shape=[10], name="b_fc2")
        tf.summary.histogram("b_fc2", b_fc2)


    # 輸入的數據於權值相乘 + bias
    with tf.name_scope("wx_plus_b2"):
        wx_plus_b2 = tf.matmul(h_fc1_drop, w_fc2) + b_fc2

    # 計算輸出每一個類別的概率
    with tf.name_scope("softmax"):
        prediction = tf.nn.softmax(wx_plus_b2)

  1. loss函數以及優化器
# 計算交叉熵損失函數
with tf.name_scope("loss"):
    # 輸入真實值跟預測值
    loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction), name="loss")

    # 收集損失函數的變化
    tf.summary.scalar("loss", loss)

# 使用AdamOptimizer進行優化
# with tf.name_scope('train'):
#     train_step = tf.train.AdamOptimizer(0.01).minimize(loss)

# 使用梯度下降優化器
with tf.name_scope('train'):
    train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)

  • 準確率
# 計算準確率
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        # 結果存放在一個布爾列表中, [None, 10]
        correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))  # argmax返回一維張量中最大的值所在的位置
    with tf.name_scope('accuracy'):
        # 求準確率
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        tf.summary.scalar('accuracy', accuracy)


  • 開始訓練,保存模型
# 合併所有的summary
merged = tf.summary.merge_all()

# 最後開啓會話進行訓練

with tf.Session() as sess:
    # 初始化所有的變量
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter("F:/mnist/model/train/", graph=sess.graph)
    test_writer = tf.summary.FileWriter("F:/mnist/model/test/", graph=sess.graph)

    for i in range(1000):
        # 開始訓練模型
        # 訓練模型
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 0.5, learn_rate: rate})

        # 記錄訓練集計算的參數
        summary = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.0, learn_rate: rate})
        train_writer.add_summary(summary, i)

        # 記錄測試集計算的參數
        batch_xs, batch_ys = mnist.test.next_batch(batch_size)
        summary = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob: 1.0, learn_rate: rate})
        test_writer.add_summary(summary, i)

        if i % 100 == 0:
            # 每50次下降一點學習率
            rate = rate * 0.93
            test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels, keep_prob: 1.0, learn_rate: rate})
            train_acc = sess.run(accuracy, feed_dict={x: mnist.train.images[:10000], y: mnist.train.labels[:10000],
                                                      keep_prob: 1.0})
            print("Iter " + str(i) + ", Testing Accuracy= " + str(test_acc) + ", Training Accuracy= " + str(train_acc))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章