tensorflow实现简单卷积网络进行mnist分类

版权声明:本文为博主原创文章,转载请注明出处 https://blog.csdn.net/shuzfan/article/details/78714118

所有代码数据可在百度云下载:

链接: https://pan.baidu.com/s/1c31hKLM 密码: 4tpm

所有涉及tensorflow API用法的,均可查看https://tensorflow.google.cn/api_docs/

下面的代码实现了一个简单的卷积神经网络,来处理MNIST手写数字识别问题。

import input_data
import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
os.environ['CUDA_DEVICE_VISIBLE'] = '3'


def deepnn(x):

  with tf.name_scope('reshape'):
    x_image = tf.reshape(x, [-1, 28, 28, 1])

  # First convolutional layer - maps one grayscale image to 32 feature maps.
  with tf.name_scope('conv1'):
    W_conv1 = weight_variable([5, 5, 1, 32])
    b_conv1 = bias_variable([32])
    h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

  # Pooling layer - downsamples by 2X.
  with tf.name_scope('pool1'):
    h_pool1 = max_pool_2x2(h_conv1)

  # Second convolutional layer -- maps 32 feature maps to 64.
  with tf.name_scope('conv2'):
    W_conv2 = weight_variable([5, 5, 32, 64])
    b_conv2 = bias_variable([64])
    h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)

  # Second pooling layer.
  with tf.name_scope('pool2'):
    h_pool2 = max_pool_2x2(h_conv2)

  # Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
  # is down to 7x7x64 feature maps -- maps this to 1024 features.
  with tf.name_scope('fc1'):
    W_fc1 = weight_variable([7 * 7 * 64, 1024])
    b_fc1 = bias_variable([1024])

    h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])
    h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

  # Dropout - controls the complexity of the model, prevents co-adaptation of
  # features.
  with tf.name_scope('dropout'):
    keep_prob = tf.placeholder(tf.float32)
    h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

  # Map the 1024 features to 10 classes, one for each digit
  with tf.name_scope('fc2'):
    W_fc2 = weight_variable([1024, 10])
    b_fc2 = bias_variable([10])

    y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
  return y_conv, keep_prob


def conv2d(x, W):
  """conv2d returns a 2d convolution layer with full stride."""
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')


def max_pool_2x2(x):
  """max_pool_2x2 downsamples a feature map by 2X."""
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')


def weight_variable(shape):
  """weight_variable generates a weight variable of a given shape."""
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)


def bias_variable(shape):
  """bias_variable generates a bias variable of a given shape."""
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)


def main(_):
  # Import data
  mnist = input_data.read_data_sets('MNIST_data', one_hot=True)

  # Create the model
  x = tf.placeholder(tf.float32, [None, 784])

  # Define loss and optimizer
  y_ = tf.placeholder(tf.float32, [None, 10])

  # Build the graph for the deep net
  y_conv, keep_prob = deepnn(x)

  with tf.name_scope('loss'):
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits_v2(labels=y_,
                                                            logits=y_conv)
  cross_entropy = tf.reduce_mean(cross_entropy)

  with tf.name_scope('adam_optimizer'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)

  with tf.name_scope('accuracy'):
    correct_prediction = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))
    correct_prediction = tf.cast(correct_prediction, tf.float32)
  accuracy = tf.reduce_mean(correct_prediction)


  with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(20000):
      batch = mnist.train.next_batch(50)
      if i % 2000 == 0:
        train_accuracy = accuracy.eval(feed_dict={
            x: batch[0], y_: batch[1], keep_prob: 1.0})
        print('step %d, training accuracy %g' % (i, train_accuracy))
        print('test accuracy %g' % accuracy.eval(feed_dict={
            x: mnist.test.images, y_: mnist.test.labels, keep_prob: 1.0}))
      train_step.run(feed_dict={x: batch[0], y_: batch[1], keep_prob: 0.6})

if __name__ == '__main__':
  tf.app.run(main=main)

逐个解释一下里面一些比较陌生的用法:

tf.name_scope

tf.namescope通常和tf.variable_scope、tf.get_variable_scope一起使用,主要是为了声明变量的作用域:

import tensorflow as tf
import os

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'


var1 = tf.Variable(tf.zeros([2,2]))
with tf.name_scope('scope1'):
    var2 = tf.Variable(tf.zeros([2,2]))
    # 取消作用域
    with tf.name_scope(None):
        var3 = tf.Variable(tf.zeros([2,2]))
with tf.name_scope('scope1'):
    var4 = tf.Variable(tf.zeros([2,2]))
print(var1.name,'\n', var2.name,'\n', var3.name,
    '\n', var4.name)

打印结果如下:

Variable:0 
scope1/Variable:0 
Variable_1:0 
scope1_1/Variable:0

tf.reshape

# x_image = tf.reshape(x, [-1, 28, 28, 1])
reshape(
    tensor,
    shape,
    name=None
)

-1表示该维自动计算,并保证总的元素数量不变。

tf.nn.conv2d

conv2d(
    input,
    filter,
    strides,
    padding,
    use_cudnn_on_gpu=True,
    data_format='NHWC',
    name=None
)
  • input:4D向量,必须是half或者float32类型。维度顺序由data_format决定。
  • filter:4D向量,[filter_height, filter_width, in_channels, out_channels]
  • strides:1D向量,长度为4,分别表示4个维度的滑动步长。维度顺序由data_format决定。
  • padding:’SAME’或者’VALID’。’VALID’表示不padding,因此有可能丢弃一部分边缘数据;’SAME’表示自动补0,具体左右补多少可参考官网卷积的具体计算。
  • data_format:’NHWC’或者’NCHW’,默认’NHWC’表示[batch, height, width, channels]。

tf.nn.max_pool

max_pool(
    value,
    ksize,
    strides,
    padding,
    data_format='NHWC',
    name=None
)

类似的还有tf.nn.avg_pool,且参数用法和tf.nn.conv2d基本一致。

tf.truncated_normal

truncated_normal(
    shape,
    mean=0.0,
    stddev=1.0,
    dtype=tf.float32,
    seed=None,
    name=None
)

产生截断正态分布的随机变量。均值和标准差可以自己设定,如果生成的随机值与均值的差值大于两倍的标准差,就重新生成。

tf.nn.softmax_cross_entropy_with_logits_v2

softmax_cross_entropy_with_logits_v2(
    _sentinel=None,
    labels=None,
    logits=None,
    dim=-1,
    name=None
)

tf.nn.softmax_cross_entropy_with_logits 函数以后会被弃用。

  • _sentinel: 一般不使用
  • labels: labels的每一行labels[i]必须为一个概率分布,也即是说labels的长度必须等于类别数。特别的,对于独立分类问题,应当是one-shot label。
  • logits: 网络输出的未缩放的对数概率,即操作内部会对logits使用softmax操作,所以我们在外部就不要再用了。
  • dims: 类别信息所处的维度,默认-1,也就是最后一维

如果说label直接表示真实的类别标签,比如第10类的label就是9。此时应当使用

tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=None, logits=None, name=None)

猜你喜欢

转载自blog.csdn.net/shuzfan/article/details/78714118
今日推荐