这里,我们将采用Tensor Flow内建函数实现简单的CNN,并用MNIST数据集进行测试
第1步:加载相应的库并创建计算图会话
import numpy as np
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
import matplotlib.pyplot as plt
#创建计算图会话
sess = tf.Session()
第2步:加载MNIST数据集,这里采用TensorFlow自带数据集,MNIST数据为28×28的图像,因此将其转化为相应二维矩阵
#数据集
data_dir = 'MNIST_data'
mnist = read_data_sets(data_dir)
train_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.train.images] )
test_xdata = np.array([np.reshape(x,[28,28]) for x in mnist.test.images] )
train_labels = mnist.train.labels
test_labels = mnist.test.labels
第3步:设置模型参数
这里采用随机批量训练的方法,每训练10次对测试集进行测试,共迭代1500次,学习率采用指数下降的方式,初始学习率为0.1,每训练10次,学习率乘0.9,为了进行对比,后面会给出固定学习率为0.01的损失曲线图和准确率图
#设置模型参数
batch_size = 100 #批量训练图像张数
initial_learning_rate = 0.1 #学习率
global_step = tf.Variable(0, trainable=False) ;
learning_rate = tf.train.exponential_decay(initial_learning_rate,
global_step=global_step,
decay_steps=10,decay_rate=0.9)
evaluation_size = 500 #测试图像张数
image_width = 28 #图像的宽和高
image_height = 28
target_size = 10 #图像的目标为0~9共10个目标
num_channels = 1 #灰度图,颜色通道为1
generations = 1500 #迭代500次
evaluation_step = 10 #每训练十次进行一次测试
conv1_features = 25 #卷积层的特征个数
conv2_features = 50
max_pool_size1 = 2 #池化层大小
max_pool_size2 = 2
fully_connected_size = 100 #全连接层的神经元个数
第4步:声明占位符,注意这里的目标y_target类型为int32整型
#声明占位符
x_input_shape = [batch_size,image_width,image_height,num_channels]
x_input = tf.placeholder(tf.float32,shape=x_input_shape)
y_target = tf.placeholder(tf.int32,shape=[batch_size])
evaluation_input_shape = [evaluation_size,image_width,image_height,num_channels]
evaluation_input = tf.placeholder(tf.float32,shape=evaluation_input_shape)
evaluation_target = tf.placeholder(tf.int32,shape=