免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2662 | 回复: 0
打印 上一主题 下一主题

学习笔记TF028:实现简单卷积网络 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2017-07-24 20:54 |只看该作者 |倒序浏览
载入MNIST数据集。创建默认Interactive Session。

初始化函数,权重制造随机噪声打破完全对称。截断正态分布噪声,标准差设0.1。ReLU,偏置加小正值(0.1),避免死亡节点(dead neurons)。

卷积层函数,tf.nn.conv2d,TensorFlow 2 维卷积函数,参数x输入,W卷积参数,卷积核尺寸,channel个数,卷积核数量(卷积层提取特征数量)。Strides卷积模板移动步长,全1代表不遗漏划过图片每一个点。Padding代表边界处理方式,SAME边界加Padding,卷积输出、输入保持同样尺寸。

池化层函数,tf.nn.max_pool,TensorFlow 最大池化函数。2x2最大池化,2x2像素块降为1x1像素。最大池化保留原始像素块灰度值最高像素,保留最显著特征。strides设横竖方向2步长。

定义输入placeholder,x特征,y真实label。卷积神经网络空间结构信息,1D输入向量,转为2D图片结构。尺寸[-1,28,28,1]。-1代表样本数量不固定。1代表颜色通道数量。tf.reshape tensor变形函数。

第一个卷积层,卷积函数初始化,weights、bias。[5,5,1,32]代表卷积核尺寸5x5,1个颜色通道,32个不同卷积核。使用conv2d函数卷积操作,加偏置,使用ReLU激活函数非线性处理。使用最大池化函数max_pool_2x2池化操作卷积输出结果。

第二个卷积层,卷积核64个,提取64种特征。经历两次步长2x2最大池化,边长只有1/4,图片尺寸28x28变7x7.第二个卷积层卷积核数量64,输出tensor尺寸7x7x64。使用tf.reshape函数对第二个卷积层输出tensor变形,转成1D向量,连接一个全连接层,隐含节点1024,使用ReLU激活函数。

使用Dropout层减轻过拟合。Dropout,通过一个placeholder传入keep_prob比率控制。训练时,随机丢弃部分节点数据减轻过拟合,预测时保留全部数据追求最好预测性能。

Dropout层输出连接Softmax层,得到最后概率输出。

定义损失函数cross_entropy。优化器使用Adam,给予较小学习速率1e-4。

定义评测准确率操作。

训练,初始化所有参数,设置训练时Dropout的keep_prob比率0.5.使用大小50的mini-batch,进行20000次训练迭代,样本数量100万。每100次训练,评测准确率,keep_prob设1,实时监测模型性能。

全部训练完成,测试集全面测试,得到整体分类准确率。

99.2%准确率,卷积网络对图像特征提取抽象,卷积核权值共享。

    from tensorflow.examples.tutorials.mnist import input_data
    import tensorflow as tf
    mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
    sess = tf.InteractiveSession()
    def weight_variable(shape):
      initial = tf.truncated_normal(shape, stddev=0.1)
      return tf.Variable(initial)
    def bias_variable(shape):
      initial = tf.constant(0.1, shape=shape)
      return tf.Variable(initial)

    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')  

    x = tf.placeholder(tf.float32, [None, 784])
    y_ = tf.placeholder(tf.float32, [None, 10])
    x_image = tf.reshape(x, [-1,28,28,1])

    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
    h_pool2 = max_pool_2x2(h_conv2)
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])
    h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])
    y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y_conv), reduction_indices=[1]))
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
    correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.global_variables_initializer().run()
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i%100 == 0:
        train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
        print("step %d, training accuracy %g"%(i, train_accuracy))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
    print("test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))

参考资料:
《TensorFlow实践》

欢迎付费咨询(150元每小时),我的微信:qingxingfengzi

您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP