从零开始搭建自己的卷积神经网络:day.2--LeNet.5复现

心态崩了,写了一天,包括各种函数的用法注意事项等都不在了,自从上次出现了这种问题,我写一步保存一下,结果又是这样,没心情再写了任务还很多。直接贴lenet-5的代码吧

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

# 加载数据
mnist = input_data.read_data_sets('./MNIST_data', one_hot=True)
with tf.device('/CPU:0'):
    # 设置占位符,利用占位符处理输入输出数据
    x = tf.placeholder(tf.float32, shape=[None, 784])
    #表示有n行,784列
    y_ = tf.placeholder(tf.float32, shape=[None, 10])

    # 创建w参数
    def weight_variable(shape):
      initial = tf.truncated_normal(shape, stddev=0.1)
      return tf.Variable(initial)

    # 创建b参数
    def bias_variable(shape):
      initial = tf.constant(0.1, shape=shape)
      return tf.Variable(initial)

    # 创建卷积层,步长为1,周围补0,输入与输出的数据大小一样(可得到补全的圈数)
    def conv2d(x, W):
      return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

    # 创建池化层,kernel大小为2,步长为2,周围补0,输入与输出的数据大小一样(可得到补全的圈数)
    def max_pool_2x2(x):
      return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                            strides=[1, 2, 2, 1], padding='SAME')


    # 第一层卷积,这里使用5*5的过滤器,因为是灰度图片,所以只有一个颜色通道,使用32个过滤器来建立卷积层,所以
    # 我们一共是有5*5*32个参数
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    # 数据加载出来以后是一个n*784的矩阵,每一行是一个样本。784是灰度图片的所有的像素点。实际上应该是28*28的矩阵
    # 平铺开之后的结果,但在cnn中我们需要把他还原成28*28的矩阵,所以要reshape
    x_image = tf.reshape(x, [-1,28,28,1])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
    h_pool1 = max_pool_2x2(h_conv1)

    # 第二层卷积,同样使用5*5的过滤器,因为上一层使用32个过滤器所以相当于有32个颜色通道一样。 而这一层我们使用64
    # 个过滤器
    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)

    # 全连接层,经过上面2层以后,图片大小变成了7*7
    # 初始化权重,全连接层我们使用1024个神经元
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    # 铺平图像数据。因为这里不再是卷积计算了,需要把矩阵冲洗reshape成一个一维的向量
    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表示保留不关闭的神经元的比例。为了避免过拟合,这里在全连接层使用dropout方法,
    # 就是随机地关闭掉一些神经元使模型不要与原始数据拟合得辣么准确。
    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.matmul(h_fc1_drop, W_fc2) + b_fc2



    # 训练过程
    # # 1.计算交叉熵损失
    cross_entropy = tf.reduce_mean(
        tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv))

    # # 2.创建优化器(注意这里用  AdamOptimizer代替了梯度下降法)
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

    # # 3. 计算准确率
    correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
import time
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))
with tf.Session() as sess:
    # # 4.初始化所有变量
    sess.run(tf.global_variables_initializer())

    # # 5. 执行循环
    for i in range(1):
        # 每批取出50个训练样本
        batch = mnist.train.next_batch(50)
        # 循环次数是100的倍数的时候,打印准确率信息
        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
        }))
print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())))

结果
由于我电脑问题迭代次数我设置了200,这里设置1为了看结果。迭代200的时候正确率就0.9+
在这里插入图片描述
参考文献:
深度学习基础 (十九)-- 使用 tensorflow 构建一个卷积神经网络 (上)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值