第一个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. Ubuntu18.04下安装mysql5.7超详细步骤

    1.首先执行下面三条命令: #安装mysql服务 sudo apt-get install mysql-server #安装客户端 sudo apt install mysql-client #安装依 ...

  2. H5多列布局

    多列布局 基本概念 1.多列布局类似报纸或杂志中的排版方式,上要用以控制大篇幅文本. 2.跨列属性可以控制横跨列的数量 /*列数*/ -webkit-column-count: 3; /*分割线*/ ...

  3. Nginx + uWSGI部署中的一些小坑

    1.invalid host in upstream报错 重新启动nginx : sudo /etc/init.d/nginx restart 原因是在配置负载均衡nginx.conf配置文件时,发现 ...

  4. MacOS麦克风输入监听的方法

    Windows上很多人都知道,然而实际上并没什么用——延迟太大,根本没法用. MacOS上有两种方法: QuickTime Player新建音频录制(不需要真的录音),如下图: 这个方法和Window ...

  5. 什么是phpMyAdmin

    phpMyAdmin 是一个以PHP为基础,以Web-Base方式架构在网站主机上的MySQL的数据库管理工具,让管理者可用Web接口管理MySQL数据库.借由此Web接口可以成为一个简易方式输入繁杂 ...

  6. HTC推出了VIVE Comos 全新 VR(虚拟现实)系列产品

    据 The Verge 报道,近日,HTC 推出了 VIVE Comos 全新 VR(虚拟现实)系列产品.包括 Cosmos 精英套装.VIVE Cosmos XR 版.Cosmos Play 基础版 ...

  7. C++ 动态创建链表

    #define _CRT_SECURE_NO_WARNINGS #include <iostream> struct Node { int data; Node* next; }; Nod ...

  8. python 2 和3 的区别

    python 2 和3 的区别 Python2 Python3 打印 print " " print() 输入 raw_input() input() 范围 range/xrang ...

  9. IPFS(星际文件系统)-初步接触

    〇.IPFS介绍 从HTTP到IPFS,星际文件系统能变革信息传播的方式吗? 戴嘉乐:详解IPFS的本质.技术架构以及应用 以下为实现相关摘要 1.存储 在IPFS中,信息可以存储进IPFS系统中的块 ...

  10. Android位置服务开发

    1. 使用LocationManager获取地理位置信息 代码如下: private TextView positiontext; private String provider; private L ...