在TensorFlow中封裝好了一個高級庫,tf.contrib.layers庫封裝了不少的函數,使用這個高級庫來開發將會提升效率,卷積函數使用tf.contrib.layers.conv2d,池化函數使用tf.contrib.layers.max_pool2d和tf.contrib.layers.avg_pool2d,全鏈接函數使用 tf.contrib.layers.fully_connected,下面來看裏面封裝好的函數接口:git
以最複雜的卷積爲例,其餘的幾個函數與之相似:數組
layers.conv2d(inputs, num_outputs, kernel_size, stride, padding='SAME', data_format=None, rate=1, activation_fn=tf.nn.relu, normalizer_fn=None, normalizer_params=None, weights_initializer=initializers.xavier_initializers(), weights_regularizer=None, reuse=None, variables_collections=None, outputs_collections=None, trainable=True, scope=None)
經常使用的參數說明:網絡
inputs:輸入的數據ide
num_outputs:設置輸出的channel數量。這裏不用在設置輸入的channel的數量了,該函數會自動根據shape來判斷。函數
kernel_size:卷積核大小,不須要帶上batch和channel,只須要輸入尺寸便可,[ 5, 5 ]就表明5x5大小的卷積核,若是長寬都同樣,能夠直接寫一個5就好了。spa
stride:步長,默認的長寬都是相等的步長,卷積時通常都用1,默認的值也是1,若是長寬都不一樣,也能夠用一個數組[ 1,2 ]來表示。code
padding:設置填充的規則。orm
activation_fn:輸出後的激活函數。blog
weights_initializer:權重的初始化方式,默認使用的是 initializers.xavier_initializers(),可以使得全部層的梯度保持大致相同,biases_initializer同理。接口
weights_regularizer:正則化項,能夠加入正則函數。
trainable:是否可訓練,如做爲訓練節點,必須設置爲True。
下面咱們使用layers構建一個網絡模型:
import tensorflow.contrib.layers as layers x = tf.placeholder(dtype=tf.float32, shape=[None, 32, 32, 3]) y = tf.placeholder(dtype=tf.float32, shape=[None, 10]) x_images = tf.reshape(x, [-1, 32, 32, 3]) h_conv1 = layers.conv2d(x_images, 64, 3, 1, activation_fn=tf.nn.relu) h_pool1 = layers.max_pool2d(h_conv1, [2, 2], stride=2, padding='SAME') h_conv2 = layers.conv2d(h_pool1, 64, 3, 1, activation_fn=tf.nn.relu) h_pool2 = layers.max_pool2d(h_conv2, [2, 2], stride=2, padding='SAME') h_conv3 = layers.conv2d(h_pool2, 32, 3, 1, activation_fn=tf.nn.relu) h_pool3 = layers.max_pool2d(h_conv3, [2, 2], stride=2, padding='SAME') h_conv4 = layers.conv2d(h_pool3, 16, 3, 1, activation_fn=tf.nn.relu) h_pool4 = layers.max_pool2d(h_conv4, [2, 2], stride=2, padding='SAME') h_conv5 = layers.conv2d(h_pool4, 10, 3, 1, activation_fn=tf.nn.relu) y_pool = tf.reshape(h_conv5, shape=[-1, 40]) y_pool = layers.fully_connected(y_pool, 10, activation_fn=None) cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=y_pool)) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cross_entropy)
使用layers是否是極大的簡化了網絡默寫的代碼,提高了咱們的代碼效率。