一、与tensorflow自带的函数相比,slim能够让我们不用重复写函数的参数,那么函数的参数写在哪里呢?核心方法就是slim.arg_scope.
也就是说可以通过这个函数将不想重复写的参数通过这个函数自动赋值。
这个函数的作用是给list_ops中的内容设置默认值。但是每个list_ops中的每个成员需要用@add_arg_scope修饰才行。所以使用slim.arg_scope()有两个步骤:
- 使用@slim.add_arg_scope修饰目标函数
- 用 slim.arg_scope()为目标函数设置默认参数.
import tensorflow.contrib.slim as slim
@slim.add_arg_scope#
def hh(name, add_arg):
print("name:", name)
print("add_arg:", add_arg)
with slim.arg_scope([hh], add_arg='this is add'):
hh('test')#这里就可以不用对参数 add_arg赋值了
#结果:
#name: test
#add_arg: this is add
二、使用slim构建神经网络常用的函数
slim.conv2d是对tf.conv2d的进一步封装,常见调用方式
net = slim.conv2d(inputs, 256, [3, 3], stride=1, scope='conv1_1')
源代码
@add_arg_scope
def convolution(inputs,num_outputs,
kernel_size,
stride=1,
padding='SAME',
data_format=None,
rate=1,
activation_fn=nn.relu,
normalizer_fn=None,
normalizer_params=None,
weights_initializer=initializers.xavier_initializer(),
weights_regularizer=None,
biases_initializer=init_ops.zeros_initializer(),
biases_regularizer=None,
reuse=None,
variables_collections=None,
outputs_collections=None,
trainable=True,
scope=None)
参数解析:
padding : 补零的方式,例如'SAME'
activation_fn : 激活函数,默认是nn.relu
normalizer_fn : 正则化函数,默认为None,这里可以设置为batch normalization,函数用slim.batch_norm
normalizer_params : slim.batch_norm中的参数,以字典形式表示
weights_initializer : 权重的初始化器,initializers.xavier_initializer()
weights_regularizer : 权重的正则化器,一般不怎么用到
biases_initializer : 如果之前有batch norm,那么这个及下面一个就不用管了
biases_regularizer :
trainable : 参数是否可训练,默认为True
scope:你绘制的网络结构图中它属于那个范围内
三、slim.max_pool2d
net = slim.max_pool2d(net, [2, 2], scope='pool1')
前两个参数分别为网络输入,输出的神经元数量,第三个同上
四、slim.flattern(inputs,outputs_collections=None,scope=None)
功能:将输入扁平化但保留batch_size,假设第一维是batch
参数:
inpust: a tensor of size [batch_size,...]
outputs_collections:collection to add the outputs
scope: optional scope for name_scope
test=([[[1,2,3],[4,5,6],[7,8,9]],[[10,11,12],[13,14,15],[16,17,27]],[[18,19,20],[21,22,23],[24,25,26]]]) #shape is (3,3,3)
test=slim.fatten(test)
test.eval()
array([[ 1, 2, 3, ..., 7, 8, 9],
[10, 11, 12, ..., 16, 17, 27],
[18, 19, 20, ..., 24, 25, 26]], dtype=int32)
test.get_shape()
TensorShape([Dimension(3), Dimension(9)]) #(3,9)
五、slim.fully_connected()
slim.fully_connected(x,128,scope='fc1')
前两个参数分别为网络输入,输出的神经元数量