學習筆記TF056:TensorFlow MNIST,資料集、分類、可視化,tf056tensorflow

來源:互聯網
上載者:User

學習筆記TF056:TensorFlow MNIST,資料集、分類、可視化,tf056tensorflow

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.