基于TensorFlow实现的CNN神经网络 花卉识别系统Demo

  • Demo展示
    • 登录与注册
    • 主页面
    • 模型训练
    • 识别
  • 神经网络
  • 训练
  • Demo下载

Demo展示

登录与注册



主页面



模型训练

识别


神经网络

定义CNN网络结构
卷积神经网络,卷积加池化2,全连接2,softmax分类
关键代码:

# 定义函数infence,定义CNN网络结构
# 卷积神经网络,卷积加池化*2,全连接*2,softmax分类
# 卷积层1
def inference(images, batch_size, n_classes):with tf.variable_scope('conv1') as scope:weights = tf.Variable(tf.truncated_normal(shape=[3, 3, 3, 64], stddev=1.0, dtype=tf.float32),name='weights', dtype=tf.float32)biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[64]),name='biases', dtype=tf.float32)conv = tf.nn.conv2d(images, weights, strides=[1, 1, 1, 1], padding='SAME')pre_activation = tf.nn.bias_add(conv, biases)conv1 = tf.nn.relu(pre_activation, name=scope.name)# 池化层1# 3x3最大池化,步长strides为2,池化后执行lrn()操作,局部响应归一化,对训练有利。with tf.variable_scope('pooling1_lrn') as scope:pool1 = tf.nn.max_pool(conv1, ksize=[1, 3, 3, 1], strides=[1, 2, 2, 1], padding='SAME', name='pooling1')norm1 = tf.nn.lrn(pool1, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm1')# 卷积层2# 16个3x3的卷积核(16通道),padding=’SAME’,表示padding后卷积的图与原图尺寸一致,激活函数relu()with tf.variable_scope('conv2') as scope:weights = tf.Variable(tf.truncated_normal(shape=[3, 3, 64, 16], stddev=0.1, dtype=tf.float32),name='weights', dtype=tf.float32)biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[16]),name='biases', dtype=tf.float32)conv = tf.nn.conv2d(norm1, weights, strides=[1, 1, 1, 1], padding='SAME')pre_activation = tf.nn.bias_add(conv, biases)conv2 = tf.nn.relu(pre_activation, name='conv2')# 池化层2# 3x3最大池化,步长strides为2,池化后执行lrn()操作,# pool2 and norm2with tf.variable_scope('pooling2_lrn') as scope:norm2 = tf.nn.lrn(conv2, depth_radius=4, bias=1.0, alpha=0.001 / 9.0, beta=0.75, name='norm2')pool2 = tf.nn.max_pool(norm2, ksize=[1, 3, 3, 1], strides=[1, 1, 1, 1], padding='SAME', name='pooling2')# 全连接层3# 128个神经元,将之前pool层的输出reshape成一行,激活函数relu()with tf.variable_scope('local3') as scope:reshape = tf.reshape(pool2, shape=[batch_size, -1])dim = reshape.get_shape()[1].valueweights = tf.Variable(tf.truncated_normal(shape=[dim, 128], stddev=0.005, dtype=tf.float32),name='weights', dtype=tf.float32)biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[128]),name='biases', dtype=tf.float32)local3 = tf.nn.relu(tf.matmul(reshape, weights) + biases, name=scope.name)# 全连接层4# 128个神经元,激活函数relu()with tf.variable_scope('local4') as scope:weights = tf.Variable(tf.truncated_normal(shape=[128, 128], stddev=0.005, dtype=tf.float32),name='weights', dtype=tf.float32)biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[128]),name='biases', dtype=tf.float32)local4 = tf.nn.relu(tf.matmul(local3, weights) + biases, name='local4')# dropout层#    with tf.variable_scope('dropout') as scope:#        drop_out = tf.nn.dropout(local4, 0.8)# Softmax回归层# 将前面的FC层输出,做一个线性回归,计算出每一类的得分with tf.variable_scope('softmax_linear') as scope:weights = tf.Variable(tf.truncated_normal(shape=[128, n_classes], stddev=0.005, dtype=tf.float32),name='softmax_linear', dtype=tf.float32)biases = tf.Variable(tf.constant(value=0.1, dtype=tf.float32, shape=[n_classes]),name='biases', dtype=tf.float32)softmax_linear = tf.add(tf.matmul(local4, weights), biases, name='softmax_linear')return softmax_linear# -----------------------------------------------------------------------------
# loss计算
# 传入参数:logits,网络计算输出值。labels,真实值,在这里是0或者1
# 返回参数:loss,损失值
def losses(logits, labels):with tf.variable_scope('loss') as scope:cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=labels, name='xentropy_per_example')loss = tf.reduce_mean(cross_entropy, name='loss')tf.summary.scalar(scope.name + '/loss', loss)return loss# --------------------------------------------------------------------------
# loss损失值优化
# 输入参数:loss。learning_rate,学习速率。
# 返回参数:train_op,训练op,这个参数要输入sess.run中让模型去训练。
def trainning(loss, learning_rate):with tf.name_scope('optimizer'):optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate)global_step = tf.Variable(0, name='global_step', trainable=False)train_op = optimizer.minimize(loss, global_step=global_step)return train_op# -----------------------------------------------------------------------
# 评价/准确率计算
# 输入参数:logits,网络计算值。labels,标签,也就是真实值,在这里是0或者1。
# 返回参数:accuracy,当前step的平均准确率,也就是在这些batch中多少张图片被正确分类了。
def evaluation(logits, labels):with tf.variable_scope('accuracy') as scope:correct = tf.nn.in_top_k(logits, labels, 1)correct = tf.cast(correct, tf.float16)accuracy = tf.reduce_mean(correct)tf.summary.scalar(scope.name + '/accuracy', accuracy)return accuracy

训练

关键代码:

class Train:path, train_dir, logs_train_dir = None, None, Nonedef __init__(self):self.path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))self.train_dir = self.path + '/input_data'  # 训练样本的读入路径self.logs_train_dir = self.path + '/save'  # logs存储路径def train(self, BATCH_SIZE=20, MAX_STEP=1000, learning_rate=0.0001):# 变量声明N_CLASSES = 4  # 四种花类型IMG_W = 64  # resize图像,太大的话训练时间久IMG_H = 64CAPACITY = 200# 获取批次batch# train, train_label = input_data.get_files(train_dir)train, train_label, val, val_label = input_data.get_files(self.train_dir, 0.3)# 训练数据及标签train_batch, train_label_batch = input_data.get_batch(train, train_label, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)# 测试数据及标签val_batch, val_label_batch = input_data.get_batch(val, val_label, IMG_W, IMG_H, BATCH_SIZE, CAPACITY)# 训练操作定义train_logits = model.inference(train_batch, BATCH_SIZE, N_CLASSES)train_loss = model.losses(train_logits, train_label_batch)train_op = model.trainning(train_loss, learning_rate)train_acc = model.evaluation(train_logits, train_label_batch)# 测试操作定义test_logits = model.inference(val_batch, BATCH_SIZE, N_CLASSES)test_loss = model.losses(test_logits, val_label_batch)test_acc = model.evaluation(test_logits, val_label_batch)# 这个是log汇总记录summary_op = tf.summary.merge_all()# 产生一个会话sess = tf.Session()# 产生一个writer来写log文件train_writer = tf.summary.FileWriter(self.logs_train_dir, sess.graph)# 产生一个saver来存储训练好的模型saver = tf.train.Saver()# 所有节点初始化sess.run(tf.initialize_all_variables())# 队列监控coord = tf.train.Coordinator()threads = tf.train.start_queue_runners(sess=sess, coord=coord)# 进行batch的训练try:print('批次为:{},步数为:{},学习率为:{}'.format(BATCH_SIZE, MAX_STEP, learning_rate))# 执行MAX_STEP步的训练,一步一个batchfor step in np.arange(MAX_STEP + 1):if coord.should_stop():break_, tra_loss, tra_acc = sess.run([train_op, train_loss, train_acc])# 每隔50步打印一次当前的loss以及acc,同时记录log,写入writerif step % 10 == 0:print('步数:%d, loss:%.2f, 训练准确率:%.2f%%' % (step, tra_loss, tra_acc * 100.0))summary_str = sess.run(summary_op)train_writer.add_summary(summary_str, step)# 每隔100步,保存一次训练好的模型if (step) == MAX_STEP:checkpoint_path = os.path.join(self.logs_train_dir, 'model.ckpt')saver.save(sess, checkpoint_path, global_step=step)except tf.errors.OutOfRangeError:print('到达训练上限,训练完成')finally:coord.request_stop()if __name__ == '__main__':Train().train()

Demo下载

大家喜欢的话,希望可以star一下,谢谢。
https://github.com/JJJiangYH/Flower-Distinguish

基于TensorFlow实现的CNN神经网络 花卉识别系统Demo相关推荐

  1. 基于TensorFlow Lite实现的Android花卉识别应用

    介绍 本教程将在Android设备上使用TensorFlow Lite运行图像识别模型,具体包括: 使用TensorFlow Lite Model Maker训练自定义的图像分类器 利用Android ...

  2. CV之CNN:基于tensorflow框架采用CNN(改进的AlexNet,训练/评估/推理)卷积神经网络算法实现猫狗图像分类识别

    CV之CNN:基于tensorflow框架采用CNN(改进的AlexNet,训练/评估/推理)卷积神经网络算法实现猫狗图像分类识别 目录 基于tensorflow框架采用CNN(改进的AlexNet, ...

  3. CV之IC之AlexNet:基于tensorflow框架采用CNN卷积神经网络算法(改进的AlexNet,训练/评估/推理)实现猫狗分类识别案例应用

    CV之IC之AlexNet:基于tensorflow框架采用CNN卷积神经网络算法(改进的AlexNet,训练/评估/推理)实现猫狗分类识别案例应用 目录 基于tensorflow框架采用CNN(改进 ...

  4. 基于神经网络的花卉识别系统,可以识别10种花的类型:向日葵、月季、玫瑰、仙人掌、牡丹等

    基于神经网络的花卉识别系统,可以识别10种花的类型:向日葵.月季.玫瑰.仙人掌.牡丹等,精度可达95. 系统可手动自主选择图片导入识别,识别结果可通过标签形式标注在图片上生成到本地,便于归档和实时验证 ...

  5. 基于Tensorflow + Opencv 实现CNN自定义图像分类

    摘要:本篇文章主要通过Tensorflow+Opencv实现CNN自定义图像分类案例,它能解决我们现实论文或实践中的图像分类问题,并与机器学习的图像分类算法进行对比实验. 本文分享自华为云社区< ...

  6. 基于Pytorch框架的轻量级卷积神经网络垃圾分类识别系统

    今天在查资料的时候在网上看到一篇文章,博主是基于TensorFlow实现的CNN来完成对垃圾分类识别的,想到最近正好在使用Pytorch就想也做一下,就当是项目开发实践了.先看下动态操作效果: 原文在 ...

  7. 基于tensorflow2.0+opencv的花卉识别系统源码(含数据集)

    花卉识别-基于tensorflow2.3实现 完整代码下载地址:基于tensorflow2.0+opencv的花卉识别系统源码( 文件目录 # 数据下载地址 https://storage.googl ...

  8. TF之LiR:基于tensorflow实现手写数字图片识别准确率

    TF之LiR:基于tensorflow实现手写数字图片识别准确率 目录 输出结果 代码设计 输出结果 Extracting MNIST_data\train-images-idx3-ubyte.gz ...

  9. 基于BP神经网络车牌识别系统的设计与实现

    1.1 题目的主要研究内容 (1)工作的主要描述 使用MATLAB将采集到的图像信息读入,采用一系列的方法对图像信息进行预处理:再分析不同像素点分布与边缘的相应变化范围,从而确定牌照的大致位置,由此分 ...

最新文章

  1. Hadoop集群搭建(四:Zookeeper环境安装)
  2. const 与 static readonly 的区别
  3. 隋唐5s与linux的关系,我与Linux
  4. 指针和Const限定符
  5. python3多线程queue_Python多线程(3)——Queue模块
  6. [UOJ299][CTSC2017] 游戏
  7. 黑马程序员—多线程,单线程
  8. JVM堆外内存的回收机制分析
  9. windows系统bat批处理 一键添加共享打印机
  10. vasp如何杀掉任务_如何优雅地在学堂路上骑着车跑代码
  11. BatchNormalization 优点
  12. 服务器网卡驱动装好后本地连接显示,系统装好后网卡驱动也装好了,可是没有本地连接,怎么弄...
  13. 软考 系统架构设计师 2009-2018年英语翻译及重点词汇
  14. windows ssh命令_如何启用和使用Windows 10的新内置SSH命令
  15. maya表面种植物体插件 Plant Objects on surface v1.0 下载及教程
  16. vue-router路由防卫
  17. JS 流行库(三):Zepto
  18. html设置背景颜色无效,设置背景颜色无效果(第二种实现方式 背景颜色设置不起作用)...
  19. 笔记:PoseCNN:A Convolutional Neural Network for 6D Object Pose Estimation in Cluttered Scenes
  20. 基于Unity3D的Xml文件的存储的实现

热门文章

  1. 使用C++代码打造:史上最恶心的“推箱子”游戏,你敢再坑爹点吗?
  2. 蔡吴失效准则matlab编程,蔡吴张量准则.ppt
  3. ylinux系统找到软件_一分钟了解Linux软件安装
  4. Powershell管理系列(三)2012 AD域用户UPN名称还原
  5. 名言警句(每天三遍)
  6. 毕业设计- 基于Android的健身计划APP
  7. 计算机主机启动不了系统安装,台式机无法开机怎么重装win7系统
  8. 前端框架:jQuery
  9. Linux驱动——PCI
  10. UE4人工智能设计软件Promethean AI 详细安装步骤