[英]Force a model to return a single output as a list of one element
According to https://keras.io/models/model/ , when a model returns a multiple output, it is represented as a list of outputs. 根据https://keras.io/models/model/ ,当模型返回多个输出时,它将表示为输出列表。
It is possible to force the model to return a list even with a single output? 是否可以强制模型即使有单个输出也返回列表? By default when building the model, if there is only one output, it is returned 默认情况下,构建模型时,如果只有一个输出,则将其返回
I am doing a generic utility and this inconsistency in the keras API (returning two output types) does not seem very elegant. 我正在做一个通用的实用程序,并且keras API中的这种不一致(返回两个输出类型)似乎不是很优雅。 I don't know what will the input be so I always assume multiple inputs/outputs. 我不知道输入是什么,所以我总是假设多个输入/输出。
Is it possible to return a list of one output? 是否可以返回一个输出列表? How can I overcome this limitation? 如何克服此限制?
import tensorflow as tf
import numpy as np
def get_model1():
in_layer = tf.keras.Input(
name='IN',
shape=(10),
dtype=tf.float32
)
out_layer = tf.keras.layers.Dense(
name="OUT",
units=1,
activation=tf.keras.activations.sigmoid
)(in_layer)
return tf.keras.Model(
name='Model_1',
inputs=[in_layer],
outputs=[out_layer]
)
def get_model2():
in_layer1 = tf.keras.Input(
name='IN1',
shape=(10),
dtype=tf.float32
)
in_layer2 = tf.keras.Input(
name='IN2',
shape=(10),
dtype=tf.float32
)
out_layer1 = tf.keras.layers.Dense(
name="OUT1",
units=1,
activation=tf.keras.activations.sigmoid
)(in_layer1)
out_layer2 = tf.keras.layers.Dense(
name="OUT2",
units=1,
activation=tf.keras.activations.sigmoid
)(in_layer2)
return tf.keras.Model(
name='Model_1',
inputs=[in_layer1,in_layer2],
outputs=[out_layer1, out_layer2]
)
m1 = get_model1()
m2 = get_model2()
print(m1.input_shape)
print(m2.input_shape)
print(m1.output_shape)
print(m2.output_shape)
This is the result. 这就是结果。
(None, 10)
[(None, 10), (None, 10)]
(None, 1)
[(None, 1), (None, 1)]
What I expect is the first model to have a list as an input and as an output, the same behavior as the second model but with one element. 我期望的是第一个模型将列表作为输入和输出,其行为与第二个模型相同,但具有一个元素。
At the end I have used the keras internal function to_list
最后,我使用了keras内部函数to_list
from tensorflow.python.keras.utils.generic_utils import to_list
to_list(model.predict(x))
This way I unify the expected output of my model by returning always a list and delegating the checks in the library that generates the inconsistency. 这样,我通过始终返回一个列表并委托产生不一致的库中的检查来统一模型的预期输出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.