tensorflow+mnist数据集(代码)

      终于自己完整实现了一个例子了。这个例子比较简单,但是用到了好多之前没接触的知识,感觉有必要记下来,方便自己以后学习,也能跟大家学习交流。用的是mnist数据集

(其中自己的文件夹路径得换成 '/' 这样的斜杠才行)


# coding: utf-8

# In[48]:


import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


# In[49]:


#MNIST数据集相关的常数。
INPUT_NODE = 784
OUTPUT_NODE = 10


# In[50]:


#配置神经网络的参数;
LAYER1_NODE = 500
BATCH_SIZE = 100
LEARNING_RATE_BASE = 0.8
LEARNING_RATE_DECAY = 0.99
REGULARIZATION_RATE = 0.0001
TRAINING_STEPS = 5000
MOVING_AVERAGE_DECAY = 0.99


# In[51]:


#定义一个辅助函数,给定神经网络的输入和所有参数,计算前向传播结果;Relu激活函数;
def inference(input_tensor, avg_class, weights1, biases1,
             weights2, biases2):
    #当没有提供滑动平均类时,直接使用参数当前的取值;
    if avg_class == None:
        layer1 = tf.nn.relu(tf.matmul(input_tensor, weights1) + biases1)
        return tf.matmul(layer1, weights2) + biases2
    
    else:
        layer1 = tf.nn.relu(
        tf.matmul(input_tensor, avg_class.average(weights1)) + 
        avg_class.average(biases1))
        return tf.matmul(layer1, avg_class.average(weights2)) + avg_class.average(biases2)


# In[52]:


def train(mnist):
    x = tf.placeholder(tf.float32, [None, INPUT_NODE], name='x-input') #第一层的输入;
    y_ = tf.placeholder(tf.float32, [None, OUTPUT_NODE], name='y-input') # 最后一层的输入;
    
    #生成隐藏层的参数;
    weights1 = tf.Variable(tf.truncated_normal([INPUT_NODE, LAYER1_NODE], stddev=0.1))
    biases1 = tf.Variable(tf.constant(0.1, shape=[LAYER1_NODE]))
    #生成输出层的参数;
    weights2 = tf.Variable(tf.truncated_normal([LAYER1_NODE, OUTPUT_NODE], stddev=0.1))
    biases2 = tf.Variable(tf.constant(0.1, shape=[OUTPUT_NODE]))
    
    #调用之前编写的函数inference;
    y = inference(x, None, weights1, biases1, weights2, biases2)
    
    global_step = tf.Variable(0, trainable=False)
    
    variable_averages = tf.train.ExponentialMovingAverage(
        MOVING_AVERAGE_DECAY, global_step)
    
    variables_averages_op = variable_averages.apply(tf.trainable_variables())
    
    average_y = inference(x, variable_averages, weights1, biases1, weights2, biases2)
    
    #使用交叉熵作为损失函数;
    cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=y, labels=tf.argmax(y_, 1))
    cross_entropy_mean = tf.reduce_mean(cross_entropy)
    
    #计算L2正则化损失函数;
    regularizer = tf.contrib.layers.l2_regularizer(REGULARIZATION_RATE)
    regularization = regularizer(weights1) + regularizer(weights2)
    loss = cross_entropy_mean + regularization   #总损失;
    #设置指数衰减的学习率;
    learning_rate = tf.train.exponential_decay(
         LEARNING_RATE_BASE,
         global_step,
         mnist.train.num_examples / BATCH_SIZE, 
         LEARNING_RATE_DECAY)
    #使用梯度下降来优化算法;
    train_step = tf.train.GradientDescentOptimizer(learning_rate).minimize(loss, global_step=global_step)
    with tf.control_dependencies([train_step, variables_averages_op]):
        train_op = tf.no_op(name='train')
        
    # 计算正确率
    correct_prediction = tf.equal(tf.argmax(average_y, 1), tf.argmax(y_, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    
    # 初始化会话,并开始训练过程。
    with tf.Session() as sess:
        tf.global_variables_initializer().run()
        validate_feed = {x: mnist.validation.images, y_: mnist.validation.labels}
        test_feed = {x: mnist.test.images, y_: mnist.test.labels} 
        
        # 循环的训练神经网络。
        for i in range(TRAINING_STEPS):
            if i % 1000 == 0:
                validate_acc = sess.run(accuracy, feed_dict=validate_feed)
                print("After %d training step(s), validation accuracy using average model is %g " % (i, validate_acc))
            
            xs,ys=mnist.train.next_batch(BATCH_SIZE)
            sess.run(train_op,feed_dict={x:xs,y_:ys})

        test_acc=sess.run(accuracy,feed_dict=test_feed)
        print(("After %d training step(s), test accuracy using average model is %g" %(TRAINING_STEPS, test_acc)))
   


# In[53]:


def main(argv=None):
    mnist = input_data.read_data_sets("Z:/jupyter_notebooks/tensorflow-tutorial-master/Deep_Learning_with_TensorFlow/datasets/MNIST_data", one_hot=True)
    train(mnist)

if __name__=='__main__':
    main()


# In[ ]:




 

猜你喜欢

转载自blog.csdn.net/weixin_41765699/article/details/82144240
0条评论
添加一条新回复
  
今日推荐