【簡述】git
咱們在學習編程語言時,每每第一個程序就是打印「Hello World」,那麼對於人工智能學習系統平臺來講,他的「Hello World」小程序就是MNIST手寫數字訓練了。MNIST是一個手寫數字的數據集,官網是Yann LeCun's website。數據集總共包含了60000行的訓練數據集(mnist.train
)和10000行的測試數據集(mnist.test
),每個數字的大小爲28*28像素。經過利用Tensorflow人工智能平臺,咱們能夠學習到人工智能學習平臺是如何經過數據進行學習的。web
【數據準備】編程
下載mnist數據集,和mnist_10k_sprite.png圖片,分別放在MNIST_data文件夾和projector/data文件夾下。小程序
【代碼】瀏覽器
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data from tensorflow.contrib.tensorboard.plugins import projector #載入數據集 mnist = input_data.read_data_sets("MNIST_data/",one_hot=True) #運行次數 max_steps = 1001 #圖片數量 image_num = 3000 #文件路徑 DIR = "E:/Github/TensorFlow/trunk/Test/" #定義會話 sess = tf.Session() #載入圖片 embedding = tf.Variable(tf.stack(mnist.test.images[:image_num]), trainable=False, name='embedding') #參數概要 def variable_summaries(var): with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean)#平均值 with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev)#標準差 tf.summary.scalar('max', tf.reduce_max(var))#最大值 tf.summary.scalar('min', tf.reduce_min(var))#最小值 tf.summary.histogram('histogram', var)#直方圖 #命名空間 with tf.name_scope('input'): #這裏的none表示第一個維度能夠是任意的長度 x = tf.placeholder(tf.float32,[None,784],name='x-input') #正確的標籤 y = tf.placeholder(tf.float32,[None,10],name='y-input') #顯示圖片 with tf.name_scope('input_reshape'): image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input', image_shaped_input, 10) with tf.name_scope('layer'): #建立一個簡單神經網絡 with tf.name_scope('weights'): W = tf.Variable(tf.zeros([784,10]),name='W') variable_summaries(W) with tf.name_scope('biases'): b = tf.Variable(tf.zeros([10]),name='b') variable_summaries(b) with tf.name_scope('wx_plus_b'): wx_plus_b = tf.matmul(x,W) + b with tf.name_scope('softmax'): prediction = tf.nn.softmax(wx_plus_b) with tf.name_scope('loss'): #交叉熵代價函數 loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction)) tf.summary.scalar('loss',loss) with tf.name_scope('train'): #使用梯度降低法 train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss) #初始化變量 sess.run(tf.global_variables_initializer()) with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): #結果存放在一個布爾型列表中 correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))#argmax返回一維張量中最大的值所在的位置 with tf.name_scope('accuracy'): #求準確率 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))#把correct_prediction變爲float32類型 tf.summary.scalar('accuracy',accuracy) #產生metadata文件 if tf.gfile.Exists(DIR + 'projector/projector/metadata.tsv'): tf.gfile.DeleteRecursively(DIR + 'projector/projector/metadata.tsv') with open(DIR + 'projector/projector/metadata.tsv', 'w') as f: labels = sess.run(tf.argmax(mnist.test.labels[:],1)) for i in range(image_num): f.write(str(labels[i]) + '\n') #合併全部的summary merged = tf.summary.merge_all() projector_writer = tf.summary.FileWriter(DIR + 'projector/projector',sess.graph) saver = tf.train.Saver() config = projector.ProjectorConfig() embed = config.embeddings.add() embed.tensor_name = embedding.name embed.metadata_path = DIR + 'projector/projector/metadata.tsv' embed.sprite.image_path = DIR + 'projector/data/mnist_10k_sprite.png' embed.sprite.single_image_dim.extend([28,28]) projector.visualize_embeddings(projector_writer,config) for i in range(max_steps): #每一個批次100個樣本 batch_xs,batch_ys = mnist.train.next_batch(100) run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE) run_metadata = tf.RunMetadata() sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata) summary = sess.run(merged,feed_dict={x:batch_xs,y:batch_ys},options=run_options,run_metadata=run_metadata) projector_writer.add_run_metadata(run_metadata, 'step%03d' % i) projector_writer.add_summary(summary, i) if i%100 == 0: acc = sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels}) print ("Iter " + str(i) + ", Testing Accuracy= " + str(acc)) saver.save(sess, DIR + 'projector/projector/a_model.ckpt', global_step=max_steps) projector_writer.close() sess.close()
【運行】網絡
直接運行代碼編程語言
【可視化界面】ide
一、在cmd命令行輸入tensorboard --logdir=progector文件夾路徑;函數
二、在瀏覽器打開http://localhost:6006路徑便可查看可視化效果。學習
源碼獲取方式,關注公總號RaoRao1994,查看往期精彩-全部文章,便可獲取資源下載連接
更多資源獲取,請關注公總號RaoRao1994