使用tensorflow实现cnn进行mnist识别
第一个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识别的更多相关文章
- 使用tensorflow的softmax进行mnist识别
tensorflow真是方便,看来深度学习需要怎么使用框架.如何建模- ''' softmax classifier for mnist created on 2019.9.28 author: vi ...
- Tensorflow搭建CNN实现验证码识别
完整代码:GitHub 我的简书:Awesome_Tang的简书 整个项目代码分为三部分: Generrate_Captcha: 生成验证码图片(训练集,验证集和测试集): 读取图片数据和标签(标签即 ...
- 机器学习: Tensor Flow with CNN 做表情识别
我们利用 TensorFlow 构造 CNN 做表情识别,我们用的是FER-2013 这个数据库, 这个数据库一共有 35887 张人脸图像,这里只是做一个简单到仿真实验,为了计算方便,我们用其中到 ...
- Tensorflow实践:CNN实现MNIST手写识别模型
前言 本文假设大家对CNN.softmax原理已经比较熟悉,着重点在于使用Tensorflow对CNN的简单实践上.所以不会对算法进行详细介绍,主要针对代码中所使用的一些函数定义与用法进行解释,并给出 ...
- 深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识
深度学习-tensorflow学习笔记(1)-MNIST手写字体识别预备知识 在tf第一个例子的时候需要很多预备知识. tf基本知识 香农熵 交叉熵代价函数cross-entropy 卷积神经网络 s ...
- 深度学习-tensorflow学习笔记(2)-MNIST手写字体识别
深度学习-tensorflow学习笔记(2)-MNIST手写字体识别超级详细版 这是tf入门的第一个例子.minst应该是内置的数据集. 前置知识在学习笔记(1)里面讲过了 这里直接上代码 # -*- ...
- [Python]基于CNN的MNIST手写数字识别
目录 一.背景介绍 1.1 卷积神经网络 1.2 深度学习框架 1.3 MNIST 数据集 二.方法和原理 2.1 部署网络模型 (1)权重初始化 (2)卷积和池化 (3)搭建卷积层1 (4)搭建卷积 ...
- TensorFlow 入门之手写识别CNN 三
TensorFlow 入门之手写识别CNN 三 MNIST 卷积神经网络 Fly 多层卷积网络 多层卷积网络的基本理论 构建一个多层卷积网络 权值初始化 卷积和池化 第一层卷积 第二层卷积 密集层连接 ...
- TensorFlow 入门之手写识别(MNIST) softmax算法
TensorFlow 入门之手写识别(MNIST) softmax算法 MNIST flyu6 softmax回归 softmax回归算法 TensorFlow实现softmax softmax回归算 ...
随机推荐
- 设计模式-11享元模式(Flyweight Pattern)
1.模式动机 在面向对象程序设计过程中,有时会面临要创建大量相同或相似对象实例的问题.创建那么多的对象将会耗费很多的系统资源,它是系统性能提高的一个瓶颈. 享元模式就是把相同或相似对象的公共部分提取出 ...
- JMeter-WebService接口的测试
前言 JMeter3.2版本之后就没有SOAP/XML-RPC Request插件了,那么该如何进行webservice接口的测试呢? 今天我们来一起学习一下怎么在3.2以后版本的JMeter进行we ...
- 设计模式-12组合模式(Composite Pattern)
1.模式动机 很多时候会存在"部分-整体"的关系,例如:大学中的部门与学院.总公司中的部门与分公司.学习用品中的书与书包.在软件开发中也是这样,例如,文件系统中的文件与文件夹.窗体 ...
- JZOJ 1301. treecut
1301. treecut (Standard IO) Time Limits: 1000 ms Memory Limits: 131072 KB Description 有一个N个节点的无根树,各节 ...
- Spring Boot 2.x基础教程:使用MyBatis的XML配置方式
上一篇我们介绍了如何在Spring Boot中整合我们国人最常用的MyBatis来实现对关系型数据库的访问.但是上一篇中使用了注解方式来实现,而对于很多MyBatis老用户还是习惯于XML的开发方式, ...
- vue 点击跳转路由设置
刚接触 知道有两种方法,一种是用路由,一种是原生js的 <a @click="handleClick"></a> methods:function(){ h ...
- JS中的reduce()详解
reduce()作为一个循环使用.接收四个参数:初始值(上一次返回值),当前元素值,当前元素下标,原数组. 应用 作为累加器使用 var a=[4,5,6,7,8] //item代表一次回调的值 初 ...
- web自动化的三大等待
由于web网页打开后需要时间进行数据的传送,页面的渲染,所以我们在写web自动化脚本的时候,需要等待它加载完所有的页面元素,我们才进行操作或点击.同时这种等待也是为了提高脚本的稳定性. seleniu ...
- C++ 指针实现字符串倒序排列
#define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include <coni ...
- 原生JavaScript下的Ajax
概述 AJAX即asynchronous javascript and XML,中文翻译是异步的javascript和XML.是指一种创建交互式网页应用.用于创建快速动态网页的开发技术. 传统的网页( ...