利用全连接网络将图片分类

一 实例描述
构建一个简单的多层神经网络,以拟合MNIST样本特征完成分类任务。

二 代码
import tensorflow as tf
# 导入 MINST 数据集
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/data/", one_hot=True)
#定义网络参数
'''
在输入层和输出层之间使用两个隐藏层,每层256个节点,学习率使用0.001。
'''
learning_rate = 0.001
training_epochs = 25
batch_size = 100
display_step = 1
# Network Parameters
n_hidden_1 = 256 # 1st layer number of features
n_hidden_2 = 256 # 2nd layer number of features
n_input = 784 # MNIST data 输入 (img shape: 28*28)
n_classes = 10  # MNIST 列别 (0-9 ,一共10类)
'''
定义网络结构
'''
# tf Graph input
x = tf.placeholder("float", [None, n_input])
y = tf.placeholder("float", [None, n_classes])
# Create model
#multilayer_perceptron函数封装好网络模型函数,第一层与第二层均使用Relu激活函数,loss使用交叉熵
def multilayer_perceptron(x, weights, biases):
    # Hidden layer with RELU activation
    layer_1 = tf.add(tf.matmul(x, weights['h1']), biases['b1'])
    layer_1 = tf.nn.relu(layer_1)
    # Hidden layer with RELU activation
    layer_2 = tf.add(tf.matmul(layer_1, weights['h2']), biases['b2'])
    layer_2 = tf.nn.relu(layer_2)
    # Output layer with linear activation
    out_layer = tf.matmul(layer_2, weights['out']) + biases['out']
    return out_layer
    
# Store layers weight & bias
weights = {
    'h1': tf.Variable(tf.random_normal([n_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, n_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([n_classes]))
}
# 构建模型
pred = multilayer_perceptron(x, weights, biases)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# 初始化变量
init = tf.global_variables_initializer()
# 启动session
with tf.Session() as sess:
    sess.run(init)
    # 启动循环开始训练
    for epoch in range(training_epochs):
        avg_cost = 0.
        total_batch = int(mnist.train.num_examples/batch_size)
        # 遍历全部数据集
        for i in range(total_batch):
            batch_x, batch_y = mnist.train.next_batch(batch_size)
            # Run optimization op (backprop) and cost op (to get loss value)
            _, c = sess.run([optimizer, cost], feed_dict={x: batch_x,
                                                          y: batch_y})
            # Compute average loss
            avg_cost += c / total_batch
        # 显示训练中的详细信息
        if epoch % display_step == 0:
            print ("Epoch:", '%04d' % (epoch+1), "cost=", \
                "{:.9f}".format(avg_cost))
    print (" Finished!")
    # 测试 model
    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}))
三 运行结果
Successfully downloaded train-images-idx3-ubyte.gz 9912422 bytes.
Extracting /data/train-images-idx3-ubyte.gz
Successfully downloaded train-labels-idx1-ubyte.gz 28881 bytes.
Extracting /data/train-labels-idx1-ubyte.gz
Successfully downloaded t10k-images-idx3-ubyte.gz 1648877 bytes.
Extracting /data/t10k-images-idx3-ubyte.gz
Successfully downloaded t10k-labels-idx1-ubyte.gz 4542 bytes.
Extracting /data/t10k-labels-idx1-ubyte.gz
Epoch: 0001 cost= 167.503109946
Epoch: 0002 cost= 42.023845719
Epoch: 0003 cost= 26.434357550
Epoch: 0004 cost= 18.450763896
Epoch: 0005 cost= 13.571702020
Epoch: 0006 cost= 10.169877889
Epoch: 0007 cost= 7.683901399
Epoch: 0008 cost= 5.580870980
Epoch: 0009 cost= 4.258601876
Epoch: 0010 cost= 3.213997342
Epoch: 0011 cost= 2.429289338
Epoch: 0012 cost= 1.821290299
Epoch: 0013 cost= 1.474814914
Epoch: 0014 cost= 1.091195856
Epoch: 0015 cost= 0.901945515
Epoch: 0016 cost= 0.752033565
Epoch: 0017 cost= 0.625414731
Epoch: 0018 cost= 0.596724849
Epoch: 0019 cost= 0.513915204
Epoch: 0020 cost= 0.432392413
Epoch: 0021 cost= 0.511673744
Epoch: 0022 cost= 0.384512378
Epoch: 0023 cost= 0.323022437
Epoch: 0024 cost= 0.367242469
Epoch: 0025 cost= 0.299307836
Finished!
Accuracy: 0.9534

四 说明
全连接网络可以成功将图片进行分类,并且随着层数的增加和节点的增多,还能够得到更好的拟合效果。

五 注意
由于神经网络学习算法限制,在实际情况中并不是层数越多,节点越多,效果就越好,因为在训练过程中使用BP算法,会随着层数的逐渐增大其算出来的调整值会逐渐变小,直到其他层都感觉不到变化,即梯度消失的情况。

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/80208247