《TensorFlow实战》MNIST分类实战笔记-ch03

背景

因为看paper或者别人的源码,总是连感性认识都没有,很是捉急。在网上找一些博客来看看, 不过是临时解决问题,碎片的很!故买本tensorflow实战书学习,培养感性认识,待将来有机会再上升到理性认识。

学习内容

因为之前隐约看过相关代码,装过tensorflow,跑过些例子。对于这个工具的属性,网络的输入、输出等方面都没有一个直观感受。所以笔记内容为本书学习章节代码注释版,也不敢妄称为学习心得,请各位大佬赐教

基础版
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

print(mnist.train.images.shape, mnist.train.labels.shape)
print(mnist.test.images.shape, mnist.test.labels.shape)
print(mnist.validation.images.shape, mnist.validation.labels.shape)

import tensorflow as tf
sess = tf.InteractiveSession() ## 其实可以用with Session() as sess: 
x = tf.placeholder(tf.float32, [None, 784],name="x")

### 只是声明变量,并没有初始化 get_varible用法不同
W = tf.Variable(tf.zeros([784, 10]),name="W")
b = tf.Variable(tf.zeros([10]))
print(W) ## 这里并没有运行,只能看到是一个tensor

### 定义模型迭代预测值 softmax函数
y = tf.nn.softmax(tf.matmul(x, W) + b)
### 样本真实值
y_ = tf.placeholder(tf.float32, [None, 10])

###定义交叉熵损失函数
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), axis=[1])) ### axis == reduction_indices

### 定义训练器来优化损失函数
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)

tf.global_variables_initializer().run() ##或者sess.run(tf.global_variables_initializer())
## 打印初始化后的权重矩阵
print (W.eval(sess)) ## 或者 W.eval()

## 开始迭代训练,优化模型参数
for i in range(1000):
    batch_xs, batch_ys = mnist.train.next_batch(100)
    sess.run(train_step, feed_dict={x:batch_xs, y_:batch_ys}) # train_step.run({x: batch_xs, y_: batch_ys})
    ###print (y) ##只能打印出y tensor
    pre = sess.run(y, feed_dict={x:batch_xs, W:W.eval(), b:b.eval()})
    print ("pre result:",pre)
    break

## 计算准确率
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

print(accuracy.eval({x: mnist.test.images, y_: mnist.test.labels}))
sess.close()

进阶版本
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data


max_steps=1000
learning_rate=0.001
dropout=0.9
# data_dir='/tmp/tensorflow/mnist/input_data'
log_dir='/tmp/tensorflow/mnist/logs/mnist_with_summaries'

# Import data
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
sess = tf.InteractiveSession()

# Create a multilayer model.
# 占位符
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')

### 这个节点用来展示图片
### tf.reshape(tensor,shape,name=None);-1 表示可以 这个值需要被推断出来
# tf.summary.image(
#     name,
#     tensor,  #构建的图像的Tensor必须是4-D形状[batch_size, height, width, channels];
               #因为是黑白图像,所以channels等于1;长宽等于28*28
#     max_outputs=3, #Max number of batch elements to generate images for.
#     collections=None,
#     family=None
# )
with tf.name_scope('input_reshape'):
  image_shaped_input = tf.reshape(x, [-1, 28, 28, 1])
  tf.summary.image('input', image_shaped_input, 10)

# 初始化权重矩阵
def weight_variable(shape):
  """Create a weight variable with appropriate initialization."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial,name="w")

# 初始化偏置
def bias_variable(shape):
  """Create a bias variable with appropriate initialization."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial,name="bias")

# 记录变量的各种值
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)

## 封装layer
#input_tensor
#input_dim,output_dim (输入向量的维度)
#layer_name 层的名称
#act 激活函数
def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu):
  """Reusable code for making a simple neural net layer.
  It does a matrix multiply, bias add, and then uses relu to nonlinearize.
  It also sets up name scoping so that the resultant graph is easy to read,
  and adds a number of summary ops.
  """
  # Adding a name scope ensures logical grouping of the layers in the graph.
  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'):
    # The raw formulation of cross-entropy,
    #
    # tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(tf.softmax(y)),
    #                               reduction_indices=[1]))
    #
    # can be numerically unstable.
    #
    # So here we use tf.nn.softmax_cross_entropy_with_logits on the
    # raw outputs of the nn_layer above, and then average across
    # the batch.
  diff = tf.nn.softmax_cross_entropy_with_logits(logits=y, labels=y_)
  ##计算每个batch中交叉熵均值
  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(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/mnist_logs (by default)
merged = tf.summary.merge_all()
train_writer = tf.summary.FileWriter(log_dir + '/train', sess.graph)
test_writer = tf.summary.FileWriter(log_dir + '/test')
tf.global_variables_initializer().run()

  # Train the model, and also write summaries.
  # Every 10th step, measure test-set accuracy, and write test summaries
  # All other steps, run train_step on training data, & add training summaries

def feed_dict(train):
  """Make a TensorFlow feed_dict: maps data onto Tensor placeholders."""
  if train:
    xs, ys = mnist.train.next_batch(100)
    k = dropout
  else:
    xs, ys = mnist.test.images, mnist.test.labels
    k = 1.0
  return {x: xs, y_: ys, keep_prob: k}

  
saver = tf.train.Saver()  
for i in range(max_steps):
  if i % 10 == 0:  # Record summaries and test-set accuracy 每10步计算一次准确率
    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,每100步,记录summary 并记录内存及耗时
      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)
      saver.save(sess, log_dir+"/model.ckpt", i)
      print('Adding run metadata for', i)
    else:  # Record a summary 记录summary 并记录内存及耗时
      summary, _ = sess.run([merged, train_step], feed_dict=feed_dict(True))
      train_writer.add_summary(summary, i)

train_writer.close()
test_writer.close()

《TensorFlow实战》MNIST分类实战笔记-ch03_第1张图片

学习总结

结合本书第三章及第九章,学习利用tensorflow 进行简单的图像分类,熟悉了tf1.x的使用流程,及tf1.x部分方法的使用,进阶部分有展示命名空间的内容以及tensorboard可视化模型。
一般简单的使用流程

  • 定义输入操作节点
  • 定义权重、偏置节点(对于层,可以抽象出来)
  • 定义层 layer
    • 矩阵乘法操作
    • 激活函数操作
  • 定义损失 loss
  • 定义训练 Train
  • Run Train定义的操作,以及需要记录 loss,accuracy, weight变量

你可能感兴趣的:(ML&DL)