美文网首页
TensorFlow之简单卷积神经网络构建

TensorFlow之简单卷积神经网络构建

作者: 你要好好学习呀 | 来源:发表于2019-04-30 15:41 被阅读0次
#模型架构
#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_output=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_output ],stddev= 0.1))
}
biases ={
    'bc1':tf.Variable(tf.random_normal([64],stddev= 0.1)),
    'bc2':tf.Variable(tf.random_normal([128],stddev= 0.1)),
    'bd1':tf.Variable(tf.random_normal([1024],stddev= 0.1)),
    'bd2':tf.Variable(tf.random_normal([n_output ],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
    第四个参数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]这种形式
    
    '''
    _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]])
    _fc1=tf.nn.relu(tf.add(tf.matmul(_densel,_w['wd1']),_b['bd1']))
    _fc_dr1=tf.nn.dropout(_fc1,_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':_fc1,'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_output])
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.argmax(_pred,1),tf.argmax(y,1))
accr=tf.reduce_mean(tf.cast(_corr,tf.float32))

init=tf.global_variables_initializer()

print("FUNCTIONS READY")

sess=tf.Session()
sess.run(init)

training_epochs=20
batch_size=64#示范,防止过慢
display_step=1
for epoch in range(training_epochs ):
    avg_cost=0
    total_batch=20#示范,防止过慢
    for i in range(total_batch):
        batch_xs,batch_ys=mnist.train.next_batch(batch_size)
        sess.run(optm,feed_dict={x:batch_xs ,y:batch_ys ,keepratio :0.7})
        avg_cost+=sess.run(cost,feed_dict={x:batch_xs ,y:batch_ys ,keepratio :1.})/total_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")

相关文章

网友评论

      本文标题:TensorFlow之简单卷积神经网络构建

      本文链接:https://www.haomeiwen.com/subject/jpsvnqtx.html