在入门篇之后 进阶篇进行了拓展
使用了卷积神经网络 两个卷积层 两个pooling层 一个全连接层
其中注意 padding='SAME'对图片大小的影响
-
For the
SAME
padding, the output height and width are computed as:out_height = ceil(float(in_height) / float(strides[1]))
out_width = ceil(float(in_width) / float(strides[2]))
And
-
For the
VALID
padding, the output height and width are computed as:out_height = ceil(float(in_height - filter_height + 1) / float(strides1))
out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))
input_data.py
# __author__ = 'youngkl'
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gzip
import os
import tempfile
import numpy
from six.moves import urllib
from six.moves import xrange # pylint: disable=redefined-builtin
import tensorflow as tf
from tensorflow.contrib.learn.python.learn.datasets.mnist import read_data_sets
mnist_second.py
#-*- coding:utf-8 -*-
import input_data
import tensorflow as tf
mnist=input_data.read_data_sets("MNIST_data/",one_hot=True)
#one_hot编码 向量上只有一位是1其他都是0
x=tf.placeholder(tf.float32,[None,784])#占位符 输入任意数量的图片 每一张图片展开成784维向量
y_=tf.placeholder("float",[None,10])#占位符用于输入正确值
x_image=tf.reshape(x,[-1,28,28,1])
#把x变成一个4d向量 其第2,3维对应图片的宽、高 最后一维代表图片的颜色通道数(灰度图片通道数为1 如果是rgb彩色图,为3)
# print x_image
#权重初始化
def weight_variale(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):
return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')
#等于SAME 表示0边距 卷积核可以停留在图像边缘
def max_pool_2x2(x):
return tf.nn.max_pool(x,ksize=[1,2,2,1],
strides=[1,2,2,1],padding='SAME')
#第一层卷积层
w_conv1=weight_variale([5,5,1,32])
#前两个参数表示卷积的窗口大小,第三个参数:输入的通道数 第四个参数:输出的通道数(我们想使用的特征数)
b_conv1=bias_variable([32])
h_conv1=tf.nn.relu(conv2d(x_image,w_conv1)+b_conv1)
#卷积之后加上偏置 进行relu操作
h_pool1=max_pool_2x2(h_conv1)
#第二层卷积层
w_conv2=weight_variale([5,5,32,64])
#第一层的输出变成第二层的输入了 所以第三个参数为32
b_conv2=bias_variable([64])
h_conv2=tf.nn.relu(conv2d(h_pool1,w_conv2)+b_conv2)
h_pool2=max_pool_2x2(h_conv2)
#全连接层
#图片变成了28*28/2/2=7*7 上一层输出64个
w_fc1=weight_variale([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("float")
h_fc1_drop=tf.nn.dropout(h_fc1, keep_prob)#使用占位符 表示dropout的比率
#输出层
w_fc2=weight_variale([1024,10])
b_fc2=bias_variable([10])
y_conv=tf.nn.softmax(tf.matmul(h_fc1_drop, w_fc2)+b_fc2)
#训练和评估模型
cross_entropy=-tf.reduce_sum(y_*tf.log(y_conv))
#adam优化来做梯度下降
train_step=tf.train.AdadeltaOptimizer(1e-4).minimize(cross_entropy)
correct_prediction=tf.equal(tf.argmax(y_conv,1),tf.argmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(correct_prediction,"float"))
sess=tf.Session()
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch=mnist.train.next_batch(500)
if i%100 == 0:
train_accuracy=sess.run(accuracy,feed_dict={x:batch[0],y_:batch[1],keep_prob:1.0})
print "Step %d, training accuracy %g"%(i,train_accuracy)
sess.run(train_step,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})