下面的示例适用于 2.2;K.function在 2.3 中发生了重大变化,现在Model在 Eager 执行中构建了一个,所以我们正在通过Model(inputs=[learning_phase,...]).
我确实有一个解决方法,但它很hackish,而且比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]))
Run Code Online (Sandbox Code Playgroud)
>>> ValueError: Input tensors to a Functional must come from `tf.keras.Input`.
Received: Tensor("keras_learning_phase:0", shape=(), …Run Code Online (Sandbox Code Playgroud)