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 compute_accuracy(v_xs,v_ys):
global prediction
y_pre = sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1})
correct_prediction = tf.equal(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
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')

#define placeholder for inputs to network
xs = tf.placeholder(tf.float32,[None,784])#28x28
ys = tf.placeholder(tf.float32,[None,10])
keep_prob = tf.placeholder(tf.float32)
x_image = tf.reshape(xs,[-1,28,28,1])
# print(x_image.shape)#[n_samples,28,28,1]

##conv1 layer##
W_conv1 = weight_variable([5,5,1,32])#pathc 5x5,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 28x28x32
h_pool1 = max_pool_2x2(h_conv1) #output size 14x14x32

##conv2 layer##
W_conv2 = weight_variable([5,5,32,64])#pathc 5x5,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 14x14x64
h_pool2 = max_pool_2x2(h_conv2) #output size 7x7x64

##func1 layer##
W_fc1 = weight_variable([7*7*64,1024])
b_fc1 = bias_variable([1024])
#[n_sample,7,7,64]->>[n_sample,7*7*64]
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)
h_fc1_drop = tf.nn.dropout(h_fc1,keep_prob)
##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
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(1000):
batch_xs,batch_ys = mnist.train.next_batch(100)
sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys,keep_prob:1})
if i%50 ==0:
print(compute_accuracy(mnist.test.images,mnist.test.labels))

莫烦tensorflow(8)-CNN的更多相关文章

  1. 莫烦tensorflow(9)-Save&Restore

    import tensorflow as tfimport numpy as np ##save to file#rember to define the same dtype and shape w ...

  2. 莫烦tensorflow(7)-mnist

    import tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_data#number 1 to 10 dat ...

  3. 莫烦tensorflow(6)-tensorboard

    import tensorflow as tfimport numpy as np def add_layer(inputs,in_size,out_size,n_layer,activation_f ...

  4. 莫烦tensorflow(5)-训练二次函数模型并用matplotlib可视化

    import tensorflow as tfimport numpy as npimport matplotlib.pyplot as plt def add_layer(inputs,in_siz ...

  5. 莫烦tensorflow(4)-placeholder

    import tensorflow as tf input1 = tf.placeholder(tf.float32)input2 = tf.placeholder(tf.float32) outpu ...

  6. 莫烦tensorflow(3)-Variable

    import tensorflow as tf state = tf.Variable(0,name='counter') one = tf.constant(1) new_value = tf.ad ...

  7. 莫烦tensorflow(2)-Session

    import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import tensorflow as tfmatrix1 = tf.constant([[3,3] ...

  8. 莫烦tensorflow(1)-训练线性函数模型

    import tensorflow as tfimport numpy as np #create datax_data = np.random.rand(100).astype(np.float32 ...

  9. tensorflow学习笔记-bili莫烦

    bilibili莫烦tensorflow视频教程学习笔记 1.初次使用Tensorflow实现一元线性回归 # 屏蔽警告 import os os.environ[' import numpy as ...

随机推荐

  1. springboot使用hibernate validator校验

    一.参数校验 在开发中经常需要写一些字段校验的代码,比如字段非空,字段长度限制,邮箱格式验证等等,写这些与业务逻辑关系不大的代码个人感觉有两个麻烦: 验证代码繁琐,重复劳动 方法内代码显得冗长 每次要 ...

  2. PhpStorm 2017破解

    最新版PhpStorm 2017正式版改进了PHP 7支持,改进代码完成功能. PhpStorm 是最好的PHP开发工具,使用它进行PHP开发将会让你感觉到编程的乐趣. 快乐无极终于从oschina看 ...

  3. Docker run命令参数整理

    Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] -d, --detach=false 指定容器运行于前台还是后台,默认为false -i, - ...

  4. [c/c++] programming之路(14)、数组+冒泡和选择排序

    一.数组的基本知识 #include<stdio.h> #include<stdlib.h> void main0(){ ]={,,,,};//数组在内存里是连续排列的 int ...

  5. 第十届蓝桥杯2019年C/C++ 大学B组省赛试题

    2019年第十届蓝桥杯大赛软件类省赛C/C++大学B组 试题 A:组队 本题总分:5分 [问题描述] 作为篮球队教练,你需要从以下名单中选出 1号位至 5号位各一名球员, 组成球队的首发阵容. 每位球 ...

  6. 进程池 和 multiprocessing.Pool模块

    进程池的概念 在程序实际处理问题过程中,忙时会有成千上万的任务需要被执行,闲时可能只有零星任务.那么在成千上万个任务需要被执行的时候,我们就需要去创建成千上万个进程么?首先,创建进程需要消耗时间,销毁 ...

  7. 代码覆盖率-JaCoCo

    代码覆盖率 在做单元测试时,代码覆盖率常常被拿来作为衡量测试好坏的指标,甚至,用代码覆盖率来考核测试任务完成情况,比如,代码覆盖率必须达到80%或 90%. JaCoCo Jacoco从多种角度对代码 ...

  8. HTTP请求处理流程 MVC核心(MVC就是扩展了一个HttpModule)

    访问Localhost:8080/Home/index.aspx 在调用MVC扩展的UrlRoutingModule的时候  会先检查物理路径文件是否存在  存在的话就不执行MVC中的路由匹配规则  ...

  9. (转)浏览器对象window,history,location,navigator,screen

    1.window对象:当前的浏览器窗口 window对象是BOM的核心,window对象指当前的浏览器窗口 所有JavaScript全局对象.函数以及变量均自动成为window对象的成员 全局变量是w ...

  10. HDFS常用操作命令

    启动hdfs#start-all.sh查看hdfs的配置文件#cat hdfs-site.sh#hadoop fs -put /soft/jdk /#HDFS上传文件命令查看上传后的文件属性#hado ...