# -*- coding:utf-8 -*-
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
import os
import argparse
import sys DATA_DIR = os.path.join('.', 'mnist_link') # =======================================
# COMMON OPERATIONS
# =======================================
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def init_weight(shape):
init = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(init) def init_bias(shape):
init = tf.constant(0.1, shape=shape)
return tf.Variable(init) # =======================================
# BUILD CNN
# =======================================
def build_cnn(x):
'''
build the cnn model
'''
x_image = tf.reshape(x, [-1,28,28,1]) w1 = init_weight([5,5,1,32])
b1=init_bias([32])
conv1 = tf.nn.relu(conv2d(x_image, w1) + b1)
pool1 = max_pool_2x2(conv1) w2 = init_weight([5,5,32,64])
b2 = init_bias([64])
conv2 = tf.nn.relu(conv2d(pool1, w2) + b2)
pool2 = max_pool_2x2(conv2) # fc
w_fc1 = init_weight([7*7*64, 1024])
b_fc1 = init_bias([1024])
pool2_flat = tf.reshape(pool2, [-1, 7*7*64])
fc1 = tf.nn.relu(tf.matmul(pool2_flat, w_fc1) + b_fc1) # dropout
keep_prob = tf.placeholder(tf.float32)
fc1_dropout = tf.nn.dropout(fc1, keep_prob) # fc2
w_fc2 = init_weight([1024, 10])
b_fc2 = init_bias([10])
y_conv = tf.matmul(fc1_dropout, w_fc2) + b_fc2
return y_conv, keep_prob # =======================================
# train and test
# =======================================
def main():
'''
feed data into cnn model, and train and test the model
'''
# import data
print('import data...')
mnist = input_data.read_data_sets(DATA_DIR, one_hot=True) # create graph for cnn
x = tf.placeholder(tf.float32, [None, 784])
y_ = tf.placeholder(tf.float32, [None, 10])
y_conv, keep_prob = build_cnn(x) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels = y_, logits = y_conv))
optimizer = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_predictions = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_predictions, tf.float32))
init = tf.global_variables_initializer() print('start training...')
with tf.Session() as sess:
sess.run(init)
for i in range(2000):
batch = mnist.train.next_batch(128)
optimizer.run(feed_dict={x:batch[0], y_:batch[1], keep_prob:0.5})
if i%100 == 0:
train_acc = accuracy.eval(
feed_dict = {x:batch[0], y_:batch[1], keep_prob:1.0})
print('step {}, accuracy is {}'.format(i, train_acc)) test_acc = accuracy.eval(feed_dict={x:mnist.test.images, y_:mnist.test.labels, keep_prob:1.0})
print('test accuracy is {}'.format(test_acc)) if __name__ == '__main__':
print('run main')
main()

Tensorflow学习笔记3:卷积神经网络实现手写字符识别的更多相关文章

  1. tensorflow学习笔记七----------卷积神经网络

    卷积神经网络比神经网络稍微复杂一些,因为其多了一个卷积层(convolutional layer)和池化层(pooling layer). 使用mnist数据集,n个数据,每个数据的像素为28*28* ...

  2. TensorFlow卷积神经网络实现手写数字识别以及可视化

    边学习边笔记 https://www.cnblogs.com/felixwang2/p/9190602.html # https://www.cnblogs.com/felixwang2/p/9190 ...

  3. CNN学习笔记:卷积神经网络

    CNN学习笔记:卷积神经网络 卷积神经网络 基本结构 卷积神经网络是一种层次模型,其输入是原始数据,如RGB图像.音频等.卷积神经网络通过卷积(convolution)操作.汇合(pooling)操作 ...

  4. 【学习笔记】卷积神经网络 (CNN )

    前言 对于卷积神经网络(cnn)这一章不打算做数学方面深入了解,所以只是大致熟悉了一下原理和流程,了解了一些基本概念,所以只是做出了一些总结性的笔记. 感谢B站的视频 https://www.bili ...

  5. 学习笔记TF027:卷积神经网络

    卷积神经网络(Convolutional Neural Network,CNN),可以解决图像识别.时间序列信息问题.深度学习之前,借助SIFT.HoG等算法提取特征,集合SVM等机器学习算法识别图像 ...

  6. Tensorflow搭建卷积神经网络识别手写英语字母

    更新记录: 2018年2月5日 初始文章版本 近几天需要进行英语手写体识别,查阅了很多资料,但是大多数资料都是针对MNIST数据集的,并且主要识别手写数字.为了满足实际的英文手写识别需求,需要从训练集 ...

  7. 深度学习笔记 (一) 卷积神经网络基础 (Foundation of Convolutional Neural Networks)

    一.卷积 卷积神经网络(Convolutional Neural Networks)是一种在空间上共享参数的神经网络.使用数层卷积,而不是数层的矩阵相乘.在图像的处理过程中,每一张图片都可以看成一张“ ...

  8. Tensorflow学习教程------利用卷积神经网络对mnist数据集进行分类_利用训练好的模型进行分类

    #coding:utf-8 import tensorflow as tf from PIL import Image,ImageFilter from tensorflow.examples.tut ...

  9. 使用TensorFlow的卷积神经网络识别手写数字(3)-识别篇

    from PIL import Image import numpy as np import tensorflow as tf import time bShowAccuracy = True # ...

随机推荐

  1. [LightOJ1240]Point Segment Distance 题解

    题意简述 原题LightOJ 1240,Point Segment Distance(3D). 求三维空间里线段AB与C. 题解 我们设一个点在线段AB上移动,然后发现这个点与原来的C点的距离呈一个单 ...

  2. Leetcode 11. Container With Most Water(逼近法)

    11. Container With Most Water Medium Given n non-negative integers a1, a2, ..., an , where each repr ...

  3. es之得分(加权)

    随着应用程序的增长,提高搜索质量的需求也进一步增大.我们把它叫做搜索体验.我们需要知道什么对用户更重要,关注用户如何使用搜索功能.这导致不同的结论,例如,有些文档比其他的更重要,或特定查询需强调一个字 ...

  4. set集合 浅层拷贝会和深层拷贝

    一.什么是set集合 集合是无序的,不重复的数据集合,它里面的元素是可哈希的(不可变类型),但是集合本身是不可哈希(所以集合做不了字典的键)的.以下是集合最重要的两点: 1.去重,把一个列表变成集合, ...

  5. 阶段1 语言基础+高级_1-3-Java语言高级_1-常用API_1_第4节 ArrayList集合_19-ArrayList练习四_筛选集合

    大集合里面循环装了20个int类型的随即数字 下面要自定义方法,这个方法专门负责筛选 遍历偶数的集合 重点是集合当做方法的参数,还能当做集合的返回值

  6. vi, Java, Ant, Junit自学报告 - 实训week1

    vi, Java, Ant, Junit自学报告 2017软件工程实训 15331023 陈康怡 vi Vi是linux系统的标准文本编辑器,采用指令的方式进行操作,此处仅记录部分常用的指令. vi模 ...

  7. python实现建立udp通信

    实现代码如下: #udp协议通信import socket,timeclass UdpConnect: def get_udp(self,ip,port,message): #建立udp连接 myso ...

  8. 数组的includes方法

    Array.prototype.includes方法返回一个布尔值,表示某个数组是否包含给定的值,与字符串的includes方法类似.该方法属于 ES7 ,但 Babel 转码器已经支持. [1, 2 ...

  9. python基础-5 冒泡排序、递归

    上节总结 一.上节内容补充回顾 1.lambda func = lambda x,y: 9+x 参数: x,y 函数体:9+x ==> return 9+x func: 函数名 def func ...

  10. Linux系统中tomcat的安装及优化

    Linux系统中Tomcat 8 安装 Tomcat 8 安装 官网:http://tomcat.apache.org/ Tomcat 8 官网下载:http://tomcat.apache.org/ ...