1/先解释下CNN的过程:

首先对一张图片进行卷积,可以有多个卷积核,卷积过后,对每一卷积核对应一个chanel,也就是一张新的图片,图片尺寸可能会变小也可能会不变,然后对这个chanel进行一些pooling操作。

最后pooling输出完成,这个算作一个卷积层。

最后对最后一个pooling结果进行一个简单的MLP的判别其就好了

2.代码分步:

2.1 W and bias:注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到

 #注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到
def getWeights(shape):
return tf.Variable(tf.truncated_normal(shape,stddev= 0.1))
def getBias(shape):
return tf.Variable(tf.constant(0.1))

2.2 卷积层操作:

首先说下tf.nn.conv2d这个函数:

其中官方解释:

这里主要需要了解的是strides的含义:其shape表示的是[batch, in_height, in_width, in_channels]。需要注意的是,看我们在Weights初始化时的shape,我们自己定义的shape格式是[h,w,inchanel,outchanel]   --->chanel也就是我们理解的厚度。

 def conv2d(x,W):
return tf.nn.conv2d(x,W,strides = [1,1,1,1],padding="SAME")
#ksize
def maxpooling(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides = [1,2,2,1],padding= "SAME")

关于data_format

padding也有两种方式:

其他地方其实也没有什么新操作所有代码在下面:

 # -*- coding: utf-8 -*-
"""
Spyder Editor This is a temporary script file.
"""
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
import numpy as np
#注意不要将一些W设为0,一定要注意,这个会在后面一些地方讲到
def getWeights(shape):
return tf.Variable(tf.truncated_normal(shape,stddev= 0.1))
def getBias(shape):
return tf.Variable(tf.constant(0.1))
#构造卷积层 strides前一个跟最后后一个为1,其他表示方向,padding一般是有两种方式 ,一个是SAME还有一个是VALID
#前者卷积后不改变大小后一个卷积后一般会变小
#strides--->data_format:data_format: An optional string from: "NHWC", "NCHW". Defaults to "NHWC". Specify the data format of the input and output data. With the default format "NHWC", the data is stored in the order of: [batch, height, width, channels]. Alternatively, the format could be "NCHW", the data storage order of: [batch, channels, height, width].
#
def conv2d(x,W):
return tf.nn.conv2d(x,W,strides = [1,1,1,1],padding="SAME")
#ksize
def maxpooling(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],strides = [1,2,2,1],padding= "SAME")
def compute_acc(v_xs,v_ys):
global predict
y_pre = sess.run(predict,feed_dict = {xs:v_xs,keep_prob:1})
tmp = tf.equal(tf.arg_max(y_pre,1),tf.arg_max(v_ys,1))
accuracy = tf.reduce_mean(tf.cast(tmp,tf.float32))
return sess.run(accuracy,feed_dict = {xs:v_xs,ys:v_ys,keep_prob:1}) mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
xs = tf.placeholder(tf.float32,[None,28*28])
ys = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32) x_images = tf.reshape(xs,[-1,28,28,1]) W_c1 = getWeights([5,5,1,32])
b_c1 = getBias([32])
h_c1 = tf.nn.relu(conv2d(x_images,W_c1)+b_c1)
h_p1 = maxpooling(h_c1) W_c2 = getWeights([5,5,32,64])
b_c2 = getBias([64])
h_c2 = tf.nn.relu(conv2d(h_p1,W_c2)+b_c2)
h_p2 = maxpooling(h_c2) W_fc1 = getWeights([7*7*64,1024])
b_fc1 = getBias([1024])
h_flat = tf.reshape(h_p2,[-1,7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_flat,W_fc1)+b_fc1)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob) W_fc2 = getWeights([1024,10])
b_fc2 = getBias([10])
predict = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2) loss = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(predict),
reduction_indices=[1]))
train_step = tf.train.AdamOptimizer(0.001).minimize(loss) sess = tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(1000):
batch_xs, batch_ys = mnist.train.next_batch(100)
sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 0.5})
if i % 50 == 0:
print (compute_acc(mnist.test.images,mnist.test.labels))

需要注意的是nn.dropout()

TFboy养成记 CNN的更多相关文章

  1. TFBOY 养成记 一些比较好多文章。

    API解释中文版(简书文章,没事看看): http://www.jianshu.com/p/e3a79eac554f Tensorlfow op辨异:tf.add()与tf.nn.bias_add() ...

  2. TFboy养成记 MNIST Classification (主要是如何计算accuracy)

    参考:莫烦. 主要是运用的MLP.另外这里用到的是批训练: 这个代码很简单,跟上次的基本没有什么区别. 这里的lossfunction用到的是是交叉熵cross_entropy.可能网上很多形式跟这里 ...

  3. TFboy养成记 tf.cast,tf.argmax,tf.reduce_sum

    referrence: 莫烦视频 先介绍几个函数 1.tf.cast() 英文解释: 也就是说cast的直译,类似于映射,映射到一个你制定的类型. 2.tf.argmax 原型: 含义:返回最大值所在 ...

  4. TFboy养成记 tensorboard

    首先介绍几个用法: with tf.name_scope(name = "inputs"): 这个是用于区分区域的.如,train,inputs等. xs = tf.placeho ...

  5. TFboy养成记 多层感知器 MLP

    内容总结与莫烦的视频. 这里多层感知器代码写的是一个简单的三层神经网络,输入层,隐藏层,输出层.代码的目的是你和一个二次曲线.同时,为了保证数据的自然,添加了mean为0,steddv为0.05的噪声 ...

  6. TFboy养成记 tensor shape到底怎么说

    tensor.shape 对于一位向量,其形式为[x,] 对于矩阵,二维矩阵[x,y],三维矩阵[x,y,z] 对于标量,也就是0.3*x这种0.3,表示形式为() 如果说这个矩阵是三维的,你想获得其 ...

  7. TFboy养成记 简单小程序(Variable & placeholder)

    学习参考周莫烦的视频. Variable:主要是用于训练变量之类的.比如我们经常使用的网络权重,偏置. 值得注意的是Variable在声明是必须赋予初始值.在训练过程中该值很可能会进行不断的加减操作变 ...

  8. TFboy养成记

    转自:http://www.cnblogs.com/likethanlove/p/6547405.html 在tensorflow的使用中,经常会使用tf.reduce_mean,tf.reduce_ ...

  9. 2016级算法第六次上机-F.AlvinZH的学霸养成记VI

    1082 AlvinZH的学霸养成记VI 思路 难题,凸包. 分析问题,平面上给出两类点,问能否用一条直线将二者分离. 首先应该联想到这是一个凸包问题,分别计算两类点的凸包,如果存在符合题意的直线,那 ...

随机推荐

  1. 【node】使用nvm管理node版本

    写在前面 nvm(nodejs version manager)是nodejs的管理工具,如果你想快速更新node版本,并且不覆盖之前的版本:或者想要在不同的node版本之间进行切换: 使用nvm来安 ...

  2. WPF 圖表控件 MetroChart

    Torsten Mandelkow MetroChart包括以下: ColumnChart(ClusteredColumnChart,StackedColumnChart,StackedColumnC ...

  3. win10 uwp 模拟网页输入

    有时候需要获得网页的 js 执行后的源代码,或者模拟网页输入,如点按钮输入文字. 如果需要实现,那么就需要用 WebView ,使用方法很简单. 首先创建一个 WebView ,接下来的所有输入都需要 ...

  4. win10 uwp 打开文件管理器选择文件

    本文:让文件管理器选择文件,不是从文件管理器获得文件. 假如已经获得一些文件,那么如何从文件管理器选择这些文件? 使用方法很简单. 从网上拿图来说 打开文件夹自动选择所有文件 首先需要获得文件夹,因为 ...

  5. git无法pull仓库refusing to merge unrelated histories

    本文讲的是把git在最新2.9.2,合并pull两个不同的项目,出现的问题如何去解决fatal: refusing to merge unrelated histories 我在Github新建一个仓 ...

  6. 【计算机网络】 一个小白的DNS学习笔记

    参考书籍 <计算机网络-自顶向下>  作者 James F. Kurose   DNS的作用   DNS是因特网的目录服务 DNS是因特网的目录服务,它提供了主机名到IP地址映射的查询服务 ...

  7. LINUX 笔记-tee命令

    作用:把输出的一个副本输送到标准输出,另一个副本拷贝到相应的文件中 格式:tee filename 例:who | tee who.out 使用who命令,结果输出到屏幕上,同时保存在who.out文 ...

  8. VNC 远程连接vmware下centOS7

    VNC ( Virtual Network Computing)是一个linux下提供远程桌面支持的服务,类似于windows下的远程桌面服务,本来我是准备用xmanager来远程连我虚拟机中的cen ...

  9. WebService WSDL结构分析

    转载地址:http://blog.csdn.net/sunchaohuang/article/details/3076375      WSDL (Web Services Description L ...

  10. this 和 new 构造函数

    function people(name) {     这样定义是在全局命名空间(global namespace)    name: name,    sayname: function() {   ...