所有代碼數據可在百度雲下載:
鏈接: 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)