Is there any advantage in using tf.nn.*
over tf.layers.*
?
Most of the examples in the doc use tf.nn.conv2d
, for instance, but it is not clear why they do so.
Is there any advantage in using tf.nn.*
over tf.layers.*
?
Most of the examples in the doc use tf.nn.conv2d
, for instance, but it is not clear why they do so.
All of these other replies talk about how the parameters are different, but actually, the main difference of tf.nn and tf.layers conv2d is that for tf.nn, you need to create your own filter tensor and pass it in. This filter needs to have the size of:
[kernel_height, kernel_width, in_channels, num_filters]
Essentially, tf.nn is lower level than tf.layers. Unfortunately, this answer is not applicable anymore is tf.layers is obselete
As others mentioned the parameters are different especially the "filter(s)". tf.nn.conv2d takes a tensor as a filter, which means you can specify the weight decay (or maybe other properties) like the following in cifar10 code. (Whether you want/need to have weight decay in conv layer is another question.)
I'm not quite sure how to set weight decay in tf.layers.conv2d since it only take an integer as filters. Maybe using
kernel_constraint
?On the other hand, tf.layers.conv2d handles activation and bias automatically while you have to write additional codes for these if you use tf.nn.conv2d.
As GBY mentioned, they use the same implementation.
There is a slight difference in the parameters.
For tf.nn.conv2d:
For tf.layers.conv2d:
I would use tf.nn.conv2d when loading a pretrained model (example code: https://github.com/ry/tensorflow-vgg16), and tf.layers.conv2d for a model trained from scratch.
For convolution, they are the same. More precisely,
tf.layers.conv2d
(actually_Conv
) usestf.nn.convolution
as the backend. You can follow the calling chain of:tf.layers.conv2d>Conv2D>Conv2D.apply()>_Conv>_Conv.apply()>_Layer.apply()>_Layer.\__call__()>_Conv.call()>nn.convolution()...
Take a look here:tensorflow > tf.layers.conv2d
and here: tensorflow > conv2d
As you can see the arguments to the layers version are:
and the nn version:
I think you can choose the one with the options you want/need/like!
DIFFERENCES IN PARAMETER:
Using tf.layer* in a code:
Using tf.nn* in a code: ( Notice we need to pass weights and biases additionally as parameters )