今天分享同样数据集的CNN处理方式,同时加上tensorboard,可以看到清晰的结构图,迭代1000次acc收敛到0.992 先放代码,注释比较详细,变量名字看单词就能知道啥意思

import tensorflow as tf
import tensorflow.examples.tutorials.mnist.input_data as input_data
 
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)
 
batch_size = 100
n_batch = mnist.train.num_examples // batch_size
 
def weight_variable(shape, name):
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial, name=name)
 
def bias_variable(shape, name):
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial, name=name)
 
def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding="SAME")     # 1, 3位是1/   2, 4位是步长
 
def max_pool_2x2(x):
    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding="SAME")  # 2, 3是步长
 
with tf.name_scope('input'):
    x = tf.placeholder(tf.float32, [None, 784], name='x_input')
    y = tf.placeholder(tf.float32, [None, 10], name='y_input')
    with tf.name_scope('x_image'):
        # 转变x格式为4D向量[batch, in_height, in_width, in_channels] 通道为1表示黑白
        x_image = tf.reshape(x, [-1, 28, 28, 1], name='x_image')
 
with tf.name_scope('Converlution_1'):
    # 初始化第一个卷积层的权重和偏置
    with tf.name_scope('Weight_Converlution_1'):
        Weight_Converlution_1 = weight_variable([5, 5, 1, 32],
                                                name='Weight_Converlution_1')  # 5 * 5的卷积窗口,32个卷积核从1个平面抽取特征
                                                                                # 生成32个特征图
    with tf.name_scope('Biase_Converlution_1'):
        Biase_Converlution_1 = bias_variable([32], name='Biase_Converlution_1')  # 每个卷积核一个偏置值
 
    # 把x_image和权值向量进行卷积,再加上偏置值,应用于relu激活函数
    with tf.name_scope('Converlution2d_1'):
        Converlution2d_1 = conv2d(x_image, Weight_Converlution_1) + Biase_Converlution_1
    with tf.name_scope('ReLu_1'):
        ReLu_Converlution_l = tf.nn.relu(Converlution2d_1)
    with tf.name_scope('Pool_1'):
        Pooling_1 = max_pool_2x2(ReLu_Converlution_l)  # max-pooling
 
with tf.name_scope('Converlution_2'):
    # 初始化第二个卷积层的权重和偏置
    with tf.name_scope('Weight_Converlution_2'):
        Weight_Converlution_2 = weight_variable([5, 5, 32, 64],
                                                name='Weight_Converlution_2')  # 5 * 5的卷积窗口,64个卷积核从32个平面抽取特征
        # 生成64个特征图
    with tf.name_scope('Biase_Converlution_2'):
        Biase_Converlution_2 = bias_variable([64], name='Biase_Converlution_2')
    with tf.name_scope('Cov2d_2'):
        Converlution2d_2 = conv2d(Pooling_1, Weight_Converlution_2) + Biase_Converlution_2
    with tf.name_scope('ReLu_2'):
        ReLu_Converlution_2 = tf.nn.relu(Converlution2d_2)
    with tf.name_scope('Pool_2'):
        Pooling_2 = max_pool_2x2(ReLu_Converlution_2)
 
# 初始化第一个全连接层
with tf.name_scope('Fully_Connected_L1'):
    with tf.name_scope('Weight_Fully_Connected_L1'):
        Weight_Fully_Connected_L1 = weight_variable([7 * 7 * 64, 1024],
                                                    name='Weight_Fully_Connected_L1')  # 上一层有7*7*64个神经元,全连接层有1024个神经元
    with tf.name_scope('Biase_Fully_Connected_L1'):
        Biase_Fully_Connected_L1 = bias_variable([1024], name='Biase_Fully_Connected_L1')
 
    # 把池化层2的输出扁平化为1维
    with tf.name_scope('Pooling_2_to_Flat'):
        Pooling_2_to_Flat = tf.reshape(Pooling_2, [-1, 7 * 7 * 64], name='Pooling_2_to_Flat')  # -1表示任意值
    with tf.name_scope('Wx_Plus_B1'):
        Wx_Plus_B1 = tf.matmul(Pooling_2_to_Flat, Weight_Fully_Connected_L1) + Biase_Fully_Connected_L1
    with tf.name_scope('ReLu_Fully_Connected_L1'):
        ReLu_Fully_Connected_L1 = tf.nn.relu(Wx_Plus_B1)
    # Keep——Prob
    with tf.name_scope('keep_prob'):
        keep_prob = tf.placeholder(tf.float32, name='keep_prob')
    with tf.name_scope('Fully_Connected_L1_Drop'):
        Fully_Connected_L1_Drop = tf.nn.dropout(ReLu_Fully_Connected_L1, keep_prob, name='Fully_Connected_L1_Drop')
 
# 初始化第二个全连接层
with tf.name_scope('Fully_Connected_L2'):
    with tf.name_scope('Weight_Fully_Connected_L2'):
        Weight_Fully_Connected_L2 = weight_variable([1024, 10], name='Weight_Fully_Connected_L2')
    with tf.name_scope('Biase_Fully_Connected_L2'):
        Biase_Fully_Connected_L2 = bias_variable([10], name='Biase_Fully_Connected_L1')
    with tf.name_scope('Wx_Plus_B2'):
        Wx_Plus_B2 = tf.matmul(Fully_Connected_L1_Drop, Weight_Fully_Connected_L2) + Biase_Fully_Connected_L2
    with tf.name_scope('SoftMax'):
        prediction = tf.nn.softmax(Wx_Plus_B2)
# 交叉熵函数
with tf.name_scope('cross_entropy'):
    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(labels=y,
                                                                              logits=prediction), name='cross_entropy')
    tf.summary.scalar('cross_entropy', cross_entropy)    # 显示标量信息  tf.summary.scalar(tags, values, collections=None, name=None)
# AdamOptimizer优化器
with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
 
with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
        correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
    with tf.name_scope('accuracy'):
        accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
        tf.summary.scalar('accuracy', accuracy)
 
# 合并所有summary
merged = tf.summary.merge_all()
 
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    train_writer = tf.summary.FileWriter('logs/train', sess.graph)
    test_writer = tf.summary.FileWriter('logs/test', sess.graph)
    for i in range(101):
        batch_xs, batch_ys = mnist.train.next_batch(batch_size)
        sess.run(train_step, feed_dict={x: batch_xs,
                                        y: batch_ys,
                                        keep_prob: 0.5})
        # 记录训练集计算的参数
        summary = sess.run(merged, feed_dict={x: batch_xs,
                                              y: batch_ys,
                                              keep_prob: 1})
        train_writer.add_summary(summary, i)
 
        # 记录训练集计算的参数
        batch_xs, batch_ys = mnist.test.next_batch(batch_size)
 
        summary = sess.run(merged, feed_dict={x: batch_xs,
                                              y: batch_ys,
                                              keep_prob: 1.0})
        test_writer.add_summary(summary, i)
 
        test_acc = sess.run(accuracy, feed_dict={x: mnist.test.images,
                                                 y: mnist.test.labels,
                                                 keep_prob: 1.0})
        train_acc = sess.run(accuracy, feed_dict={x: mnist.train.images[:10000],
                                                  y: mnist.train.labels[:10000],
                                                  keep_prob: 1.0})
        print("Iter " + str(i) +
              ", Testing Accuracy " + str(test_acc) +
              ", Training Accuracy " + str(train_acc))

  

神经网络MNIST数据集分类tensorboard的更多相关文章

  1. 机器学习与Tensorflow(3)—— 机器学习及MNIST数据集分类优化

    一.二次代价函数 1. 形式: 其中,C为代价函数,X表示样本,Y表示实际值,a表示输出值,n为样本总数 2. 利用梯度下降法调整权值参数大小,推导过程如下图所示: 根据结果可得,权重w和偏置b的梯度 ...

  2. 3.keras-简单实现Mnist数据集分类

    keras-简单实现Mnist数据集分类 1.载入数据以及预处理 import numpy as np from keras.datasets import mnist from keras.util ...

  3. 6.keras-基于CNN网络的Mnist数据集分类

    keras-基于CNN网络的Mnist数据集分类 1.数据的载入和预处理 import numpy as np from keras.datasets import mnist from keras. ...

  4. 深度学习(一)之MNIST数据集分类

    任务目标 对MNIST手写数字数据集进行训练和评估,最终使得模型能够在测试集上达到\(98\%\)的正确率.(最终本文达到了\(99.36\%\)) 使用的库的版本: python:3.8.12 py ...

  5. Tensorflow学习教程------普通神经网络对mnist数据集分类

    首先是不含隐层的神经网络, 输入层是784个神经元 输出层是10个神经元 代码如下 #coding:utf-8 import tensorflow as tf from tensorflow.exam ...

  6. 卷积神经网络应用于MNIST数据集分类

    先贴代码 import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = inpu ...

  7. MNIST数据集分类简单版本

      import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data #载入数据集 mnist = ...

  8. 6.MNIST数据集分类简单版本

    import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 载入数据集 mnist = i ...

  9. MNIST数据集

    一.MNIST数据集分类简单版本 import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data # ...

随机推荐

  1. Ubuntu查看与结束任务进程

    1.打开终端 2.敲  ps -ef  查出进程的编号(就是PID那列) 3.输入 kill PID 即可(如果PID是123456,则kill 123456) 例如: 我想把splash关闭,直接输 ...

  2. ADB 常用命令及详解

    1.pull文件 adb pull (文件路径) (想要pull的路径) MacBook-Pro:~ caris$ adb pull /sdcard/Android/data/com.xiwi.log ...

  3. PHP设计模式 - 桥接模式

    将抽象部分与它的实现部分分离,使他们都可以独立的变抽象与它的实现分离,即抽象类和它的派生类用来实现自己的对象 桥接与适配器模式的关系(适配器模式上面已讲解): 桥接属于聚合关系,两者关联 但不继承 适 ...

  4. GraphQL简介

    原文地址 https://flaviocopes.com/graphql/ 中译文地址 什么是GraphQL GraphQL的原则 GraphQL vs REST Rest是一个概念 单个端点 根据你 ...

  5. Worker Thread模式

    工人线程Worker thread会逐个取回工作并进行处理,当所有工作全部完成后,工人线程会等待新的工作到来 5个工人线程从传送带取数据,3个传送工人线程将数据放入传送带 public class C ...

  6. CF28B pSort

    题目描述 给定一个含有n个元素的数列,第i号元素开始时数值为i,元素i可以与距离为d[i]的元素进行交换.再给定一个1-n的全排列,问初始的数列可否交换成给定的样式. 输入:第一行一个整数n,第二行n ...

  7. C++Primer 5th Chap2 Variables and basic Types

    wchar_t,char16_t,char32_t用于拓展字符集 char和signed char并不一样,由编译器决定类型char表现上述两种中的哪一种 一般long的大小和int无二,如果超过in ...

  8. PAT(B) 1090 危险品装箱(Java)

    题目链接:1090 危险品装箱 (25 point(s)) 题目描述 集装箱运输货物时,我们必须特别小心,不能把不相容的货物装在一只箱子里.比如氧化剂绝对不能跟易燃液体同箱,否则很容易造成爆炸. 本题 ...

  9. 【微信小程序学习笔记】入门与了解

    [微信小程序学习笔记(一)] IDE 下载安装 下载地址 官方工具:https://mp.weixin.qq.com/debug/w … tml?t=1476434678461 下载可执行文件后,可按 ...

  10. Unity - Profiler参数详解

    CPU Usage ​       ● GC Alloc - 记录了游戏运行时代码产生的堆内存分配.这会导致ManagedHeap增大,加速GC的到来.我们要尽可能避免不必要的堆内存分配,同时注意:1 ...