文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
本文主要是使用tensorflow定義卷積神經(jīng)網(wǎng)絡(luò)來訓(xùn)練MNIST數(shù)據(jù)集。定義的神經(jīng)網(wǎng)絡(luò)結(jié)構(gòu)為兩個(gè)卷積層+兩個(gè)連接層,每個(gè)卷積層包括卷積層、ReLU層和Pooling層。
#!/usr/bin/env python
# _*_ coding: utf-8 _*_
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# 定義神經(jīng)網(wǎng)絡(luò)模型的評(píng)估部分
def compute_accuracy(test_xs, test_ys):
# 使用全局變量prediction
global prediction
# 獲得預(yù)測(cè)值y_pre
y_pre = sess.run(prediction, feed_dict = { xs: test_xs, keep_prob: 1})
# 判斷預(yù)測(cè)值y和真實(shí)值y_中最大數(shù)的索引是否一致,y_pre的值為1-10概率
correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(test_ys, 1))
# 定義準(zhǔn)確率的計(jì)算
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 計(jì)算準(zhǔn)確率
result = sess.run(accuracy)
return result
# 下載mnist數(shù)據(jù)
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
# 權(quán)重參數(shù)初始化
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev = 0.1)
return tf.Variable(initial)
# 偏置參數(shù)初始化
def bias_variable(shape):
initial = tf.constant(0.1, shape = shape)
return tf.Variable(initial)
# 定義卷積層
def conv2d(x, W):
# stride的四個(gè)參數(shù):[batch, height, width, channels], [batch_size, image_rows, image_cols, number_of_colors]
# height, width就是圖像的高度和寬度,batch和channels在卷積層中通常設(shè)為1
return tf.nn.conv2d(x, W, strides = [1, 1, 1, 1], padding = 'SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = 'SAME')
# 輸入輸出數(shù)據(jù)的placeholder
xs = tf.placeholder(tf.float32, [None, 784])
ys = tf.placeholder(tf.float32, [None, 10])
# dropout的比例
keep_prob = tf.placeholder(tf.float32)
# 對(duì)數(shù)據(jù)進(jìn)行重新排列,形成圖像
x_image = tf.reshape(xs, [-1, 28, 28, 1])
print x_image.shape
# 卷積層一
# patch為5*5,in_size為1,即圖像的厚度,如果是彩色,則為3,32是out_size,輸出的大小
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
# ReLU操作,輸出大小為28*28*32
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# Pooling操作,輸出大小為14*14*32
h_pool1 = max_pool_2x2(h_conv1)
# 卷積層二
# patch為5*5,in_size為32,即圖像的厚度,64是out_size,輸出的大小
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
# ReLU操作,輸出大小為14*14*64
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# Pooling操作,輸出大小為7*7*64
h_pool2 = max_pool_2x2(h_conv2)
# 全連接層一
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
# 輸入數(shù)據(jù)變換
h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
# 進(jìn)行全連接操作
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
# 防止過擬合,dropout
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# 全連接層二
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
# 預(yù)測(cè)
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
# 計(jì)算loss
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction), reduction_indices=[1]))
# 神經(jīng)網(wǎng)絡(luò)訓(xùn)練
train_step = tf.train.AdamOptimizer(0.0001).minimize(cross_entropy)
# 定義Session
sess = tf.Session()
# 根據(jù)tensorflow版本選擇初始化函數(shù)
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
init = tf.initialize_all_variables()
else:
init = tf.global_variables_initializer()
# 執(zhí)行初始化
sess.run(init)
# 進(jìn)行訓(xùn)練迭代
for i in range(1000):
# 取出mnist數(shù)據(jù)集中的100個(gè)數(shù)據(jù)
batch_xs, batch_ys = mnist.train.next_batch(100)
# 執(zhí)行訓(xùn)練過程并傳入真實(shí)數(shù)據(jù)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 100 == 0:
print compute_accuracy(mnist.test.images, mnist.test.labels)
執(zhí)行結(jié)果如下:
$ python practice4.py
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
0.0823
0.875
0.9243
0.9427
0.9502
0.9573
0.9595
0.9623
0.963
0.9687