tensorflow中mnist识别和结果可视化

来源:互联网 发布:java线程sleep和wait 编辑:程序博客网 时间:2024/04/28 06:06
import tensorflow as tfimport numpy as npimport input_datamnist = input_data.read_data_sets('MNIST_data',one_hot=True)def add_layer(inputs,in_size,out_size,n_layer,activation_function=None):    layer_name = 'layer%s' %n_layer    with tf.name_scope(layer_name):        with tf.name_scope('weights'): #tf.name_scope()创建结点            Weights = tf.Variable(tf.random_normal([in_size,out_size],mean=0,stddev=1))            tf.histogram_summary(layer_name+'/weights',Weights)        with tf.name_scope('biases'):            biases = tf.Variable(tf.zeros([1,out_size])+0.25)            tf.histogram_summary(layer_name+'/biases',biases) #tf.histogram_summary()创建值        with tf.name_scope('out1'):            out1 = tf.matmul(inputs,Weights)+biases            tf.histogram_summary(layer_name+'/out1',out1)        if activation_function is None:            outputs = out1        else:            outputs = activation_function(out1)        tf.histogram_summary(layer_name+'/output',outputs)        return outputs#define placeholder for inputs to networkwith tf.name_scope('inputs'):    xs = tf.placeholder(tf.float32,[None,784],name = 'input_x')    ys = tf.placeholder(tf.float32,[None,10],name = 'input_y')#add output layerprediction = add_layer(xs,784,10,n_layer=1,activation_function=tf.nn.softmax)#the error between prediction and real datawith tf.name_scope('cross_entropy'):    cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))    tf.scalar_summary('cross_entropy',cross_entropy)with tf.name_scope('train'):        train_step = tf.train.GradientDescentOptimizer(0.25).minimize(cross_entropy)init = tf.initialize_all_variables()sess = tf.Session()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 resultmerged = tf.merge_all_summaries() #将所有summary mergedwriter = tf.train.SummaryWriter('logs/',sess.graph) #写入logs文件夹下sess.run(init)for i in range(1000):    batch_xs,batch_ys = mnist.train.next_batch(500)    sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})    if i % 50 == 0:        result = sess.run(merged,feed_dict={xs:mnist.test.images,ys:mnist.test.labels})        writer.add_summary(result,i)        print(compute_accuracy(mnist.test.images,mnist.test.labels))

运行

tensorboard –logdir = ‘log/’

结果

这里写图片描述
这里写图片描述
这里写图片描述
这里写图片描述

原创粉丝点击