代码实例讲解:卷积神经网络程序细节(附完整代码)

2023-11-12

1、导入数据集和tensorflow包

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

2、初步探索mnist数据集的内容

此处使用mnist数据集,如果需要用自己的数据集,将数据读入pandas的dataframe中即可;

mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)
print(mnist.train.images.shape)
print(mnist.train.labels.shape)
print(mnist.validation.images.shape)
print(mnist.validation.labels.shape)
print(mnist.test.images.shape)
print(mnist.test.labels.shape)
可知mnist由三个部分组成,训练集、测试集、验证集,这三个集合样本个数不一样,但每个样本都是784个元素的数组
想看下长啥样的可以先reshape成28*28的单通道手写图片,然后使用画图工具或者opencv将这个样本集画出来

3、设置神经网络超参数

learning_rate = 0.001
学习率,即是梯度下降时每一步的步长

num_steps = 1000
迭代步数,一般用来设置随机梯度下降进行多少次

batch_size = 128
批次数量,即是一个批次放多少样本,一般可以选择32,64,128
先大后小的设置,批次样本数大,迭代总次数就小,反之就多

n_hidden_1 = 256 
第一个隐藏层的神经元个数,关于神经元个数,可以查看我的另外一篇关于深度学习参数调整的博客

n_hidden_2 = 256 
第二个隐藏层神经元个数,说明此神经网络至少有三层

num_input = 784 
输入样本的特征数,即是每个输入样本有这么多个元素

num_classes = 10 
即是最终样本有这么多个label

4、定义卷积神经网络层级结构

def conv_net(x_dict, n_classes, dropout, reuse, is_training):
    # tf.variable_scope 让不同命名空间中的变量取相同的名字,其后面的第一个参数是命名空间名称
    with tf.variable_scope('ConvNet', reuse=reuse):
        # 输入参数x_dict是一个字典
        x = x_dict['images']

        # mnist数据中的样本格式是(样本个数,784),这里reshape是因为网络能接受的入参要和网络的data_format一致
        # 所以先reshape为 28*28
        # -1的意思表示自适应,最终得到的是样本的数量
        x = tf.reshape(x, shape=[-1, 28, 28, 1])

        # 下面一句话第二个参数32个滤波器,第三个参数表示滤波器大小为5*5 ,第四个参数表示激活函数使用relu
        # 滤波器一般选择2的n次方,比如32,64,滤波器个数越多,提取的feature map越多,但训练参数越多,速度越慢
        conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
        
        # 下面一句话第二个参数表示以步数为2,大小为2*2的最大值池化的滤波器
        conv1 = tf.layers.max_pooling2d(conv1, 2, 2)
        
        # 卷积核数目设置
        # 按照16的倍数倍增,结合了gpu硬件的配置。
        # 一个卷积核对应一个初始的卷积核参数矩阵w,得到一种特征对应的激活层(feature map),最终积累的特征数越多,分类效果肯定越好
        # 因为每个卷积核的初始矩阵都不相同,所以每个卷积核得到的激活层其实也不相同,可以理解为每个卷积核都是训练并提取了一种特征

        
        # Convolution Layer with 64 filters and a kernel size of 3
        conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)
        # Max Pooling (down-sampling) with strides of 2 and kernel size of 2
        conv2 = tf.layers.max_pooling2d(conv2, 2, 2)

        # 将计算完的数据,拉伸为1维的方便做全连接处理
        fc1 = tf.contrib.layers.flatten(conv2)

        # Fully connected layer (in tf contrib folder for now)
        # 定义一个全连接网络,第一个参数表示输入的计算结果,第二个参数是输出维度,相当于是做一个降维处理
        fc1 = tf.layers.dense(fc1, 1024)
        # 定义一个随机失活,需不需要随机失活看training这个参数
        fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)

        # 在进行全连接,第一个参数表示输入,第二个参数表示输出维度,同样是降维处理
        out = tf.layers.dense(fc1, n_classes)

    return out

5、定义model_fn

def model_fn(features, labels, mode):
    # 构建两个卷积神经网络,一个是训练网络,一个是测试网络
    logits_train = conv_net(features, num_classes, dropout, reuse=False,
                            is_training=True)
    logits_test = conv_net(features, num_classes, dropout, reuse=True,
                           is_training=False)

    # 定义预测的operation
    # 预测的分类器是softmax
    pred_classes = tf.argmax(logits_test, axis=1)
    pred_probas = tf.nn.softmax(logits_test)

    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)

    # 定义损失和优化器
    # 损失计算方法为L2
    # 优化器选择 adam
    # 训练目标为最小化损失函数optimizer.minimize()
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op,
                                  global_step=tf.train.get_global_step())

    # 计算模型的准确率
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)

    # 返回一个EstimatorSpec的对象
    # EstimatorSpec对象返回一个准确率的键值对:{'accuracy': acc_op},所以训练结束后可以通过'accuracy'键返回值
    estim_specs = tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=pred_classes,
        loss=loss_op,
        train_op=train_op,
        eval_metric_ops={'accuracy': acc_op})

    return estim_specs

6、创建Estimator实例

model = tf.estimator.Estimator(model_fn)

7、定义训练过程input_fn函数

input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.train.images}, y=mnist.train.labels,
    batch_size=batch_size, num_epochs=None, shuffle=True)
这个函数的作用是生成一个评估器对象能接受的标准输入格式,其实是一个输入组装的过程

8、开始启动模型训练

前面的所有定义,都是逻辑上的定义,到了这一步才是真的开始触发训练
model.train(input_fn, steps=num_steps)
# Evaluate the Model

9、定义验证过程的input_fn

input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, y=mnist.test.labels,
    batch_size=batch_size, shuffle=False)
逻辑同上面的训练过程

10、开始启动验证过程

e = model.evaluate(input_fn)

11、打印模型在验证集中的准确率

print("Testing Accuracy:", e['accuracy'])

12、附完整代码

from __future__ import division, print_function, absolute_import
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=False)

import tensorflow as tf

# Training Parameters
learning_rate = 0.001
num_steps = 2000 #这个步数即是随机梯度下降中,随机下降多少次
batch_size = 128 #一个batch_size是128个样本,一个epoch有多个batch

# Network Parameters
num_input = 784 # MNIST data input (img shape: 28*28)
num_classes = 10 # MNIST total classes (0-9 digits)
dropout = 0.25 # Dropout, probability to drop a unit

# 定义卷积神经网络层级结构
def conv_net(x_dict, n_classes, dropout, reuse, is_training):
    # tf.variable_scope 让不同命名空间中的变量取相同的名字,其后面的第一个参数是命名空间名称
    with tf.variable_scope('ConvNet', reuse=reuse):
        # 输入参数x_dict是一个字典
        x = x_dict['images']

        # mnist数据中的样本格式是(样本个数,784),这里reshape是因为网络能接受的入参要和网络的data_format一致
          #那mnist数据中的样本都是单通道?
        # 所以先reshape为 28*28
        # -1的意思表示自适应,最终得到的是样本的数量
        x = tf.reshape(x, shape=[-1, 28, 28, 1])

        # 下面一句话第二个参数32个滤波器,第三个参数表示滤波器大小为5*5 ,第四个参数表示激活函数使用relu
        conv1 = tf.layers.conv2d(x, 32, 5, activation=tf.nn.relu)
        # 下面一句话第二个参数表示以步数为2,大小为2*2的最大值池化的滤波器
        conv1 = tf.layers.max_pooling2d(conv1, 2, 2)
        
        # 卷积核数目设置
        # 按照16的倍数倍增,结合了gpu硬件的配置。
        # 一个卷积核对应一个初始的卷积核参数矩阵w,得到一种特征对应的激活层(feature map),最终积累的特征数越多,分类效果肯定越好
        # 因为每个卷积核的初始矩阵都不相同,所以每个卷积核得到的激活层其实也不相同,可以理解为每个卷积核都是训练并提取了一种特征

        
        # Convolution Layer with 64 filters and a kernel size of 3
        conv2 = tf.layers.conv2d(conv1, 64, 3, activation=tf.nn.relu)
        # Max Pooling (down-sampling) with strides of 2 and kernel size of 2
        conv2 = tf.layers.max_pooling2d(conv2, 2, 2)

        # 将计算完的数据,拉伸为1维的方便做全连接处理
        fc1 = tf.contrib.layers.flatten(conv2)

        # Fully connected layer (in tf contrib folder for now)
        # 定义一个全连接网络,第一个参数表示输入的计算结果,第二个参数是输出维度,相当于是做一个降维处理
        fc1 = tf.layers.dense(fc1, 1024)
        # 定义一个随机失活,需不需要随机失活看training这个参数
        fc1 = tf.layers.dropout(fc1, rate=dropout, training=is_training)

        # 在进行全连接,第一个参数表示输入,第二个参数表示输出维度,同样是降维处理
        out = tf.layers.dense(fc1, n_classes)

    return out

# 根据TF的评估器模板,定义训练模型
def model_fn(features, labels, mode):
    # 构建两个卷积神经网络,一个是训练网络,一个是测试网络
    logits_train = conv_net(features, num_classes, dropout, reuse=False,
                            is_training=True)
    logits_test = conv_net(features, num_classes, dropout, reuse=True,
                           is_training=False)

    # 定义预测的operation
    # 预测的分类器是softmax
    pred_classes = tf.argmax(logits_test, axis=1)
    pred_probas = tf.nn.softmax(logits_test)

    # If prediction mode, early return
    if mode == tf.estimator.ModeKeys.PREDICT:
        return tf.estimator.EstimatorSpec(mode, predictions=pred_classes)

    # 定义损失和优化器
    # 损失计算方法为L2
    # 优化器选择 adam
    # 训练目标为最小化损失函数optimizer.minimize()
    loss_op = tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(
        logits=logits_train, labels=tf.cast(labels, dtype=tf.int32)))
    optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)
    train_op = optimizer.minimize(loss_op,
                                  global_step=tf.train.get_global_step())

    # 计算模型的准确率
    acc_op = tf.metrics.accuracy(labels=labels, predictions=pred_classes)

    # 返回一个EstimatorSpec的对象
    # EstimatorSpec对象返回一个准确率的键值对:{'accuracy': acc_op},所以训练结束后可以通过'accuracy'键返回值
    estim_specs = tf.estimator.EstimatorSpec(
        mode=mode,
        predictions=pred_classes,
        loss=loss_op,
        train_op=train_op,
        eval_metric_ops={'accuracy': acc_op})

    return estim_specs

# Build the Estimator
model = tf.estimator.Estimator(model_fn)

# input_fn是评估器训练模型的时候能接受的入参的特殊格式
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.train.images}, y=mnist.train.labels,
    batch_size=batch_size, num_epochs=None, shuffle=True)

# Train the Model
model.train(input_fn, steps=num_steps)
# Evaluate the Model

# Define the input function for evaluating
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, y=mnist.test.labels,
    batch_size=batch_size, shuffle=False)

# 评估/测试训练好的模型
e = model.evaluate(input_fn)
print("Testing Accuracy:", e['accuracy'])
# 这里得到的是准确率,假如准确率足够的话,怎么使用这个模型进行预测呢?
# Estimator有专门的预测的函数,predict(self, input_fn, predict_keys=None, hooks=None, checkpoint_path=None, yield_single_examples=True)

#使用训练好的模型进行预测
input_fn = tf.estimator.inputs.numpy_input_fn(
    x={'images': mnist.test.images}, shuffle=False)
predictions = model.predict(input_fn)  #返回一个预测分类的列表
for pred_dict in predictions:
        print(pred_dict)

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

代码实例讲解:卷积神经网络程序细节(附完整代码) 的相关文章

  • golang The system cannot find the file specified

    使用io ioutil包读取文件时报错 open abi The system cannot find the file specified 原因是 ioutil ReadFile 这个方法需要传入决绝路径的文件名 代码 abiStr er
  • ESP32 之 ESP-IDF 教学(十一)WiFi篇—— WiFi两种模式

    本文章 来自原创专栏 ESP32教学专栏 基于ESP IDF 讲解如何使用 ESP IDF 构建 ESP32 程序 发布文章并会持续为已发布文章添加新内容 每篇文章都经过了精打细磨 通过下方对话框进入专栏目录页 CSDN 请求进入目录 O
  • 安全模型和业务安全体系

    网络安全和业务安全 网络安全中 攻击者往往通过技术手段 以非正常的技术 XSS Injection Penestrating等 影响业务正常运行 窃取敏感数据 比如 某黑客通过SSRF进入内网 并在内网横向扩张 最终脱库成功 业务安全中 黑
  • 如何理解和解决CXXABI not found问题?

    编译C 程序时 在链接阶段有时会出现CXXABI not found的问题 usr lib64 libstdc so 6 version CXXABI 1 3 8 not found 问题出现的场景 当前编译的程序需要依赖其它已编译的组件

随机推荐

  • vtk中的点云曲面重建

    对于光学扫描设备 如激光雷达 采集到的非规则点云数据 最重要的需求之一就是进行表面重建 Surface Reconstruction 对成片密集分布的点云以三角片拟合 形成连续 精确 良态的曲面表示 目前主流的算法可分为剖分类 组合类和拟合
  • win11管理我的账户提示“无法使用个人帐户在此登录,请改用工作或学校帐户”

    先把所有账户删除 注销Store 重新登陆账户 登录后选择自动登录到所有Microsoft应用就好了
  • 210. 课程表 II

    文章目录 Tag 题目来源 题目解读 解题思路 方法一 拓扑排序 写在最后 Tag 拓扑排序 题目来源 210 课程表 II 题目解读 在选修某些课程之前需要先学习某些课程 先学习的课程有数组 prerequisites 给出 其中 pre
  • NAT和全网互通

    首先在GWserver设备上安装一个 路由和远程访问 然后打开路由和远程访问右键新建nat
  • 怎么用计算机测量一个物体的高度,常用测量工具的使用方法?

    工具分类测量工具通常按用途分为通用测量工具 专类测量工具和专用测量工具3类 测量工具还可按工作原理分为机械 光学 气动 电动和光电等类型 这种分类方法是由测量工具的发展历史形成的 但一些现代测量工具已经发展成为同时采用精密机械 光 电等原理
  • Ubuntu安装SSH服务

    注 安装前需要先将 源 配置好 以下演示为root账号 1 更新软件源 apt get install y update 2 安装openssl apt get install y update apt get install y open
  • Set集合框架

    前言 给大家讲讲Set结合框架 码字不易 点个关注 转载请说明 思维导图 目录 1 List和Set的区别 1 两者的特点 2 两者之间的对比 3 取值 2 Set集合的特点 3 Set集合的循环方式 4 HashSet去重复以及原理 1
  • git修改分支名

    使用git命令操作 1 修改本地分支名称 git branch m oldBranchName newBranchName 2 将本地分支的远程分支删除 git push delete origin oldBranchName 3 将改名后
  • virtual usb multikey安装设备时出现错误_【图解USB】USB 之CDC 程序结构(完结篇)...

    来源 公众号 鱼鹰谈单片机 作者 鱼鹰Osprey ID emOsprey本篇介绍整个例程的结构和程序流程 Github 里面有一个仓库CMSIS DAP https github com x893 CMSIS DAP 该工程可以导入到gi
  • 强化学习 最前沿之graph policy gradients

    强化学习 Zee最前沿系列 深度强化学习作为当前发展最快的方向 可以说是百家争鸣的时代 针对特定问题 针对特定环境的文章也层出不穷 对于这么多的文章和方向 如果能撇一隅 往往也能够带来较多的启发 本系列文章 主要是针对当前较新的深度强化学习
  • 使用SQL语句操作数据表和管理表中的数据

    一 使用SQL语句操作数据表 表名是可以在数据库中唯一确定的一张表 1 创建表 语法 create table 表的名字 列名1 数据类型 列名2 数据类型 列名3 数据类型 注意 创建表之后括号后应该用分号结束 并且在列名和数据类型的最后
  • Windows平台下安装与配置MySQL

    免费下载网址 https dev mysql com downloads windows installer 8 0 html 版本选择 社区版8 0 20 双击安装包 选择Developer Default 下一步 点Execute执行
  • C语言 - static inline

    2019 07 16 今天在看DPDK负载均衡的实例代码中 通过函数跳转 看到官方API后 发现了static inline这个关键字 这个我只是在很早之前知道inline是内联的 可以不进行压栈 但是static毕竟是限制函数的作用域的啊
  • Sentinel实现熔断与限流

    文章目录 一 Sentinel是什么 1 简介 2 对比 3 Linux安装 二 初始化演示工程 1 新建module cloudalibaba sentinel service8401 2 pom文件 3 application yml
  • 个人总结:京东技术体系员工级别划分及薪资区间

    管理层级 序列层级 职衔 对应T序 薪资区间 技术 M5 CXO M5 VP M4 3 高级总监 M4 2 总监 T5 40 50k M4 1 副总监 T5 35 45k M3 高级经理 T4 2 30 40k M2 2 经理 T4 1 2
  • 【ReID】【代码注释】采样器 deep-person-reid/samplers.py

    源码URL https github com michuanhaohao deep person reid blob master samplers py 采样器读源码注释如下 from future import absolute imp
  • Java三大器之拦截器(Interceptor)的实现原理及代码示例

    前言 前面2篇博客 我们分析了Java中过滤器和监听器的实现原理 今天我们来看看拦截器 1 拦截器的概念 java里的拦截器是动态拦截Action调用的对象 它提供了一种机制可以使开发者在一个Action执行的前后执行一段代码 也可以在一个
  • ImportError: cannot import name ‘mean_absolute_percentage_error‘ from ‘sklearn.metrics‘

    在使用mean absolute percentage error时 导入模块报错 from sklearn metrics import mean absolute percentage error 报错信息 ImportError ca
  • python将字符串转为字典(将str类型还原为dict字典类型)

    有三种方法 eval 字符串 yaml load 字符串 Loader yaml FullLoader ast literal eval 字符串 但是要注意 转换之前 原始的字典中key与value必须是python原生支持的类型 不能是d
  • 代码实例讲解:卷积神经网络程序细节(附完整代码)

    1 导入数据集和tensorflow包 from tensorflow examples tutorials mnist import input data import tensorflow as tf 2 初步探索mnist数据集的内容