莫烦tensorflow教程笔记(六)

来源:互联网 发布:关闭windows自动更新 编辑:程序博客网 时间:2024/05/22 15:47

mnist手写数字分类及简单的可视化

import numpy as npimport tensorflow as tffrom tensorflow.examples.tutorials.mnist import input_datamnist = input_data.read_data_sets('E:\\python\\minist',one_hot=True)  #此处选择自己存放数据的地址def add_layer(inputs,in_size,out_size,activation_function=None):    with tf.name_scope('layer'):        Weights = tf.Variable(tf.random_uniform([in_size,out_size]),name='weights')        biases = tf.Variable(tf.zeros([1,out_size]) + 0.1,name='biases')        Wx_plus_b = tf.matmul(inputs,Weights) + biases    if activation_function == None:        outputs = Wx_plus_b    else:        outputs = activation_function(Wx_plus_b)    return outputsdef compute_accuracy(v_xs,v_ys):    global prediction    y_pre = session.run(prediction,feed_dict={xs:v_xs,ys:v_ys})    correct_prediction = tf.equal(tf.argmax(y_pre,axis=1),tf.argmax(v_ys,axis=1))     ##axis=1 表示按行求和    accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))    result = session.run(accuracy,feed_dict={xs:v_xs,ys:v_ys})    return resultwith tf.name_scope('input'):    xs = tf.placeholder(tf.float32,[None,784],name='x_input')    ys = tf.placeholder(tf.float32,[None,10],name='y_input')prediction = add_layer(xs,in_size=784,out_size=10,activation_function=tf.nn.softmax)with tf.name_scope('loss'):    cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.log(prediction),reduction_indices=[1]))      tf.summary.scalar('cross_entropy',cross_entropy)            ##记录cross_entropy的变化情况with tf.name_scope('train'):    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)session = tf.Session()merged = tf.summary.merge_all()writer = tf.summary.FileWriter('E:\\python\\hhhhh',session.graph)init = tf.global_variables_initializer()session.run(init)for i in range(1000):    batch_xs,batch_ys = mnist.train.next_batch(100)    session.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})    if i % 50 == 0:        print(compute_accuracy(mnist.test.images,mnist.test.labels))        res = session.run(merged,feed_dict={xs:batch_xs,ys:batch_ys})        writer.add_summary(res,i)