tensorflow学习之(九)classification 分类问题之分类手写数字0-9

#classification 分类问题
#例子 分类手写数字0-9
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#数据包,如果没有自动下载 number 0 to 9 data
mnist = input_data.read_data_sets('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 the 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 computer_accuracy(v_xs,v_ys):
    global prediction
    y_pre = sess.run(prediction,feed_dict={xs:v_xs})
    #tf.argmax()返回最大数值的下标
    #tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和A是一样的
    '''
    tf.argmax(input, axis=None, name=None, dimension=None)
    此函数是对矩阵按行或列计算最大值    
    参数
    input:输入Tensor
    axis:0表示按列,1表示按行
    name:名称
    dimension:和axis功能一样,默认axis取值优先。新加的字段
    返回:Tensor  一般是行或列的最大值下标向量
    '''
    '''
    A = [[1,3,4,5,6]]
    B = [[1,3,4,3,2]] 
    with tf.Session() as sess:
    print(sess.run(tf.equal(A, B)))
    输出:[[ True  True  True False False]]
    '''
    correct_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))#tf.argmax(y_pre,1)表示预测出的值,tf.argmax(v_ys,1)表示实际值
    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#将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表示无论给多少个例子都行,784=28*28
ys = tf.placeholder(tf.float32, [None, 10])  #表示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 function
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
#cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=xs,labels=ys))

sess = tf.Session()
#important step
sess.run(tf.initialize_all_variables())


for i in range(1000):
    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(computer_accuracy(mnist.test.images,mnist.test.labels))

猜你喜欢

转载自www.cnblogs.com/Harriett-Lin/p/9593180.html
今日推荐