Когда я позволяю модели "строить себя", я получаю другой результат, чем при вызове Model.build()
.
В приведенном ниже коде кажется, что вызов:
Model.build (<input_shape>)
не в полной мере использует input_shape
.
В этом примере model_input_shape
и model_build
не совсем совпадают.В частности, слой model_build
не знает своего input_shape
, хотя input_shape
был передан build()
.
Вот код:
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()
для построения модели так же, как позволить модели «построить себя»?