tensorflow MNIST Convolutional Neural Network
2024-09-06 18:14:28
tensorflow MNIST Convolutional Neural Network
MNIST CNN 包含的几个部分:
- Weight Initialization
- Convolution and Pooling
- Convolution layer
- Fully connected layer
- Readout Layer
直接上tensorflow 给的示例:
先读入数据:
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
import tensorflow as tf
import time
#Weight Initialization
#现在还没有值,只是计算图中的节点,直到‘tf.global_variables_initializer()’才初始化
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)
#Convolution and Pooling
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')
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=None, name=None)
- 第一个参数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"其中之一,这个值决定了不同的卷积方式(后面会介绍)
- 第五个参数:use_cudnn_on_gpu:bool类型,是否使用cudnn加速,默认为true
结果返回一个Tensor,这个输出,就是我们常说的feature map
#Input (placeholder)
x = tf.placeholder(tf.float32,shape=[None,784])
y_ = tf.placeholder(tf.float32,shape=[None,10])
#Convolution layer
x_image = tf.reshape(x, [-1,28,28,1])
W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) #维度为[-1,28,28,32]
h_pool1 = max_pool_2x2(h_conv1)#维度为[-1,14,14,32]
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) #维度为[-1,14,14,64]
h_pool2 = max_pool_2x2(h_conv2) #维度为[-1,7,7,64]
tf.reshape(x, [-1,28,28,1])其中的-1表示由后面的几个维度来确定,
例如:
t=[[1, 2], [3, 4], [5, 6], [7, 8]] ,那么t的维度是[4,2]
(1) reshape(t,[2,4])后,t为[[1, 2, 3, 4], [5, 6, 7, 8]]
(2) reshape(t,[-1,4])后,t同样为[[1, 2, 3, 4], [5, 6, 7, 8]],所以这里的-1实际上为2。
#Fully connected 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])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)
#dropout
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
训练时使用dropout,减少过拟合
#Readout Layer
W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
#Training and Evaluation
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y_conv)) #Evaluation
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy) #optimizer
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) #accuracy
sess=tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
t1=time.time()
for i in range(4000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: 1.0})
print("step %d, training accuracy %g"%(i, train_accuracy))
train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.5})
print("test accuracy %g"%accuracy.eval(feed_dict={x: mnist.test.images, y_: mnist.test.labels,keep_prob: 1.0}))
t2=time.time()
print(t2-t1)
最新文章
- Sql Server系列:分区表操作
- angular开发者吐槽react+redux的复杂:“一个demo证明你的开发效率低下”
- 通过反射获得 spring 的 RequestMapping value值
- (六)文件操作的主要接口API
- unittest可能面临的问题以及解决方法
- OpenCV学习笔记——形态学梯度操作
- 用python产生一个好的秘钥
- JSTL-core核心代码标签库中的forEach,remove, forTokens,choose,when,otherwise,redirect 标签
- C++ 清空消息队列
- java--ThreadPool线程池简单用法
- js原生之设计模式开篇介绍
- 微信小程序开发之微信支付
- C# (using Newtonsoft.Json) Json 转换用法小总结
- 我的第一个chrome浏览器扩展 5分钟学习搞定
- Git那些事儿
- 如何像Python高手(Pythonista)一样编程
- IntelliJ IDEA生成live template(代码模板)
- 【学习总结】GirlsInAI ML-diary day-4:变量/Variable
- 【C++/类与对象总结】
- 【文文殿下】【洛谷】分治NTT模板
热门文章
- 02_css3.0 前端长度单位 px em rem vm vh vm pc pt in 你真的懂了吗?
- Arrays.asList() 导致的java.lang.UnsupportedOperationException异常
- Linux Cgroup浅析
- html 鼠标指针讲解
- TypeScript 源码详细解读(1)总览
- MapGIS注记文字无损转入ArcGIS软件
- LeetCode刷题预备知识(二)
- 官方文档中文版!Spring Cloud Stream 快速入门
- numpy 索引和切片
- Java框架之SpringMVC 04-视图解析-Spring表单-JSON-上传下载