模型架构
输入数据:n*784的数据
第一层卷积:卷积层1(filter=3* 3*1,个数为64个,padding=1,s=1)
第一层池化:池化层1(maxpooling:2*2,s=2)
第二层卷积:卷积层2(filter:3* 3* 64,128个filter,padding=1,s=1)
第二层池化:池化层2(maxpooling:2*2,s=2)
全连接层第一层:全连接层第一层(总结为1024个向量)
全连接层第二层:全连接层第二层(10个向量)
完成代码如下:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('data/',one_hot=True)
n_input = 784
n_out = 10
weights = {
'wc1': tf.Variable(tf.random_normal([3,3,1,64],stddev=0.1)),#第一层卷积的【高,宽,通道,个数】
'wc2': tf.Variable(tf.random_normal([3,3,64,128],stddev=0.1)),#第二层卷积的【高,宽,通道,个数】
'wd1': tf.Variable(tf.random_normal([7*7*128,1024],stddev=0.1)),#第三层全连接层的参数
'wd2': tf.Variable(tf.random_normal([1024,n_out],stddev=0.1))#输出层参数
}
biases = {
'bc1':tf.Variable(tf.random_normal([64],stddev=0.1)),#bc1是根据第一层卷积层神经元数决定的
'bc2':tf.Variable(tf.random_normal([128],stddev=0.1)),#bc2是根据第二层卷积层神经元数决定的
'bd1':tf.Variable(tf.random_normal([1024],stddev=0.1)),#bd1是根据全连接层神经元数决定的
'bd2':tf.Variable(tf.random_normal([n_out],stddev=0.1))
}
def conv_basic(_input,_w,_b,_keepratio):# 卷积神经网络的前向传播
# 对输入进行简单的预处理[n,h,w,c]-bitchsize大小,图像的高度、宽度,深度
_input_r = tf.reshape(_input,shape=[-1,28,28,1])# -1意思是让TensorFlow自己做一个推断,确定了其他所有维,可推断出第一维
'''
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
除去name参数用以指定该操作的name,与方法有关的一共五个参数:
第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,
具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一
第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,
具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维
第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4分别是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数]四个维度
第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式
第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
'''
# "VALID" 仅舍弃最后列,或最后行的数据
# "SAME" 尝试在数据左右均匀的填充0,若填充个数为奇数时,则将多余的填充值放数据右侧.
_conv1 = tf.nn.conv2d(_input_r,_w['wc1'],strides=[1,1,1,1],padding='SAME')
_conv1 = tf.nn.relu(tf.nn.bias_add(_conv1,_b['bc1']))
'''
tf.nn.max_pool(value, ksize, strides, padding, name=None)
参数是四个,和卷积很类似:
第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape
第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride, stride, 1]
第四个参数padding:和卷积类似,可以取'VALID'或者'SAME'
返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式
'''
'''
tf.nn.dropout(x, keep_prob, noise_shape=None, seed=None, name=None)
根据给出的keep_prob参数,将输入tensor x按比例输出。
使用说明:
参数 keep_prob: 表示的是保留的比例,假设为0.8,则20 % 的数据变为0,然后其他的数据乘以1 / keep_prob;keep_prob越大,保留的越多;
参数 noise_shape:干扰形状。此字段默认是None,表示第一个元素的操作都是独立,但是也不一定。比例:数据的形状是shape(x) = [k, l, m, n],而noise_shape = [k, 1, 1,n],
则第1和4列是独立保留或删除,第2和3列是要么全部保留,要么全部删除
'''
_pool1 = tf.nn.max_pool(_conv1,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
_pool1_dr1 = tf.nn.dropout(_pool1,_keepratio)# _keepratio表示保留的比例
_conv2 = tf.nn.conv2d(_pool1_dr1,_w['wc2'],strides=[1,1,1,1],padding='SAME')
_conv2 = tf.nn.relu(tf.nn.bias_add(_conv2,_b['bc2']))
_pool2 = tf.nn.max_pool(_conv2,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')
_pool_dr2 = tf.nn.dropout(_pool2,_keepratio)
# 全连接层——把输出转换为矩阵(向量)的形式
_densel = tf.reshape(_pool_dr2,[-1,_w['wd1'].get_shape().as_list()[0]])
_fc = tf.nn.relu(tf.add(tf.matmul(_densel,_w['wd1']),_b['bd1']))
_fc_dr1 = tf.nn.dropout(_fc,_keepratio)
_out = tf.add(tf.matmul(_fc_dr1,_w['wd2']),_b['bd2'])
out = {'input_r': _input_r, 'conv1': _conv1, 'pool1': _pool1, 'pool1_dr1': _pool1_dr1,
'conv2': _conv2, 'pool2': _pool2, 'pool_dr2': _pool_dr2, 'densel': _densel,
'fc1': _fc, 'fc_dr1': _fc_dr1, 'out': _out}
return out
print("CNN READY")
x = tf.placeholder(tf.float32,[None,n_input])
y = tf.placeholder(tf.float32,[None,n_out])
keepratio = tf.placeholder(tf.float32)
#预测结果值
_pred = conv_basic(x,weights,biases,keepratio)['out']
#计算损失
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=_pred,labels=y))
#使用梯度下降方法求解最小值就是得到的优化值
optm = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(cost)
#准确率
_corr = tf.equal(tf.arg_max(_pred,1),tf.argmax(y,1))#equal是判断预测得到的结果和真实y之间结果是否相同
accr = tf.reduce_mean(tf.cast(_corr,tf.float32))#tf.cast函数将布尔值转换成float
#初始化所有
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
training_epochs = 50
batch_size = 64
display_step = 1
for epoch in range(training_epochs):
avg_cost = 0
num_batch = int(mnist.train.num_examples/batch_size)
for i in range(num_batch):
batch_xs,batch_ys = mnist.train.next_batch(batch_size)
feed = {x:batch_xs,y:batch_ys,keepratio:0.7}
sess.run(optm,feed_dict=feed)
avg_cost = avg_cost + sess.run(cost,feed_dict={x:batch_xs,y:batch_ys,keepratio:1.})
avg_cost = avg_cost /num_batch
if epoch%display_step ==0:
print("Epoch: %03d/%03d cost: %.9f" % (epoch, training_epochs, avg_cost))
train_acc = sess.run(accr, feed_dict={x: batch_xs, y: batch_ys, keepratio: 1.})
print("Training accuracy: %.3f" % (train_acc))
print("FINISHED")