详解mnist实例__tensorflow

详解mnist实例__tensorflow

导入数据

import tensorflow as tf 
import tensorflow.examples.tutorials.mnist.input_data as input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)     #下载并加载mnist数据
x = tf.placeholder(tf.float32, shape=[None, 784])                  #输入的数据占位符,输入图片数据为28x28x1=784
y_actual = tf.placeholder(tf.float32, shape=[None, 10])            #输入的标签占位符

定义常用函数

下面用到的tf.constant, tf.Variable, tf.truncated_normal 详解请见:Locutus博客 tf.nn.conv2d详解见左理想fisher博客

#定义一个函数,用于初始化所有的权值 W
def weight_variable(shape):
  #tf.truncated_normal(shape, mean, stddev) :shape表示生成张量的维度,mean是均值,stddev是标准差。
  #这个函数产生正太分布,均值和标准差自己设定。
    
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

#定义一个函数,用于初始化所有的偏置项 b
def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)    #tf.constant()常量
  return tf.Variable(initial)                #tf.Variable()变量, 用常量去初始化.
  
#定义一个函数,用于构建卷积层
def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')  

#padding='SAME' --> out_height=ceil(inputheight/stride[1]), out_width =ceil(inputweight/stride[2]) 
#padding='VALID'--> out_height = ceil(float(in_height - filter_height + 1) / float(strides[1]))
#                   out_width = ceil(float(in_width - filter_width + 1) / float(strides[2]))
                                                         
#stides首尾1固定,中间1,1为步长.

#定义一个函数,用于构建池化层
def max_pool(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],strides=[1, 2, 2, 1], padding='SAME') 

构建网络

#构建网络
x_image = tf.reshape(x, [-1,28,28,1])         #转换输入数据shape,以便于用于网络中.shape中-1表示自动计算此维度.
W_conv1 = weight_variable([5, 5, 1, 32])      
b_conv1 = bias_variable([32])

#线性整流函数(Rectified Linear Unit, ReLU),即 f(x)=max(x, 0)。是常用的激活函数(activation function)
#--> 即将矩阵中每行的 <0 的值置0。如:(-1.0, 2.0)-->(0.0, 2.0)
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)     #第一个卷积层, 输出:1x28x28x32
h_pool1 = max_pool(h_conv1)                                  #第一个池化层, 输出:1x14x14x32

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)      #第二个卷积层, 输出:1x14x14x64
h_pool2 = max_pool(h_conv2)                                   #第二个池化层, 输出:1x7x7x64

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])              #reshape成向量
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)    #第一个全连接层. tf.matmul矩阵相乘.

keep_prob = tf.placeholder("float") 
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)                  #dropout层

W_fc2 = weight_variable([1024, 10])
b_fc2 = bias_variable([10])
y_predict=tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)   #softmax层
#Softmax的含义:Softmax简单的说就是把一个N*1的向量归一化为(0,1)之间的值,由于其中采用指数运算,使得向量中数值较大的量特征更加明显。

对tf.nn.softmax的详解请见自律者自由博客

训练模型

cross_entropy = -tf.reduce_sum(y_actual*tf.log(y_predict))                        #交叉熵
#tf.reduce_sum(x):求所有和, tf.reduce_sum(x,0):按行求和, tf.reduce_sum(x,1):按列求和.

##创建train_step和accuracy 等op操作,用于在sess会话中进行运行
train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(cross_entropy)      #梯度下降法

correct_prediction = tf.equal(tf.argmax(y_predict,1), tf.argmax(y_actual,1)) 
#tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和A是一样的
#A = [[1,3,4,5,6]]
#B = [[1,3,4,3,2]]
#输出[[ True  True  True False False]]

#tf.argmax就是返回最大的那个数值所在的下标。
#test = np.array([[1, 2, 3], [2, 3, 4], [5, 4, 3], [8, 7, 2]]) 
#np.argmax(test, 0)   0:全局范围内比较.            #输出:array([3, 3, 1] 
#np.argmax(test, 1)   1:会比较每个数组内的数的大小   #输出:array([2, 2, 0, 0]


accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))                   #精确度计算
#tf.cast(x,dtype)将x的数据格式转化成dtype.
#tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。
#如果不指定则计算所有的平局值.


#sess=tf.InteractiveSession() 
#tf.InteractiveSession():它能让你在运行图的时候,插入一些计算图,这些计算图是由某些操作(operations)构成的。
#tf.Session():需要在启动session之前构建整个计算图,然后启动该计算图。

saver=tf.train.Saver(max_to_keep=1)

init_op=tf.global_variables_initializer()
#初始化所有变量

#Tensorflow依赖于一个高效的C++后端来进行计算。与后端的这个连接叫做session。
#一般而言,使用TensorFlow程序的流程是先创建一个图,然后在session中启动它。

with tf.Session() as sess:
    sess.run(init_op)
    for i in range(2000):
        batch = mnist.train.next_batch(50)
    
        if i%100 == 0:                  #每训练100个batch,验证一次.
            train_acc = accuracy.eval(feed_dict={x:batch[0], y_actual: batch[1], keep_prob: 1.0})
            #在tensorflow中,在一个With tf.Session() as sess底下执行一个op操作执行eval()函数等价于执行sess.run(op)操作
    
            print 'step %d, training accuracy %g'%(i,train_acc) 
            #占位符说明%, %d十进制整数, %g指数(e)或浮点数 (根据显示长度)
        
        sess.run(train_step,feed_dict={x: batch[0], y_actual: batch[1], keep_prob: 0.5})
    
    test_acc=accuracy.eval(feed_dict={x: mnist.test.images, y_actual: mnist.test.labels, keep_prob: 1.0})
    print "test accuracy %g"%test_acc
    
    #saver.save(sess,保存目录)
    saver.save(sess,os.path.join(os.path.dirname(os.path.dirname(__file__)),'data','minist.ckpt'))
    print("Saved")

模型的保存saver 与恢复restore详解见博客 os.path.dirname(file) 详解见博客

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值