【发布时间】:2020-12-23 00:03:01
【问题描述】:
我是 CNN 和 TensorFlow 的新手。自从阅读 Geron 的 Hands-on TF 书以来,已经过去了大约 2 天。如果有人可以帮助我,我将不胜感激。
目标:了解 keras 官方文档 (https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) 如何以及为何使用 Conv2D (m,n...) 表示法。
问题:我写了两组代码。我理解第一个,它使用明确的声明集来表示 filters 和 kernel_size 的数量。
TF 和 Python 版本:
sys.version
Out: '3.7.9 (default, Aug 31 2020, 17:10:11) [MSC v.1916 64 bit (AMD64)]'
tf.__version__
Out: '2.3.0'
代码 1:
import tensorflow as tf
input_shape = (4, 30, 60, 3) #Sample 30x60 images with RGB channel. `batch_size` = 4
a1=tf.keras.layers.Conv2D(filters=10,kernel_size=(3,3), input_shape=input_shape[1:])
a1(tf.random.normal(input_shape)).shape
a1.filters
a1.kernel_size
model = tf.keras.Sequential()
model.add(a1)
model.output_shape
model.summary()
输出:
Out[99]: TensorShape([4, 28, 58, 10]) #we are not using padding. So, the shape of tensor is 4 batch x 28x58 x 10 filters Out[99]: 10 # number of filters Out[99]: (3, 3) #kernel size Out[99]: (None, 28, 58, 10) #this is the feature map for one image Model: "sequential_24" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_34 (Conv2D) (None, 28, 58, 10) 280 ================================================================= Total params: 280 Trainable params: 280 Non-trainable params: 0 _________________________________________________________________
我对上面的输出很满意。我已经在上面添加了我的想法。
代码 2:
现在,我根据上面的官方文档修改了上面的代码,没有明确提及kernel_size 和filters。
a2=tf.keras.layers.Conv2D(10,3,3, input_shape=input_shape[1:]) #here's the change.
a2(tf.random.normal(input_shape)).shape
a2.filters
a2.kernel_size
model = tf.keras.Sequential()
model.add(a2)
model.output_shape
model.summary()
输出:
Out[100]: TensorShape([4, 10, 20, 10]) Out[100]: 10 Out[100]: (3, 3) Out[100]: (None, 10, 20, 10) Model: "sequential_25" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d_35 (Conv2D) (None, 10, 20, 10) 280 ================================================================= Total params: 280 Trainable params: 280 Non-trainable params: 0 _________________________________________________________________
正如我们所见,唯一的区别是 代码 1 使用 Conv2D(filters=10,kernel_size=(3,3),... 而 代码 2 使用 Conv2D(10,3,3,...。而且filters和kernel_size也是一样的。但是,output_shape 完全不同。
这是为什么?有人可以解释一下吗?我在 keras 官方文档 (https://www.tensorflow.org/api_docs/python/tf/keras/layers/Conv2D) 上找不到任何内容。
【问题讨论】:
标签: python tensorflow machine-learning keras conv-neural-network