mnist数据集+cnn卷积神经网络+FC全连接网络

版权声明:仅用于个人学习,分享收获。 https://blog.csdn.net/qq_33431972/article/details/86725808

mnist数据集

读取mnist数据集

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/home/liang/tf/data', one_hot=True)

得到:
Extracting /home/liang/tf/data/train-images-idx3-ubyte.gz
Extracting /home/liang/tf/data/train-labels-idx1-ubyte.gz
Extracting /home/liang/tf/data/t10k-images-idx3-ubyte.gz
Extracting /home/liang/tf/data/t10k-labels-idx1-ubyte.gz

Datasets(train validation test)

训练train
mnist.train.num_examples
55000
mnist.train.images
图片像素方阵
(55000, 784)

mnist.train.labels
标签方阵
(55000, 10)

测试test
mnist.test.num_examples
10000
mnist.test.images
图片像素方阵
(10000, 784)

mnist.test.labels
标签方阵
(10000, 10)

验证validation
mnist.validation.num_examples
5000
mnist.validation.images
(5000, 784)
mnist.validation.labels
(5000, 10)

定义方便的常用函数

#x是输入图片,y_是输出标准答案历史数据
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])

#w权值初始化
def get_weight(shape):
    w = tf.truncated_normal(shape, stddev=0.01)
    return tf.Variable(w)
    
#b值初始化
def get_bias(shape):
    b = tf.constant(0.1, shape=shape)
    return tf.Variable(b)

#卷积
def conv2d(x, w):
    return tf.nn.conv2d(x, w, 
    					strides=[1, 1, 1, 1],
    			 		adding='SAME')

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

cnn卷积神经网络

#c1
x_image = tf.reshape(x, [-1, 28, 28, 1])
w_conv1 = get_weight([5, 5, 1, 32])
b_conv1 = get_bias([32])

conv1 = tf.nn.relu(conv2d(x_image, w_conv1)+b_conv1)
pool1 = max_pool_2x2(conv1)

#c2
w_conv2 = get_weight([5, 5, 32, 64])
b_conv2 = get_bias([64])
conv2 = tf.nn.relu(conv2d(pool1, w_conv2)+b_conv2)
pool2 = max_pool_2x2(conv2)

Fc全连接网络

前向传播,得出预测结果

#fc1
pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
w_fc1 = get_weight([7 * 7 * 64, 1024])
b_fc1 = get_bias([1024])
fc1 = tf.nn.relu(tf.matmul(pool2_flat, w_fc1)+b_fc1)

# drop_out
prob = tf.placeholder("float")
fc1_drop = tf.nn.dropout(fc1, prob)

#fc2
w_fc2 = get_weight([1024, 10])
b_fc2 = get_bias([10])
y = tf.nn.softmax(tf.matmul(fc1_drop,w_fc2)+b_fc2)

反向传播,优化参数

#减小loss值
loss = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01)
			 .minimize(loss)

准确率

correct_prediction = tf.equal(tf.argmax(y_, 1),
							  tf.argmax(y,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction, 
						        "float"))

会话,运行计算

with tf.Session() as sess:
    tf.global_variables_initializer().run()
#训练集准确率
    for i in range(800):
        x_image,y_labels = mnist.train.next_batch(50)
        sess.run(train_step, 
        		 feed_dict={x: x_image,y_: y_labels, 
        		            prob: 1.0})
        		            
        if i % 200 == 0:
            train_accuracy = sess.run(accuracy,
                                      feed_dict={x: x_image , y_: y_labels, prob: 1.0})
            print("第%d轮,训练集accuracy是 %g" % (i, train_accuracy))
#测试集准确率
	for i in range(10):
        x_image,y_labels = mnist.test.next_batch(100)
        print("测试集accuracy是 %g" % accuracy.eval(feed_dict={x: x_image, y_:y_labels, prob: 1.0}))

代码

#coding:utf-8
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/home/liang/tf/data', one_hot=True)
# x是输入图片,y_是输出标准答案历史数据
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
# w权值初始化
def get_weight(shape):
    w = tf.truncated_normal(shape, stddev=0.01)
    return tf.Variable(w)
# b值初始化
def get_bias(shape):
    b = tf.constant(0.1, shape=shape)
    return tf.Variable(b)
# 卷积
def conv2d(x, w):
    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')
#c1
x_image = tf.reshape(x, [-1, 28, 28, 1])
w_conv1 = get_weight([5, 5, 1, 32])
b_conv1 = get_bias([32])
conv1 = tf.nn.relu(conv2d(x_image, w_conv1)+b_conv1)
pool1 = max_pool_2x2(conv1)

#c2
w_conv2 = get_weight([5, 5, 32, 64])
b_conv2 = get_bias([64])
conv2 = tf.nn.relu(conv2d(pool1, w_conv2)+b_conv2)
pool2 = max_pool_2x2(conv2)

#fc1
pool2_flat = tf.reshape(pool2, [-1, 7 * 7 * 64])
w_fc1 = get_weight([7 * 7 * 64, 1024])
b_fc1 = get_bias([1024])
fc1 = tf.nn.relu(tf.matmul(pool2_flat, w_fc1)+b_fc1)

# drop_out
prob = tf.placeholder("float")
fc1_drop = tf.nn.dropout(fc1, prob)

#fc2
w_fc2 = get_weight([1024, 10])
b_fc2 = get_bias([10])
y = tf.nn.softmax(tf.matmul(fc1_drop,w_fc2)+b_fc2)

#减小loss值
loss = -tf.reduce_sum(y_ * tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss)

correct_prediction = tf.equal(tf.argmax(y_, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

with tf.Session() as sess:
    tf.global_variables_initializer().run()
    # 训练集准确率
    for i in range(800):
        x_image, y_labels = mnist.train.next_batch(50)
        sess.run(train_step, feed_dict={x: x_image, y_: y_labels, prob: 1.0})
        if i % 200 == 0:
            loss_value, train_accuracy = sess.run([loss, accuracy], feed_dict={x: x_image, y_: y_labels, prob: 1.0})
            print("第 %d 轮,训练集accuracy是 %g " % (i, train_accuracy))
            print('loss值是', loss_value)
        # 测试集准确率
    for i in range(10):
        x_image, y_labels = mnist.test.next_batch(100)
        print("测试集accuracy是 %g" % accuracy.eval(feed_dict={x: x_image, y_: y_labels, prob: 1.0}))

猜你喜欢

转载自blog.csdn.net/qq_33431972/article/details/86725808