tensorflow学习之(十)使用卷积神经网络(CNN)分类手写数字0-9
#卷积神经网络cnn
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#数据包,如果没有自动下载 number 1 to 10 data
mnist = input_data.read_data_sets('MNIST_data',one_hot=True) #用测试集来评估神经网络的准确度
def computer_accuracy(v_xs,v_ys):
global prediction
y_pre = sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1})#只要有dropout在feed_dict中必须加上keep_prob
correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))#tf.argmax(y_pre,1)表示预测出的值,tf.argmax(v_ys,1)表示实际值
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
result = sess.run(accuracy,feed_dict={xs: v_xs, ys: v_ys,keep_prob:1})
return result def weight_variable(shape):
initial = tf.truncated_normal(shape,stddev=0.1)
return tf.Variable(initial) def bias_variable(shape):
initial = tf.constant(0.1,shape=shape)
return tf.Variable(initial) def conv2d(x,W):
#stride[1,x_movement,y_movement,1]
#must have strides[0]=strides[3]=1
'''
:param x:需要输入的图像或句子,形式为[batch, in_height, in_width, in_channels]
:param W: CNN中卷积核的大小,形式为[filter_height, filter_width, in_channels, out_channels]
:return: 返回一个feature map,形式为[batch, height, width, channels]
'''
'''
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
除去name参数用以指定该操作的name,与方法有关的一共五个参数:
第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]
这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一
第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]
这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,有一个地方需要注意,第三维in_channels,就是参数input的第四维
第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4
第四个参数padding:string类型的量,只能是"SAME","VALID"其中之一,这个值决定了不同的卷积方式,'SAME'指通过填充使得输出的图片的尺寸等于输入图片的尺寸
第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
结果返回一个Tensor,这个输出,就是我们常说的feature map,shape仍然是[batch, height, width, channels]这种形式。
那么TensorFlow的卷积具体是怎样实现的呢,用一些例子去解释它:
1.考虑一种最简单的情况,现在有一张3×3单通道的图像(对应的shape:[1,3,3,1]),用一个1×1的卷积核(对应的shape:[1,1,1,1])去做卷积,最后会得到一张3×3的feature map
2.增加图片的通道数,使用一张3×3五通道的图像(对应的shape:[3,3,5, 1]),用一个1×1的卷积核(对应的shape:[1,1,1,1])去做卷积,仍然是一张3×3的feature map,这就相当于每一个像素点,卷积核都与该像素点的每一个通道做卷积。
'''
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')#padding='SAME'指通过填充使得输出的图片的尺寸等于输入图片的尺寸 def max_pool_2x2(x):
# stride[1,x_movement,y_movement,1]
'''
:param x:需要进行池化的特征图,形式为:[batch, height, width, channels]
:return:返回池化结果,形式为:[batch, height, width, channels]
'''
'''
tf.nn.max_pool(value, ksize, strides, padding, name=None)
参数是四个,和卷积很类似:
第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape
第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'
返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式
'''
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME') #define placeholder for inputs to network
xs = tf.placeholder(tf.float32, [None, 784]) # none表示无论给多少个例子都行,784=28*28
ys = tf.placeholder(tf.float32, [None, 10]) #表示10个需要识别的数字
keep_prob = tf.placeholder(tf.float32)#dropout机制使用
x_image = tf.reshape(xs,[-1,28,28,1])#-1为多少由导入的数据决定,不是指batch_size。28*28*1指一个图片的像素点数
#print(x_image.shape) #[n_samples,28,28,1] ##conv1 layer##
W_conv1 = weight_variable([5,5,1,32])#patch=5*5,in size =1,out size=32
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image,W_conv1)+b_conv1)#output size = 28*28*32
h_pool1 = max_pool_2x2(h_conv1) #output size = 14*14*32 ##conv2 layer##
W_conv2 = weight_variable([5,5,32,64])#patch=5*5,in size =32,out size=64
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)#output size = 14*14*64
h_pool2 = max_pool_2x2(h_conv2) #output size = 7*7*64 ##func1 layer##应该是全连接层的参数
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2,[-1,7*7*64])#[n_sample,7,7,64]>>[n_sample,7*7*64]
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) #tf.reshape(tensor, shape, name=None) 数据重定形状函数
# 参数:
# tensor:输入数据
# shape:目标形状
# name:名称
# 返回:Tensor ##func2 layer##
W_fc2 = weight_variable([1024,10])
b_fc2 = bias_variable([10])
prediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) #the error between prediction and real data
cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1])) #loss function
#tf.summary.scalar('loss',cross_entropy)
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) sess = tf.Session()
#important step
sess.run(tf.global_variables_initializer()) for i in range(500):
batch_xs, batch_ys = mnist.train.next_batch(500)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys,keep_prob:1})
if i%50 == 0:
print(computer_accuracy(mnist.test.images[0:500], mnist.test.labels[0:500]))
tensorflow学习之(十)使用卷积神经网络(CNN)分类手写数字0-9的更多相关文章
- 【TensorFlow-windows】(四) CNN(卷积神经网络)进行手写数字识别(mnist)
主要内容: 1.基于CNN的mnist手写数字识别(详细代码注释) 2.该实现中的函数总结 平台: 1.windows 10 64位 2.Anaconda3-4.2.0-Windows-x86_64. ...
- 如何用卷积神经网络CNN识别手写数字集?
前几天用CNN识别手写数字集,后来看到kaggle上有一个比赛是识别手写数字集的,已经进行了一年多了,目前有1179个有效提交,最高的是100%,我做了一下,用keras做的,一开始用最简单的MLP, ...
- keras—神经网络CNN—MNIST手写数字识别
from keras.datasets import mnist from keras.utils import np_utils from plot_image_1 import plot_imag ...
- 第三节,TensorFlow 使用CNN实现手写数字识别(卷积函数tf.nn.convd介绍)
上一节,我们已经讲解了使用全连接网络实现手写数字识别,其正确率大概能达到98%,这一节我们使用卷积神经网络来实现手写数字识别, 其准确率可以超过99%,程序主要包括以下几块内容 [1]: 导入数据,即 ...
- 使用神经网络来识别手写数字【译】(三)- 用Python代码实现
实现我们分类数字的网络 好,让我们使用随机梯度下降和 MNIST训练数据来写一个程序来学习怎样识别手写数字. 我们用Python (2.7) 来实现.只有 74 行代码!我们需要的第一个东西是 MNI ...
- TensorFlow 2.0 深度学习实战 —— 浅谈卷积神经网络 CNN
前言 上一章为大家介绍过深度学习的基础和多层感知机 MLP 的应用,本章开始将深入讲解卷积神经网络的实用场景.卷积神经网络 CNN(Convolutional Neural Networks,Conv ...
- Android+TensorFlow+CNN+MNIST 手写数字识别实现
Android+TensorFlow+CNN+MNIST 手写数字识别实现 SkySeraph 2018 Email:skyseraph00#163.com 更多精彩请直接访问SkySeraph个人站 ...
- tensorflow学习之(九)classification 分类问题之分类手写数字0-9
#classification 分类问题 #例子 分类手写数字0-9 import tensorflow as tf from tensorflow.examples.tutorials.mnist ...
- python手写神经网络实现识别手写数字
写在开头:这个实验和matlab手写神经网络实现识别手写数字一样. 实验说明 一直想自己写一个神经网络来实现手写数字的识别,而不是套用别人的框架.恰巧前几天,有幸从同学那拿到5000张已经贴好标签的手 ...
- matlab手写神经网络实现识别手写数字
实验说明 一直想自己写一个神经网络来实现手写数字的识别,而不是套用别人的框架.恰巧前几天,有幸从同学那拿到5000张已经贴好标签的手写数字图片,于是我就尝试用matlab写一个网络. 实验数据:500 ...
随机推荐
- laravel框架memcached的使用
在laravel配置及使用使用 Memcached 缓存要求安装了Memcached PECL 包,即 PHP Memcached 扩展.你可以在配置文件 config/cache.php 中列出所有 ...
- 【18/12/31】hashcat源码粗读 --- sha256部分
还没有详细研究过sha256算法的详细原理,主要是移植cf10算法时,hashcat在cf10_parse_hash时并不是直接调用sha256_update和sha256_final, 而是为了pr ...
- java中的数据导出到Excel表中
整个项目中导出数据到.Excel的源码 import java.io.BufferedOutputStream; import java.io.FileInputStream; import java ...
- 史上最全最详细的环境搭建教程,行百里者手把手教你在windows下搭建Anaconda+pycharm+库文件(TensorFlow,numpy)环境搭建
我是在搭建TensorFlow开发环境的道路上走了很多弯路 掉了很多头发,为了让广大同学们不在受苦受累 下面我将手把手教你学习如特快速搭建python环境 快速导入numpy,PIL,pillow,等 ...
- hbase-hive整合及sqoop的安装配置使用
从hbase中拿数据,然后整合到hbase中 上hive官网 -- 点击wiki--> hive hbase integation(整合) --> 注意整合的时候两个软件的版本要能进行整 ...
- 利用Access-Control-Allow-Origin响应头解决跨域请求原理
传统的跨域请求没有好的解决方案,无非就是jsonp和iframe,随着跨域请求的应用越来越多,W3C提供了跨域请求的标准方案(Cross-Origin Resource Sharing).IE8.Fi ...
- PhoenixFD插件流体模拟——UI布局【Rendering】详解
Liquid Rendering 流体渲染 本文主要讲解Rendering折叠栏中的内容.原文地址:https://docs.chaosgroup.com/display/PHX3MAX/Liqui ...
- Debian 8 安装Nginx最新版本
在Debian下如果直接apt-get install nginx直接装发现nginx版本是很旧的,本文主要讲一下如何在Debian 8上装新版的nginx. 原文资料:https://nginx.o ...
- 牛客小白月赛13 小A的最短路(lca+RMQ)
链接:https://ac.nowcoder.com/acm/contest/549/F来源:牛客网 题目描述 小A这次来到一个景区去旅游,景区里面有N个景点,景点之间有N-1条路径.小A从当前的一个 ...
- 内置函数-fliter
def is_odd(x): return x % 2 == 1 ret = filter(is_odd, [1,4,6,7,9]) print(ret) for i in ret: print(i) ...