TensorFlow之手写体识别

来源

from __future__ import print_function
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# number 1 to 10 data
mnist = input_data.read_data_sets('C:/Users/hubinghua/Desktop/MNIST_data/', one_hot=True)#数据加载

def add_layer(inputs, in_size, out_size, activation_function=None,):
    # add one more layer and return the output of this layer
    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#把prediction设为全局变量
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})#y的预测值
    correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))
    #tf.argmax是输出该向量中最大数对应的下标
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    #将correct_prediction转化为浮点数,求平均数就是其正确率
    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]) # 28x28
ys = tf.placeholder(tf.float32, [None, 10])

# add output layer
prediction = add_layer(xs, 784, 10,  activation_function=tf.nn.softmax)

# the error between prediction and real data
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()
# important step
# tf.initialize_all_variables() no long valid from
# 2017-03-02 if using tensorflow >= 0.12
if int((tf.__version__).split('.')[1]) < 12 and int((tf.__version__).split('.')[0]) < 1:
    init = tf.initialize_all_variables()
else:
    init = tf.global_variables_initializer()
sess.run(init)

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    #批量梯度下降,每迭代一步随机抽取100个数据去训练,一共迭代一千次,每一次都用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))
        #没迭代50次输出训练的精确度,这里测试精确度所用到的数据是包了的测试集

相关解释:

一、

for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100) 这里每迭代一步都从训练集里抽取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)) 每迭代50次输出训练的精确度,这里输出的精确度所用到的数据是包里的测试集

二、

def compute_accuracy(v_xs, v_ys)                                                                 这个函数用来计算准确度,把测试集里的数传过来
    global prediction                                                                                           把prediction设为全局变量
    y_pre = sess.run(prediction, feed_dict={xs: v_xs})                                      调用prediction函数对测试集结果预测

   correct_prediction = tf.equal(tf.argmax(y_pre,1), tf.argmax(v_ys,1))           tf.argmax是输出该向量中最大数对应的下标,其结                                                                                                                            果就是把预测出来的向量转换为预测出来的数字而                                                                                                                             ti.equal是对括号里面的数对比,相等输出ture,不                                                                                                                           相等输出fault,这样correct_prediction就变成了一个                                                                                                                           含有fault和ture的向量
   

accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

                                                                                                                         #将correct_prediction转化为浮点数(1和0的形式),                                                                                                                            求平均数就是其正确率
    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys})
    return result

三、

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

交叉熵函数:相关解释

四、

softmax回归

猜你喜欢

转载自blog.csdn.net/weixin_40849273/article/details/81221203