是否可以通过Model.build()完全控制模型的构建?

时间:2019-02-13 16:25:30

标签: tensorflow keras

当我让模型“自行构建”时,得到的结果与当 呼叫Model.build()

在下面的代码中,似乎在调用:

Model.build (<input_shape>)

没有充分利用input_shape

在此示例中,model_input_shapemodel_build不是 一模一样。特别地,model_build的层不 即使已传递input_shape,也知道其input_shapebuild()

代码如下:

import tensorflow as tf

print (tf.VERSION)

model_input_shape = tf.keras.models.Sequential([
  tf.keras.layers.Dense(64, input_shape = (8, ), activation=tf.nn.relu),
])
model_input_shape.summary()
model_input_shape.weights
model_input_shape.layers[0].input_shape

model_build = tf.keras.models.Sequential([
  tf.keras.layers.Dense(64, activation=tf.nn.relu),
])
model_build.build((None, 8))
model_build.summary()
model_build.weights
model_build.layers[0].input_shape

这是运行该代码的结果:

>>> import tensorflow as tf
>>>
>>> print (tf.VERSION)
1.12.0
>>>
>>> model_input_shape = tf.keras.models.Sequential([
...   tf.keras.layers.Dense(64, input_shape = (8, ), activation=tf.nn.relu),
... ])
>>> model_input_shape.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense (Dense)                (None, 64)                576
=================================================================
Total params: 576
Trainable params: 576
Non-trainable params: 0
_________________________________________________________________
>>> model_input_shape.weights
[<tf.Variable 'dense/kernel:0' shape=(8, 64) dtype=float32>, <tf.Variable 'dense/bias:0' shape=(64,) dtype=float32>]
>>> model_input_shape.layers[0].input_shape
(None, 8)
>>>
>>> model_build = tf.keras.models.Sequential([
...   tf.keras.layers.Dense(64, activation=tf.nn.relu),
... ])
>>> model_build.build((None, 8))
>>> model_build.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
dense_1 (Dense)              multiple                  576
=================================================================
Total params: 576
Trainable params: 576
Non-trainable params: 0
_________________________________________________________________
>>> model_build.weights
[<tf.Variable 'dense_1/kernel:0' shape=(8, 64) dtype=float32>, <tf.Variable 'dense_1/bias:0' shape=(64,) dtype=float32>]

>>> model_build.layers[0].input_shape
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\IBM_ADMIN\Documents\wnn\python_3_7_2\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 1338, in input_shape
    raise AttributeError('The layer has never been called '
AttributeError: The layer has never been called and thus has no defined input shape.
>>>

Model.build()实际做什么(而不是做什么)?是否有可能 使用Model.build()建立模型的方式与建立模型相同 “自己建造?”

0 个答案:

没有答案