【发布时间】:2019-03-13 11:56:19
【问题描述】:
我要连接model_1:
x_a = Input((5,))
hidden_a = Dense(2)(x_a)
hidden_b = Dense(2)(x_a)
model_1 = Model(x_a, [hidden_a, hidden_b])
和model_2:
x_b = Input((2,))
output = Dense(1)(x_b)
model_2 = Model(x_b, output)
我可以用下面这行来做到这一点:
model_3 = Model(x_a, model_2(model_1.outputs[0]))
但是我想定义任意数量的模型,所以我想使用函数来做到这一点。
有趣的是,当我尝试将每个模型嵌入到一个函数中时,如下所示:
def model1():
x_a = Input((5,))
hidden_a = Dense(2)(x_a)
hidden_b = Dense(2)(x_a)
model_1 = Model(x_a, [hidden_a, hidden_b])
return model_1
def model2():
x_b = Input((2,))
output = Dense(1)(x_b)
model_2 = Model(x_b, output)
return model_2
input_a = Input((5,))
m1 = model1()
m2 = model2()
m3 = Model(input_a, m2(m1.outputs[0]))
我收到一个错误:
ValueError: Graph disconnected: cannot obtain value for tensor Tensor("input_3:0", shape=(?, 5), dtype=float32) at layer "input_3". The following previous layers were accessed without issue: [].
基本上我想做和这篇文章一样的事情:Why when using this simple model with multiple outputs does Keras complain about a lack of gradients?
但有功能。
有没有办法使用函数来做我想要的,或者你认为使用自定义图层会更好吗? 谢谢。
【问题讨论】:
标签: python-3.x tensorflow keras keras-layer