學習筆記TF056:TensorFlow MNIST,數據集、分類、可視化

MNIST(Mixed National Institute of Standards and Technology)http://yann.lecun.com/exdb/mnist/ ,入門級計算機視覺數據集,美國中學生手寫數字。訓練集6萬張圖片,測試集1萬張圖片。數字經過預處理、格式化,大小調整並居中,圖片尺寸固定28x28。數據集小,訓練速度快,收斂效果好。

MNIST數據集,NIST數據集子集。4個文件。train-label-idx1-ubyte.gz 訓練集標記文件(28881字節),train-images-idx3-ubyte.gz 訓練集圖片文件(9912422字節),t10k-labels-idx1-ubyte.gz,測試集標記文件(4542字節),t10k-images-idx3-ubyte.gz 測試集圖片文件(1648877字節)。測試集,前5000個樣例取自原始NIST訓練集,後5000個取自原始NIST測試集。

訓練集標記文件 train-labels-idx1-ubyt格式:offset、type、value、description。magic number(MSB first)、number of items、label。
MSB(most significant bit,最高有效位),二進制,MSB最高加權位。MSB位於二進制最左側,MSB first 最高有效位在前。 magic number 寫入ELF格式(Executable and Linkable Format)的ELF頭文件常量,檢查和自己設定是否一致判斷文件是否損壞。

訓練集圖片文件 train-images-idx3-ubyte格式:magic number、number of images、number of rows、number of columns、pixel。
pixel(像素)取值範圍0-255,0-255代表背景色(白色),255代表前景色(黑色)。

測試集標記文件 t10k-labels-idx1-ubyte 格式:magic number(MSB first)、number of items、label。

測試集圖片文件 t10k-images-idx3-ubyte格式:magic number、number of images、number of rows、number of columns、pixel。

tensor flow-1.1.0/tensorflow/examples/tutorials/mnist。mnist_softmax.py 迴歸訓練,full_connected_feed.py Feed數據方式訓練,mnist_with_summaries.py 卷積神經網絡(CNN) 訓練過程可視化,mnist_softmax_xla.py XLA框架。

MNIST分類問題。

Softmax迴歸解決兩種以上分類。Logistic迴歸模型在分類問題推廣。tensorflow-1.1.0/tensorflow/examples/tutorials/mnist/mnist_softmax.py。

加載數據。導入input_data.py文件, tensorflow.contrib.learn.read_data_sets加載數據。FLAGS.data_dir MNIST路徑,可自定義。one_hot標記,長度爲n數組,只有一個元素是1.0,其他元素是0.0。輸出層softmax,輸出概率分佈,要求輸入標記概率分佈形式,以更計算交叉熵。

構建迴歸模型。輸入原始真實值(group truth),計算softmax函數擬合預測值,定義損失函數和優化器。用梯度下降算法以0.5學習率最小化交叉熵。tf.train.GradientDescentOptimizer。

訓練模型。初始化創建變量,會話啓動模型。模型循環訓練1000次,每次循環隨機抓取訓練數據100個數據點,替換佔位符。隨機訓練(stochastic training),SGD方法梯度下降,每次從訓練數據隨機抓取小部分數據梯度下降訓練。BGD每次對所有訓練數據計算。SGD學習數據集總體特徵,加速訓練過程。

評估模型。tf.argmax(y,1)返回模型對任一輸入x預測標記值,tf.argmax(y_,1) 正確標記值。tf.equal檢測預測值和真實值是否匹配,預測布爾值轉化浮點數,取平均值。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
from tensorflow.examples.tutorials.mnist import input_data
import tensorflow as tf
FLAGS = None
def main(_):
  # Import data 加載數據
  mnist = input_data.read_data_sets(FLAGS.data_dir, one_hot=True)
  # Create the model 定義迴歸模型
  x = tf.placeholder(tf.float32, [None, 784])
  W = tf.Variable(tf.zeros([784, 10]))
  b = tf.Variable(tf.zeros([10]))
  y = tf.matmul(x, W) + b #預測值
  # Define loss and optimizer 定義損失函數和優化器
  y_ = tf.placeholder(tf.float32, [None, 10]) # 輸入真實值佔位符
  # tf.nn.softmax_cross_entropy_with_logits計算預測值y與真實值y_差值,取平均值
  cross_entropy = tf.reduce_mean(
      tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))
  # SGD優化器
  train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
  # InteractiveSession()創建交互式上下文TensorFlow會話,交互式會話會成爲默認會話,可以運行操作(OP)方法(tf.Tensor.eval、tf.Operation.run)
  sess = tf.InteractiveSession()
  tf.global_variables_initializer().run()
  # Train 訓練模型
  for _ in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  # Test trained model 評估訓練模型
  correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
  accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  # 計算模型測試集準確率
  print(sess.run(accuracy, feed_dict={x: mnist.test.images,
                                      y_: mnist.test.labels}))
if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--data_dir', type=str, default='/tmp/tensorflow/mnist/input_data',
                      help='Directory for storing input data')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

訓練過程可視化。tensorflow-1.1.0/tensorflow/examples/tutorials/mnist/mnist_summaries.py 。
TensorBoard可視化,訓練過程,記錄結構化數據,支行本地服務器,監聽6006端口,瀏覽器請求頁面,分析記錄數據,繪製統計圖表,展示計算圖。
運行腳本:python mnist_with_summaries.py。
訓練過程數據存儲在/tmp/tensorflow/mnist目錄,可命令行參數–log_dir指定。運行tree命令,ipnut_data # 存放訓練數據,logs # 訓練結果日誌,train # 訓練集結果日誌。運行tensorboard命令,打開瀏覽器,查看訓練可視化結果,logdir參數標明日誌文件存儲路徑,命令 tensorboard –logdir=/tmp/tensorflow/mnist/logs/mnist_with_summaries 。創建摘要文件寫入符(FileWriter)指定。

# sess.graph  圖定義,圖可視化
file_writer = tf.summary.FileWriter('/tmp/tensorflow/mnist/logs/mnist_with_summaries', sess.graph)

瀏覽器打開服務地址,進入可視化操作界面。

可視化實現。

給一個張量添加多個摘要描述函數variable_summaries。SCALARS面板顯示每層均值、標準差、最大值、最小值。
構建網絡模型,weights、biases調用variable_summaries,每層採用tf.summary.histogram繪製張量激活函數前後變化。HISTOGRAMS面板顯示。
繪製準確率、交叉熵,SCALARS面板顯示。

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import os
import sys
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
FLAGS = None
def train():
  # Import data
  mnist = input_data.read_data_sets(FLAGS.data_dir,
                                    one_hot=True,
                                    fake_data=FLAGS.fake_data)
  sess = tf.InteractiveSession()
  # Create a multilayer model.
  # Input placeholders
  with tf.name_scope('input'):
    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)
  # We can't initialize these variables to 0 - the network will get stuck.
  def weight_variable(shape):
    """Create a weight variable with appropriate initialization."""
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)
  def bias_variable(shape):
    """Create a bias variable with appropriate initialization."""
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)
  def variable_summaries(var):
    """Attach a lot of summaries to a Tensor (for TensorBoard visualization)."""
    """對一個張量添加多個摘要描述"""
    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)
  def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
    # Adding a name scope ensures logical grouping of the layers in the graph.
    # 確保計算圖中各層分組,每層添加name_scope
    with tf.name_scope(layer_name):
      # This Variable will hold the state of the weights for the layer
      with tf.name_scope('weights'):
        weights = weight_variable([input_dim, output_dim])
        variable_summaries(weights)
      with tf.name_scope('biases'):
        biases = bias_variable([output_dim])
        variable_summaries(biases)
      with tf.name_scope('Wx_plus_b'):
        preactivate = tf.matmul(input_tensor, weights) + biases
        tf.summary.histogram('pre_activations', preactivate) # 激活前直方圖
      activations = act(preactivate, name='activation')
      tf.summary.histogram('activations', activations) # 激活後直方圖
      return activations
  hidden1 = nn_layer(x, 784, 500, 'layer1')
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    tf.summary.scalar('dropout_keep_probability', keep_prob)
    dropped = tf.nn.dropout(hidden1, keep_prob)
  # Do not apply softmax activation yet, see below.
  y = nn_layer(dropped, 500, 10, 'layer2', act=tf.identity)
  with tf.name_scope('cross_entropy'):
    diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y)
    with tf.name_scope('total'):
      cross_entropy = tf.reduce_mean(diff)
  tf.summary.scalar('cross_entropy', cross_entropy) # 交叉熵
  with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(FLAGS.learning_rate).minimize(
        cross_entropy)
  with tf.name_scope('accuracy'):
    with tf.name_scope('correct_prediction'):
      correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
    with tf.name_scope('accuracy'):
      accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
  tf.summary.scalar('accuracy', accuracy) # 準確率
  # Merge all the summaries and write them out to
  # /tmp/tensorflow/mnist/logs/mnist_with_summaries (by default)
  merged = tf.summary.merge_all()
  train_writer = tf.summary.FileWriter(FLAGS.log_dir + '/train', sess.graph)
  test_writer = tf.summary.FileWriter(FLAGS.log_dir + '/test')
  tf.global_variables_initializer().run()
  def feed_dict(train):
    """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
    if train or FLAGS.fake_data:
      xs, ys = mnist.train.next_batch(100, fake_data=FLAGS.fake_data)
      k = FLAGS.dropout
    else:
      xs, ys = mnist.test.images, mnist.test.labels
      k = 1.0
    return {x: xs, y_: ys, keep_prob: k}
  for i in range(FLAGS.max_steps):
    if i % 10 == 0:  # Record summaries and test-set accuracy
      summary, acc = sess.run([merged, accuracy], feed_dict=feed_dict(False))
      test_writer.add_summary(summary, i)
      print('Accuracy at step %s: %s' % (i, acc))
    else:  # Record train set summaries, and train
      if i % 100 == 99:  # Record execution stats
        run_options = tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE)
        run_metadata = tf.RunMetadata()
        summary, _ = sess.run([merged, train_step],
                              feed_dict=feed_dict(True),
                              options=run_options,
                              run_metadata=run_metadata)
        train_writer.add_run_metadata(run_metadata, 'step%03d' % i)
        train_writer.add_summary(summary, i)
        print('Adding run metadata for', i)
      else:  # Record a summary
        summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
        train_writer.add_summary(summary, i)
  train_writer.close()
  test_writer.close()
def main(_):
  if tf.gfile.Exists(FLAGS.log_dir):
    tf.gfile.DeleteRecursively(FLAGS.log_dir)
  tf.gfile.MakeDirs(FLAGS.log_dir)
  train()
if __name__ == '__main__':
  parser = argparse.ArgumentParser()
  parser.add_argument('--fake_data', nargs='?', const=True, type=bool,
                      default=False,
                      help='If true, uses fake data for unit testing.')
  parser.add_argument('--max_steps', type=int, default=1000,
                      help='Number of steps to run trainer.')
  parser.add_argument('--learning_rate', type=float, default=0.001,
                      help='Initial learning rate')
  parser.add_argument('--dropout', type=float, default=0.9,
                      help='Keep probability for training dropout.')
  parser.add_argument(
      '--data_dir',
      type=str,
      default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),
                           'tensorflow/mnist/input_data'),
      help='Directory for storing input data')
  parser.add_argument(
      '--log_dir',
      type=str,
      default=os.path.join(os.getenv('TEST_TMPDIR', '/tmp'),
                           'tensorflow/mnist/logs/mnist_with_summaries'),
      help='Summaries log directory')
  FLAGS, unparsed = parser.parse_known_args()
  tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)

參考資料:
《TensorFlow技術解析與實戰》

歡迎推薦上海機器學習工作機會,我的微信:qingxingfengzi

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章