【发布时间】:2020-11-24 00:54:03
【问题描述】:
以下示例适用于 2.2; K.function 在 2.3 中发生了显着变化,now building 在 Eager 执行中变为 Model,因此我们传递了 Model(inputs=[learning_phase,...])。
我确实有一个解决方法,但它很老套,而且比K.function 复杂得多;如果没有人可以展示一个简单的方法,我会发布我的。
from tensorflow.keras.layers import Input, Dense
from tensorflow.keras.models import Model
from tensorflow.python.keras import backend as K
import numpy as np
ipt = Input((16,))
x = Dense(16)(ipt)
out = Dense(16)(x)
model = Model(ipt, out)
model.compile('sgd', 'mse')
outs_fn = K.function([model.input, K.symbolic_learning_phase()],
[model.layers[1].output]) # error
x = np.random.randn(32, 16)
print(outs_fn([x, True]))
>>> ValueError: Input tensors to a Functional must come from `tf.keras.Input`.
Received: Tensor("keras_learning_phase:0", shape=(), dtype=bool)
(missing previous layer metadata).
【问题讨论】:
-
这是否适用于您的用例:
K.function([symbolic_inputs], [symbolic_outputs])([input_arrays], training=True)? -
我误解了最近的变化。实际上,
K.function不会返回Model实例(尽管它会构建并运行Model实例)。但是对于您在问题中的用例,为什么不这样做:partial_model = Model(model.inputs, model.layers[1].output)然后使用partial_model([x], training=True)在训练模式下运行它。如果您有其他特殊用例,请将其包含在问题中。
标签: python tensorflow keras tf.keras tensorflow2.x