1. 程式人生 > >TensorFlow實戰4:實現簡單的多層神經網路案例

TensorFlow實戰4:實現簡單的多層神經網路案例

這篇文章記錄一下使用TensorFlow實現卷積神經網路的過程,資料集採用的還是MNIST資料集,使用了兩層的卷積來進行計算,整個過程在jupyter notebook中完成,具體步驟和程式碼展示如下:

1.環境設定

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

1.資料準備

#使用tensorflow自帶的工具載入MNIST手寫數字集合
mnist = input_data.read_data_sets('./data/mnist'
, one_hot=True)

可以先對下載的資料資訊進行一個初步的瞭解,有利於後面的使用

#檢視一下訓練資料維度
mnist.train.images.shape

這裡寫圖片描述

#檢視target維度
mnist.train.labels.shape

這裡寫圖片描述
2.準備好placeholder
此處先不指定每次輸入資料的大小,在後面根據需要再進行指定和調整。

X = tf.placeholder(tf.float32, [None, 784], name='X_placeholder') 
Y = tf.placeholder(tf.int32, [None, 10], name='Y_placeholder'
)

3.準備好引數/權重

# 網路引數
n_hidden_1 = 256 # 第1個隱層  ,節點個數為256
n_hidden_2 = 256 # 第2個隱層
n_input = 784 # MNIST 資料輸入(28*28*1=784)
n_classes = 10 # MNIST 總共10個手寫數字類別

weights = {
    'h1': tf.Variable(tf.random_normal([n_input, n_hidden_1]), name='W1'),
    'h2': tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2]), name='W2'
), 'out': tf.Variable(tf.random_normal([n_hidden_2, n_classes]), name='W') } #偏置在隱層的時候和節點個數一致,在輸出層和輸出類別個數一致 biases = { 'b1': tf.Variable(tf.random_normal([n_hidden_1]), name='b1'), 'b2': tf.Variable(tf.random_normal([n_hidden_2]), name='b2'), 'out': tf.Variable(tf.random_normal([n_classes]), name='bias') }

4.構建網路計算graph

#此函式是用來構建計算的神經網路,得出預測類別的得分
def multilayer_perceptron(x, weights, biases):
    # 第1個隱層,使用relu啟用函式
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'], name='fc_1')
    layer_1 = tf.nn.relu(layer_1, name='relu_1')
    # 第2個隱層,使用relu啟用函式
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'], name='fc_2')
    layer_2 = tf.nn.relu(layer_2, name='relu_2')
    # 輸出層
    out_layer = tf.add(tf.matmul(layer_2, weights['out']), biases['out'], name='fc_3')
    return out_layer

5.拿到預測類別score

pred = multilayer_perceptron(X, weights, biases)

6.計算損失函式值並初始化optimizer

learning_rate = 0.001
loss_all = tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=Y, name='cross_entropy_loss')
loss = tf.reduce_mean(loss_all, name='avg_loss')
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(loss)

7.初始化變數

init = tf.global_variables_initializer()

8.在session中執行graph定義的運算

#訓練總輪數
training_epochs = 30
#一批資料大小
batch_size = 128
#資訊展示的頻度
display_step = 5

with tf.Session() as sess:
    sess.run(init)
    writer = tf.summary.FileWriter('./graphs/MLP_DNN', sess.graph)

    # 訓練
    for epoch in range(training_epochs):
        avg_loss = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # 遍歷所有的batches
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # 使用optimizer進行優化
            _, l = sess.run([optimizer, loss], feed_dict={X: batch_x, Y: batch_y})
            # 求平均的損失
            avg_loss += l / total_batch
        # 每一步都展示資訊
        if epoch % display_step == 0:
            print("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_loss))
    print("Optimization Finished!")

    # 在測試集上評估
    correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(Y, 1))
    # 計算準確率
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
    print("Accuracy:", accuracy.eval({X: mnist.test.images, Y: mnist.test.labels}))   #此處accuracy是Tensor,在執行計算時需要用到eval()
    # print("Accuracy:", sess.run(accuracy,feed_dict = {X: mnist.test.images, Y: mnist.test.labels}))    #也可以用sess.run()
    writer.close()

最後得出的訓練結果如下圖所示:
這裡寫圖片描述

以上就是用兩層的神經網路來對MNIST資料集進行的分類,調整學習率以及迴圈次數等引數,可能會進一步提高分類的準確率。