zoukankan      html  css  js  c++  java
  • TensorFlow实战第五课(MNIST手写数据集识别)

    Tensorflow实现softmax regression识别手写数字

    MNIST手写数字识别可以形象的描述为机器学习领域中的hello world。

    MNIST是一个非常简单的机器视觉数据集。它由几万张28*28像素的手写数字组成,这些图片只包含灰度值信息。我们的任务就是对这些手写数字进行分类。转换为0-9共十个分类。

    首先在命令行中运行如下代码加载MNIST手写数据集:

    from tensorflow.examples.tutorials.mnist import  input_data
    #number 1 to 10 data
    #创建文件夹存放数据
    mnist = input_data.read_data_sets('MNIST_data',one_hot=True)

    数据集中包含55000个样本,测试集中有10000个样本,同时验证集有5000个样本。每一个样本都有他对应的标注信息,即label。

    我们将在训练集上训练模型,在验证集上检验效果并决定何时完成训练,最后我们在测评及评测模型效果。

    准备好数据后我们开始设计算法。我们采用的是softmax regression的算法训练手写数字识别的分类模型。数字分为0-9,所以一共有十个类别,当我们对一张图片进行预测时,softmax regression会对每一种类别估算一个概率,然后取估算概率最大的数字作为模型的输出结果。

    注:当我们处理多分类模型时,通常需要使用softmax regression。例如卷积神经网络或者循环神经网络,如果是分类模型,那么最后一层同样是softmax regression。

    loss函数选择的是交叉熵函数,交叉熵用来衡量预测值与真实值的相似程度,如果完全相同,他们的交叉熵等于零。

    cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
    reduction_indices=[1])) # loss

    train方法(最优化方法)采用梯度下降法。

    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
    sess = tf.Session()
    # tf.initialize_all_variables() 这种写法马上就要被废弃
    # 替换成下面的写法:
    sess.run(tf.global_variables_initializer())

    完整代码:

    #classification 分类学习
    
    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 add_layer(inputs,in_size,out_size,activation_function=None):
        #添加一个以上的层 并且返回这个层的输出
    
        Weights = tf.Variable(tf.random_normal([in_size,out_size]))
        biases = tf.Variable(tf.zeros([1,out_size])+0.1)
        Wx_plus_b = tf.matmul(inputs,Weights)+biases
    
        if activation_function is None:
            outputs = Wx_plus_b
        else:
            outputs = activation_function(Wx_plus_b)
        return outputs
    
    def compute_accuracy(v_xs,v_ys):
        global prediction
        y_pre = sess.run(prediction,feed_dict={xs:v_xs})
        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})
        return result
    
    
    #define placeholder for inputs to network
    xs = tf.placeholder(tf.float32,[None,784])#None就是不规定他有多少sample,但是规定大小为28*28
    ys = tf.placeholder(tf.float32,[None,10])
    
    #add output layer
    #激励函数采用softmax函数
    prediction = add_layer(xs,784,10,activation_function=tf.nn.softmax)
    
    # the error between prediction and real data
    '''loss函数即最优化目标函数 选用交叉熵函数
    交叉熵用来衡量预测值和真实值相似程度
    如果完全相同 ,他们的交叉熵为零
    '''
    cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),
                                           reduction_indices=[1]))       

    # loss #采用梯度下降法 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) sess = tf.Session() init = tf.global_variables_initializer() sess.run(init) for i in range(2000): #每次只取100张图片 batch_xs,batch_ys = mnist.train.next_batch(100) sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys}) if i%50==0: print(compute_accuracy(mnist.test.images,mnist.test.labels))

    输出结果:

  • 相关阅读:
    将一个正整数分解质因数
    C语言中字符数组和字符串、字符串常量(转载)
    输出那一天是星期几
    吸血鬼数字—THINKING IN JAVA中一道习题
    Oracle外连接,左外连接,右外连接,内连接简析
    函数基础篇 Zeus
    程序员从初级到中级10个秘诀
    帮你免于失业的十大软件技术
    入门级XML学习(二)
    入门级XML学习(一)
  • 原文地址:https://www.cnblogs.com/baobaotql/p/11281537.html
Copyright © 2011-2022 走看看