把slim代码改成layers
把slim代码改成layers代码,为什么不改成keras代码?因为需要该很多东西,工作量比layers的方法大。layers的低层实现是keras。
快速修改的方法。
调查默认值
首先,找到模型的入口,我的如下图。
然后,顺着再找出所有的
with slim.arg_scope([slim.batch_norm], **batch_norm_params):
with slim.arg_scope([slim.conv2d], weights_regularizer=regularizer):
with slim.arg_scope([slim.separable_conv2d],
weights_regularizer=depthwise_regularizer) as sc:
对他们进行归类,去掉其中无用的。你心里要明白哪些参数能用到,哪些参数不必要。
最后,整理成类似于我的结构。标题为层的名字,下面为改成设置的默认属性。
filters,kernel-size,stride,pad,weight-decay,activation。这些是必要的。name必须和原model一样。
现在很多训练好的模型是根据slim来的。 这样可以直接调用他们。查看pb文件节点name我就不说了。
最后就是复现。
复现
定义单独的cnn,bn,之类的层。这是最常用的方法和最简单的。
高级点的,可以用下面的模块-偏函数。
from functools import partial
....
my_dense_layer = partial(
tf.layers.dense, activation=tf.nn.relu,
kernel_regularizer=tf.contrib.layers.l2_regularizer(scale))
....
hidden1 = my_dense_layer(X, n_hidden1, name="hidden1")
layers的层定义
这里面有两种方法定义层,一个是函数,一个类。
类定义
都是大写字母开头,用法和keras.layer层相同。例子如下
import tensorflow as tf
x = tf.compat.v1.placeholder(shape=(None, 4, 4), dtype='float32')
y = tf.layers.Flatten()(x)
函数定义
都是小写字母
import tensorflow as tf
x = tf.compat.v1.placeholder(shape=(None, 4, 4), dtype='float32')
y = tf.layers.flatten(x)
二者参数有些也不同,一般在类定义中的参数,函数定义中没有。
建议使用函数定义的层。
奇葩参数
1
slim.separable_conv2d(inputs=net, num_outputs=None
num_outputs=None,也就是只进行depthwise,也就是1x1的卷积,输出通道数为num_filters_in * depth_multiplier
其中参数说明
num_outputs: The number of pointwise convolution output filters. If is None, then we skip the pointwise convolution stage.
depth_multiplier: The number of depthwise convolution output channels for each input channel. The total number of depthwise convolution output channels will be equal to `num_filters_in * depth_multiplier`.
我理解, num_outputs是指keranel的channel个数。
2
slim.separable_conv2d(inputs=net, num_outputs=None, kernel_size=conv_def.kernel, stride=conv_def.stride,
depth_multiplier=1.0, normalizer_fn=slim.batch_norm
卷积,全连接,深度可分离里面都有这个参数normalizer_fn=slim.batch_norm、其含义是是否添加bn层处理,而设置bias不被使用。如果normalizer_fn=None,表示添加bias到结果中。
doc中原文
if `normalizer_fn` is None, it adds bias to the result, creating a variable called 'biases', otherwise, the `normalizer_fn` is applied.
以上面代码为例。流程是 seqarable_conv+bn/bias+activation.