第一个CNN代码,暂时对于CNN的BP还不熟悉。但是通过这个代码对于tensorflow的运行机制有了初步的理解

 '''
softmax classifier for mnist created on 2019.9.28
author: vince
'''
import math
import logging
import numpy
import random
import matplotlib.pyplot as plt
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
from sklearn.metrics import accuracy_score def weight_bais_variable(shape):
init = tf.random.truncated_normal(shape = shape, stddev = 0.01);
return tf.Variable(init); def bais_variable(shape):
init = tf.constant(0.1, shape=shape);
return tf.Variable(init); def conv2d(x, w):
return tf.nn.conv2d(x, w, [1, 1, 1, 1], padding = "SAME"); def max_pool_2x2(x):
return tf.nn.max_pool2d(x, ksize = [1, 2, 2, 1], strides = [1, 2, 2, 1], padding = "SAME"); def cnn(x, rate):
with tf.name_scope('reshape'):
x_image = tf.reshape(x, [-1, 28, 28, 1]); #first layer, conv & pool
with tf.name_scope('conv1'):
w_conv1 = weight_bais_variable([5, 5, 1, 32]);
b_conv1 = bais_variable([32]);
h_conv1 = tf.nn.relu(conv2d(x_image, w_conv1) + b_conv1); #28 * 28 * 32
with tf.name_scope('pool1'):
h_pool1 = max_pool_2x2(h_conv1); #14 * 14 * 32 #second layer, conv & pool
with tf.name_scope('conv2'):
w_conv2 = weight_bais_variable([5, 5, 32, 64]);
b_conv2 = bais_variable([64]);
h_conv2 = tf.nn.relu(conv2d(h_pool1, w_conv2) + b_conv2); #14 * 14 * 64
with tf.name_scope('pool2'):
h_pool2 = max_pool_2x2(h_conv2); #7 * 7 * 64 #first full connect layer, feature graph -> feature vector
with tf.name_scope('fc1'):
w_fc1 = weight_bais_variable([7 * 7 * 64, 1024]);
b_fc1 = bais_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);
with tf.name_scope("dropout1"):
h_fc1_drop = tf.nn.dropout(h_fc1, rate); #second full connect layer,
with tf.name_scope('fc2'):
w_fc2 = weight_bais_variable([1024, 10]);
b_fc2 = bais_variable([10]);
#h_fc2 = tf.matmul(h_fc1_drop, w_fc2) + b_fc2;
h_fc2 = tf.matmul(h_fc1, w_fc2) + b_fc2;
return h_fc2; def main():
logging.basicConfig(level = logging.INFO,
format = '%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',
datefmt = '%a, %d %b %Y %H:%M:%S'); mnist = read_data_sets('../data/MNIST',one_hot=True) # MNIST_data指的是存放数据的文件夹路径,one_hot=True 为采用one_hot的编码方式编码标签 x = tf.placeholder(tf.float32, [None, 784]);
y_real = tf.placeholder(tf.float32, [None, 10]);
rate = tf.placeholder(tf.float32); y_pre = cnn(x, rate); sess = tf.InteractiveSession();
sess.run(tf.global_variables_initializer()); loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = y_pre, labels = y_real));
train_op = tf.train.GradientDescentOptimizer(0.5).minimize(loss); correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(y_real, 1));
prediction_op= tf.reduce_mean(tf.cast(correct_prediction, tf.float32));
for _ in range(300):
batch_xs, batch_ys = mnist.train.next_batch(128);
sess.run(train_op, feed_dict = {x : batch_xs, y_real : batch_ys, rate: 0.5});
if _ % 10 == 0:
accuracy = sess.run(prediction_op, feed_dict = {x : mnist.test.images, y_real : mnist.test.labels, rate: 0.0 });
logging.info("%s : %s" % (_, accuracy)); if __name__ == "__main__":
main();

使用tensorflow实现cnn进行mnist识别的更多相关文章

  1. 使用tensorflow的softmax进行mnist识别

    tensorflow真是方便,看来深度学习需要怎么使用框架.如何建模- ''' softmax classifier for mnist created on 2019.9.28 author: vi ...

  2. Tensorflow搭建CNN实现验证码识别

    完整代码:GitHub 我的简书:Awesome_Tang的简书 整个项目代码分为三部分: Generrate_Captcha: 生成验证码图片(训练集,验证集和测试集): 读取图片数据和标签(标签即 ...

  3. 机器学习: Tensor Flow with CNN 做表情识别

    我们利用 TensorFlow 构造 CNN 做表情识别,我们用的是FER-2013 这个数据库, 这个数据库一共有 35887 张人脸图像,这里只是做一个简单到仿真实验,为了计算方便,我们用其中到 ...

  4. Tensorflow实践:CNN实现MNIST手写识别模型

    前言 本文假设大家对CNN.softmax原理已经比较熟悉,着重点在于使用Tensorflow对CNN的简单实践上.所以不会对算法进行详细介绍,主要针对代码中所使用的一些函数定义与用法进行解释,并给出 ...

  5. 深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识

    深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识 在tf第一个例子的时候需要很多预备知识. tf基本知识 香农熵 交叉熵代价函数cross-entropy 卷积神经网络 s ...

  6. 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别

    深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...

  7. [Python]基于CNN的MNIST手写数字识别

    目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...

  8. TensorFlow 入门之手写识别CNN 三

    TensorFlow 入门之手写识别CNN 三 MNIST 卷积神经网络 Fly 多层卷积网络 多层卷积网络的基本理论 构建一个多层卷积网络 权值初始化 卷积和池化 第一层卷积 第二层卷积 密集层连接 ...

  9. TensorFlow 入门之手写识别(MNIST) softmax算法

    TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...

随机推荐

  1. iOS 开发富文本之TTTAttributedLabel 在某个特定位置的文字添加跳转,下划线,修改字体大小,颜色

    @property(nonatomic , strong) TTTAttributedLabel * ttLabel; @property(nonatomic , strong) NSRange li ...

  2. Hibernate入门之注解@Column详解

    前言 上一节我们讲解了Hibernate的主键生成策略,本节我们继续来讲讲Hibernate中针对列的映射即@Column注解,文中若有错误之处,还望指正. @Column注解详解 我们看到如上针对列 ...

  3. 使用nestjs集成grpc具体操作

    两个程序中, 提供grpc服务的称为服务端, 调用grpc服务的为客户端, 以下是grpc服务端和客户端的代码编写     1. 创建两个nestjs项目demo1(端口: 3000)和demo2(端 ...

  4. jsp内置对象(三)-----response对象

    response对象  response对象包含了响应客户端请求的有关信息,但在JSP中很少直接用到它.他是HttpServletResponse类的实例,response对象具有页面作用域,即访问一 ...

  5. Anroid关于fragment控件设置长按事件无法弹出Popupwindows控件问题解决记录

    一.问题描述     记录一下最近在安卓的gragment控件中设置长按事件遇见的一个坑!!!     在正常的activity中整个活动中设置长按事件我通常实例化根部局,例如LinearLayout ...

  6. 逐浪CMS全面升级为.NET Core 3.0性能大提升

    微软发布了.Net Core 3.0正式版,逐浪CMS也在第一时间做了全面升级,并做了一系列的优化和调整,性能大幅提升,并解决了一些历史遗留问题,添加了一些新的功能.如后台固有小程序功能做了升级,功能 ...

  7. zabbix基本概述

    #zabbix简介 zabbix是一个基于WEB界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案 #官网地址 #官方网站 http://www.zabbix.com #zabbix4.2 ...

  8. jQuery插件select2跨域设置xhrFields参数

    ajax跨越时默认不带cookie,如果需要带cookie调用,需要设置参数 xhrFields: { withCredentials: true },如: $.ajax({url : "h ...

  9. flask 对于用户登录保持状态 flask_login

    先加载flask_login ext.py  在app下的__init__.py 进行引用把,我就不写了 login_manager = LoginManager() # 如果没有登录则重定向到该蓝图 ...

  10. 利用Python爬取OPGG上英雄联盟英雄胜率及选取率信息

    一.分析网站内容 本次爬取网站为opgg,网址为:” http://www.op.gg/champion/statistics” 由网站界面可以看出,右侧有英雄的详细信息,以Garen为例,胜率为53 ...