简体   繁体   English

tf.keras 输入层仅用于推理期间

[英]tf.keras input layer only for use during inference

I'd like to create an auxiliary input layer that I use solely during inference time, but can't figure out how to do it.我想创建一个仅在推理期间使用的辅助输入层,但不知道该怎么做。 I'd like to do something like the following:我想做类似以下的事情:

inputs = tf.keras.Input(shape=(784,))

x = tf.keras.layers.Dense(64, activation='relu')(inputs)
x = tf.keras.layers.InputLayer((64,), name='input_foo')(x)
predictions = tf.keras.layers.Dense(64, activation='relu')(x)

model = tf.keras.Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
model.fit(data, labels)  # starts training
model.save('foo.h5')

model = tf.keras.models.load_model('foo.h5')
inference_model = tf.keras.Model(model.get_layer('input_2'), model.output)

However, I get the following error upon loading:但是,我在加载时收到以下错误:

ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_foo_2:0", shape=(None, 64), dtype=float32) at layer "input_foo". The following previous layers were accessed without issue: []

Just create a new model with input2 and output and load the weights from the trained model.只需使用 input2 和 output 创建一个新的 model 并从经过训练的 model 加载权重。 or try to write a subclassing model by utilizing the training parameter in the call method as below.或尝试使用调用方法中的训练参数编写子类 model,如下所示。

def customModel(tf.kears.models.Model):
    def call(inputs, training=True):
        if training == True:
            #do your model for training
        else:
            #do your model for inference 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 输入到tf.keras的Conv2D层的大小不正确 - Input to tf.keras Conv2D layer not of appropriate size 尝试使用先前训练的 tf.keras 模型作为预训练,但出现“ValueError:dense_3 层的输入 0 与层不兼容 - Trying to use previously trained tf.keras model as pretraining, but getting "ValueError: Input 0 of layer dense_3 is incompatible with the laye 在GPU上训练RNN-我应该使用哪个tf.keras层? - Training RNN on GPU - which tf.keras layer should I use? 将tf.Keras与Tensorflow优化器一起使用 - Use tf.Keras with Tensorflow optimizer Keras model 在训练期间有 2 个输入,但在推理期间只有 1 个输入 - Keras model with 2 inputs during training, but only 1 input during inference 在推理期间从自定义 Tensorflow/Keras 层中提取中间变量 (TF 2.0) - Extract intermmediate variable from a custom Tensorflow/Keras layer during inference (TF 2.0) 手动将 pytorch 权重转换为卷积层的 tf.keras 权重 - Manualy convert pytorch weights to tf.keras weights for convolutional layer 关于 tf.keras 自定义层中 boolean 列表的问题 - a question about boolean list in custom layer in tf.keras 有没有办法加快 tf.keras 中的嵌入层? - Is there a way to speed up Embedding layer in tf.keras? tf.keras 在训练期间获得计算梯度 - tf.keras get computed gradient during training
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM