Ove*_*gon 2 python keras tensorflow tf.keras tensorflow2.x
下面的示例适用于 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=(), dtype=bool)
(missing previous layer metadata).
Run Code Online (Sandbox Code Playgroud)
为了以 Eager 模式获取中间层的输出,没有必要构建K.function和使用学习阶段。相反,我们可以构建一个模型来实现这一目标:
partial_model = Model(model.inputs, model.layers[1].output)
x = np.random.rand(...)
output_train = partial_model([x], training=True) # runs the model in training mode
output_test = partial_model([x], training=False) # runs the model in test mode
Run Code Online (Sandbox Code Playgroud)
或者,如果您坚持使用K.function并希望在 Eager 模式下切换学习阶段,则可以使用eager_learning_phase_scopefrom tensorflow.python.keras.backend(请注意,此模块是 的超集tensorflow.keras.backend并包含内部函数,例如前面提到的函数,在未来版本中可能会更改):
from tensorflow.python.keras.backend import eager_learning_phase_scope
fn = K.function([model.input], [model.layers[1].output])
# run in test mode, i.e. 0 means test
with eager_learning_phase_scope(value=0):
output_test = fn([x])
# run in training mode, i.e. 1 means training
with eager_learning_phase_scope(value=1):
output_train = fn([x])
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3663 次 |
| 最近记录: |