1. 程式人生 > >基於Tensorflow的機器學習(5) -- 全連線神經網路

基於Tensorflow的機器學習(5) -- 全連線神經網路

這篇部落格將實現的主要神經網路如下所示:

這裡寫圖片描述

以下是相關程式碼的實現步驟:

簡單化的實現

匯入必要內容

# Import MNIST data
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)

引數初始化

# Parameters
learning_rate = 0.1
num_steps = 500
batch_size = 128
display_step = 100
# Network Parameters n_hidden_1 = 256 # 1st layer number of neurons n_hidden_2 = 256 # 2nd layer number of neurons num_input = 784 # MNIST data input (img shape: 28*28) num_classes = 10 # MNIST total classes (0-9 digits) # tf Graph Input X = tf.placeholder("float", [None, num_input]) Y = tf.placeholder("float"
, [None, num_classes])

此處每個隱藏層都有256個神經元,輸入是通過圖片轉換而來的784維陣列,一共將所有資料分為0-9這10個類。

儲存weights 和 bias

# Store layers weight & bias
weights = {
    'h1' : tf.Variable(tf.random_normal([num_input, n_hidden_1])),
    'h2' : tf.Variable(tf.random_normal([n_hidden_1, n_hidden_2])),
    'out' : tf.Variable(tf.random_normal([n_hidden_2, num_classes]))
}
# 為何我們要將上述的兩個變數以矩陣的形式進行傳輸
biases = { 'b1' : tf.Variable(tf.random_normal([n_hidden_1])), 'b2' : tf.Variable(tf.random_normal([n_hidden_2])), 'out' : tf.Variable(tf.random_normal([num_classes])) }

模型建立

# Create model
def neural_net(x):
    # Hidden fully connnected layer with 256 neurons
    layer_1 = tf.add(tf.matmul(x, weights['h1']) , biases['b1'])
    # Hidden fully connnected layer with 256 neurons
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']) , biases['b2'])
    # Output fully connected layer with a neuron for each class
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

模型構建

# Create model
def neural_net(x):
    # Hidden fully connnected layer with 256 neurons
    layer_1 = tf.add(tf.matmul(x, weights['h1']) , biases['b1'])
    # Hidden fully connnected layer with 256 neurons
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']) , biases['b2'])
    # Output fully connected layer with a neuron for each class
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer

模型訓練

# Start training
with tf.Session() as sess:
    # Run the initilizer
    sess.run(init)

    for step in range(1, num_steps+1):
        batch_x, batch_y = mnist.train.next_batch(batch_size)
        # Run optimization op (backporp)
        sess.run(train_op, feed_dict={X: batch_x, Y: batch_y})
        if step % display_step == 0 or step == 1:
            # Calculate batch loss and accuracy
            loss, acc = sess.run([loss_op, accuracy], feed_dict={X: batch_x, Y: batch_y})

            print("Step " + str(step) + ", Minibatch Loss= " + \
                  "{:.4f}".format(loss) + ", Training Accuracy= " + \
                  "{:.3f}".format(acc))

    print("Optimization Finished!")

    # Calculate accuracy for MNIST test images
    print("Testiing Accuracy:", \
         sess.run(accuracy, feed_dict={X: mnist.test.images, Y: mnist.test.labels}))

結果輸出:

Step 1, Minibatch Loss= 10718.8223, Training Accuracy= 0.289
Step 100, Minibatch Loss= 254.0072, Training Accuracy= 0.852
Step 200, Minibatch Loss= 91.2099, Training Accuracy= 0.859
Step 300, Minibatch Loss= 65.1114, Training Accuracy= 0.859
Step 400, Minibatch Loss= 48.7690, Training Accuracy= 0.891
Step 500, Minibatch Loss= 13.4156, Training Accuracy= 0.922
Optimization Finished!
('Testiing Accuracy:', 0.8648001)

全連線網路高階實現

以下例項將使用tensorflow的 ‘layers’ 和 ‘estimator’的API去構建上述的全連線網路。

具體實現步驟如下:

匯入必要內容

# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data", one_hot=False)

import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np

引數初始化

# Parameters
learning_rate = 0.01
num_steps = 1000
batch_size = 128
display_step = 100

# Network Parameters
n_hidden_1 = 256 # 1st layer number of neurons
n_hidden_2 = 256 # 2nd layer number of neurons
num_input = 784 # MNIST data input( img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)

定義輸入函式

# Define the input function for training
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.train.images}, y=mnist.train.labels,
    batch_size=batch_size, num_epochs=None, shuffle=True)

稍後對estimator的API進行具體分析,此處只需要記住相關用法即可

定義神經網路

# Define the neural network
def neural_net(x_dict):
    # TF Estimator input is a dict, in case of multiple inputs
    x = x_dict['images']
    # Hidden fully connected layer with 256 neurons
    layer_1 = tf.layers.dense(x, n_hidden_1)
    # Hidden fully connected layer with 256 neurons
    layer_2 = tf.layers.dense(layer_1, n_hidden_2)
    # Output fully connected layer with a neuron for each class
    out_layer = tf.layers.dense(layer_2, num_classes)
    return out_layer

定義模型函式


# Define the model function (following TF Estimator Template)
def model_fn(features, labels, mode):

    # Build the neural network
    logits = neural_net(features) # features 是個啥

    # Predictions
    pred_classes = tf.argmax(logits, axis=1)
    pred_probas = tf.nn.softmax(logits)

    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)

    # Define loss and optimizer
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op, global_step=tf.train.get_global_step())
    # 什麼是global step??

    # Evaluate the accuracy of the model
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)

    # TF Estimators requires to return a EstimatorSpec, that specify
    # the different ops for training, evaluating
    estim_specs = tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=pred_classes,
        loss=loss_op,
        train_op=train_op,
        eval_metric_ops={'accuracy': acc_op})

    return estim_specs

建立estimator

# Build the Estimator
model = tf.estimator.Estimator(model_fn)

模型訓練

# Train the Model
model.train(input_fn, steps=num_steps)

模型評估

# Evaluate the Model
# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, y=mnist.test.labels,
    batch_size=batch_size, shuffle=False)
# Use the Estimator 'evaluate' method
model.evaluate(input_fn)

輸出結果為:

{'accuracy': 0.9091, 'global_step': 2000, 'loss': 0.31571656}

單圖片預測

# Predict single images
n_images = 5
# Get images from test set
test_images = mnist.test.images[:n_images]
# Prepare the input data
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': test_images}, shuffle=False)
# Use the model to predict the images class
preds = list(model.predict(input_fn))

# Display
for i in range(n_images):
    plt.imshow(np.reshape(test_images[i], [28,28]), cmap='gray')
    plt.show()
    print("Model prediction: ", preds[i])

以上便是基於tensorflow的全連線網路的理論及其應用的全部內容。