1. 程式人生 > >TensorFlow學習筆記(2)——CNN應用於MNIST

TensorFlow學習筆記(2)——CNN應用於MNIST

對於一個卷積網路來說,幾個必不可少的部分為:

  1. 輸入層:用以對資料進行輸入
  2. 卷積層:使用給定的核函式對輸入的資料進行特徵提取,並根據核函式的資料產生若干個卷積特徵結果
  3. 池化層:用以對資料進行降維,減少資料的特徵
  4. 全連線層:對資料已有的特徵進行重新提取並輸出結果

程式碼示例

1、資料準備

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

# 宣告輸入圖片資料,類別
x = tf.placeholder('float'
, [None, 784]) y_ = tf.placeholder('float', [None, 10]) # 輸入圖片資料轉化 x_image = tf.reshape(x, [-1, 28, 28, 1])

2、卷積層、池化層

在程式中首先建立兩個卷積層,TensorFlow中將卷積層已經實現並封裝完畢,其他人只需要呼叫即可。

# 第一層卷積層,初始化卷積核引數、偏置值,該卷積層5*5大小,一個通道,共有6個不同卷積核
filter1 = tf.Variable(tf.truncated_normal([5, 5, 1, 6]))
bias1 = tf.Variable(tf.truncated_normal([6]))
conv1
= tf.nn.conv2d(x_image, filter1, strides=[1, 1, 1, 1], padding='SAME') h_conv1 = tf.nn.sigmoid(conv1 + bias1) maxPool2 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') filter2 = tf.Variable(tf.truncated_normal([5, 5, 6, 16])) bias2 = tf.Variable(tf.truncated_normal([16])) conv2
= tf.nn.conv2d(maxPool2, filter2, strides=[1, 1, 1, 1], padding='SAME') h_conv2 = tf.nn.sigmoid(conv2 + bias2) maxPool3 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') filter3 = tf.Variable(tf.truncated_normal([5, 5, 16, 120])) bias3 = tf.Variable(tf.truncated_normal([120])) conv3 = tf.nn.conv2d(maxPool3, filter3, strides=[1, 1, 1, 1],padding='SAME') h_conv3 = tf.nn.sigmoid(conv3 + bias3)

程式碼段先定義了卷積核w_conv,其中的四個引數[5,5,1,6],前兩者引數5,5是卷積核的大小,代表卷積核是一個[5,5]的矩陣所構成,而第三個引數是輸入的資料通道,第四個引數即為輸出的資料通道(卷積核的個數)
在這裡, ksize=[1, 2, 2, 1]指的是池化矩陣的大小,即使用[2,2]的矩陣,而第三個引數strides=[1, 2, 2, 1]指的是池化層在每一維度上滑動的步長。
通過第一個卷積層和池化層,輸入的資料被轉化成[None,7,7,120](兩次池化每次size縮小兩倍)的大小的新的資料集,之後再通過一次全連線層對資料進行重新分類。

3.全連線層

# 全連線層
# 權值引數
W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 120, 80]))
# 偏置值
b_fc1 = tf.Variable(tf.truncated_normal([80]))
# 將卷積的產出展開
h_pool2_flat = tf.reshape(h_conv3,[-1, 7 * 7 * 120])
# 神經網路計算,並新增sigmoid啟用函式
h_fc1 = tf.nn.sigmoid(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# 輸出層,使用softmax進行多分類
W_fc2 = tf.Variable(tf.truncated_normal([80,10]))
b_fc2 = tf.Variable(tf.truncated_normal([10]))
y_conv = tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)

4、計算損失值

cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))

5、初始化optimizer

train_step = tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)

6、指定迭代次數,並在session執行graph

# tf.InteractiveSession():它能讓你在執行圖的時候,插入一些計算圖,
# 這些計算圖是由某些操作(operations)構成的。這對於工作在互動式環境中的人們來說非常便利,比如使用IPython。
sess = tf.InteractiveSession()
# 測試正確率
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 所有變數進行初始化
sess.run(tf.initialize_all_variables())

# 獲取mnist資料
mnist_data_set = input_data.read_data_sets('MNIST_data', one_hot=True)

# 進行訓練
start_time = time.time()
for i in range(2000):
    # 獲取訓練資料
    batch_xs, batch_ys = mnist_data_set.train.next_batch(200)

    # 每迭代100個 batch,對當前訓練資料進行測試,輸出當前預測準確率
    if (i % 100 == 0) :
        train_accurancy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys})
        print("step %d, training accuracy %g" % (i, train_accurancy))
        # 計算間隔時間
        end_time = time.time()
        print('time:', ( end_time - start_time))
        start_time = end_time
    # 訓練資料
    train_step.run(feed_dict={x: batch_xs, y_: batch_ys})

# 關閉會話
sess.close()

完整程式碼

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

# 宣告輸入圖片資料,類別
x = tf.placeholder('float', [None, 784])
y_ = tf.placeholder('float', [None, 10])

# 輸入圖片資料轉化
x_image = tf.reshape(x, [-1, 28, 28, 1])

# 第一層卷積層,初始化卷積核引數、偏置值,該卷積層5*5大小,一個通道,共有6個不同卷積核
filter1 = tf.Variable(tf.truncated_normal([5, 5, 1, 6]))
bias1 = tf.Variable(tf.truncated_normal([6]))
conv1 = tf.nn.conv2d(x_image, filter1, strides=[1, 1, 1, 1], padding='SAME')
h_conv1 = tf.nn.sigmoid(conv1 + bias1)

maxPool2 = tf.nn.max_pool(h_conv1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')

filter2 = tf.Variable(tf.truncated_normal([5, 5, 6, 16]))
bias2 = tf.Variable(tf.truncated_normal([16]))
conv2 = tf.nn.conv2d(maxPool2, filter2, strides=[1, 1, 1, 1], padding='SAME')
h_conv2 = tf.nn.sigmoid(conv2 + bias2)

maxPool3 = tf.nn.max_pool(h_conv2, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME')

filter3 = tf.Variable(tf.truncated_normal([5, 5, 16, 120]))
bias3 = tf.Variable(tf.truncated_normal([120]))
conv3 = tf.nn.conv2d(maxPool3, filter3, strides=[1, 1, 1, 1],padding='SAME')
h_conv3 = tf.nn.sigmoid(conv3 + bias3)

# 全連線層
# 權值引數
W_fc1 = tf.Variable(tf.truncated_normal([7 * 7 * 120, 80]))
# 偏置值
b_fc1 = tf.Variable(tf.truncated_normal([80]))
# 將卷積的產出展開
h_pool2_flat = tf.reshape(h_conv3,[-1, 7 * 7 * 120])
# 神經網路計算,並新增sigmoid啟用函式
h_fc1 = tf.nn.sigmoid(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

# 輸出層,使用softmax進行多分類
W_fc2 = tf.Variable(tf.truncated_normal([80,10]))
b_fc2 = tf.Variable(tf.truncated_normal([10]))
y_conv = tf.nn.softmax(tf.matmul(h_fc1, W_fc2) + b_fc2)

cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))

train_step = tf.train.GradientDescentOptimizer(0.001).minimize(cross_entropy)

# tf.InteractiveSession():它能讓你在執行圖的時候,插入一些計算圖,
# 這些計算圖是由某些操作(operations)構成的。這對於工作在互動式環境中的人們來說非常便利,比如使用IPython。
sess = tf.InteractiveSession()
# 測試正確率
correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

# 所有變數進行初始化
sess.run(tf.initialize_all_variables())

# 獲取mnist資料
mnist_data_set = input_data.read_data_sets('MNIST_data', one_hot=True)

# 進行訓練
start_time = time.time()
for i in range(2000):
    # 獲取訓練資料
    batch_xs, batch_ys = mnist_data_set.train.next_batch(200)

    # 每迭代100個 batch,對當前訓練資料進行測試,輸出當前預測準確率
    if (i % 100 == 0) :
        train_accurancy = accuracy.eval(feed_dict={x: batch_xs, y_: batch_ys})
        print("step %d, training accuracy %g" % (i, train_accurancy))
        # 計算間隔時間
        end_time = time.time()
        print('time:', ( end_time - start_time))
        start_time = end_time
    # 訓練資料
    train_step.run(feed_dict={x: batch_xs, y_: batch_ys})

# 關閉會話
sess.close()

破電腦根本不能碰CNN,直接宕機了。。。所以也沒法給執行結果了,將就著學吧,唉。。。

模組化整理後的程式碼

# -*- coding:utf-8 -*-

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

# 獲取mnist資料
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

batch_size = 100
n_batch = mnist.train.num_examples // batch_size

# 引數概要
def variable_summaries(var):
    with tf.name_scope('summaries'):
        mean = tf.reduce_mean(var)
        tf.summary.scalar('mean', mean)
        with tf.name_scope('stddev'):
            stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean)))
        tf.summary.scalar('stddev', stddev)
        tf.summary.scalar('max', tf.reduce_max(var))
        tf.summary.scalar('min', tf.reduce_min(var))
        tf.summary.histogram('histogram', var)

# 初始化權值
def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1) # 生成一個截斷的正態分佈
    return tf.Variable(initial, name=name)

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

#卷積層
def conv2d(x, W):
    # x input tensor of shape '[batch, in_height, in_width, in_channels]'
    # W filter / kernel tensor of shape [filter_height, filter_width, in_channels, out_channels]
    # 'strides[0] = stride[3] = 1'.strides[1]代表x方向的步長,strides[2]代表y方向的步長
    # padding : A 'string' from: 'SAME', 'VALID'
    return  tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

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

# 名稱空間
with tf.name_scope('input'):
    # 定義兩個placeholder
    x = tf.placeholder(tf.float32, [None, 784], name='x-input')
    y = tf.placeholder(tf.float32, [None, 10], name='y-input')
    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'):
        W_conv1 = weight_variable([5, 5, 1, 32], name='W_conv1')
        # 5*5的取樣視窗,32個卷積核從1個平面抽取特徵
    with tf.name_scope('b_conv1'):
        # 每一個卷積核一個偏置值
        b_conv1 = bias_variable([32], name='b_conv1')

    # 把x_image 和權值向量進行卷積,再加入偏置值,然後應用於relu啟用函式
    with tf.name_scope('conv2d_1'):
        conv2d_1 = conv2d(x_image, W_conv1) + b_conv1
    with tf.name_scope('relu'):
        h_conv1 = tf.nn.relu(conv2d_1)
    with tf.name_scope('h_pool1'):
        h_pool1 = max_pool_2x2(h_conv1) #進行max-pooling

with tf.name_scope('Conv2'):
    # 初始化第二個卷積層的權值和偏置
    with tf.name_scope('W_conv2'):
        W_conv2 = weight_variable([5, 5, 32, 64], name='W_conv2')
    with tf.name_scope('b_conv2');
        b_conv2  = bias_variable([64], name='b_conv2') # 每一個卷積核一個偏置值

    # 把h_pool1和權值向量進行卷積,再加上偏置值,然後應用於relu啟用函式
    with tf.name_scope('conv2d_2'):
        conv2d_2 = conv2d(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 = max_pool_2x2(h_conv2)

# 28*28的圖片第一次卷積後還是28*28,第一次池化後變為了14*14
# 第二次卷積後為14*14,第二次池化變為了7*7
# 進過上面操作後得到64張7*7的平面

with tf.name_scope('fc1'):
    with tf.name_scope('W_fc1'):
        W_fc1 = weight_variable([7 * 7 * 64, 1024], name='W_fc1')
    with tf.name_scope('b_fc1'):
        b_fc1 = bias_variable([1024], name='b_fc1')# 1024個節點

    # 把池化層2的輸出扁平化為1維
    with tf.name_scope('h_pool2_flat'):
        h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64], name='h_pool2_flat')
    # 求第一個全連線層的輸出
    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用來表示神經元的輸出概率
    with tf.name_scope('keep_prob'):
        keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    with tf.name_scope('h_fc1_dorp'):
        h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob, name='h_fc1_drop')

with tf.name_scope('fc2'):
    # 初始化第二個全連線層
    with tf.name_scope('W_fc2'):
        W_fc2 = weight_variable([1024, 10], name='W_fc2')
    with tf.name_scope('b_fc2'):
        b_fc2 = bias_variable([10], name='b_fc2')
    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)

# 交叉熵代價函式
with  tf.name_scope('cross_entropy')
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction),
                                   name='cross_entropy')
    tf.summary.scalar('cross_entropy', cross_entropy)

# 使用AdamOptimiazer進行優化
with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

# 求準確率
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        # 結果存放在一個布林列表中
        # argmax返回一維張量中最大值所在的位置
         correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    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('logs/train', sess.graph)
    test_writer = tf.summary.FileWriter('logs/test', sess.graph)
    for i in range(1001):
         # 訓練模型
         batch_xs, batch_ys = mnist.train.next_batch(batch_size)
         sess.run(train_step, feed_dict={x: batch_xs, y: batch_ys, keep_prob:1.0})
         # 記錄訓練集的引數
         summary = sess.run(merged, feed_dict={x: batch_xs, y: batch_ys, keep_prob:1.0})
         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 })
         test_writer.add_summary(summary, i)

         if i % 100 == 0:
             test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test. labels,keep_prob: 1.0})
             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))