gpt4 book ai didi

machine-learning - 为什么当使用这个具有多个输出的简单模型时,Keras 会提示缺少梯度?

转载 作者:行者123 更新时间:2023-11-30 09:17:36 26 4
gpt4 key购买 nike

所以这个问题发生在一个更大的项目的上下文中,但我已经组装了一个最小的工作示例。考虑以下因素:

input_1 = Input((5,))
hidden_a = Dense(2)(input_1)
hidden_b = Dense(2)(input_1)

m1 = Model(input_1, [hidden_a, hidden_b])

input_2 = Input((2,))
output = Dense(1)(input_2)

m2 = Model(input_2, output)

m3 = Model(input_1, m2(m1(input_1)[0]))

print(m3.summary())

m3.compile(optimizer='adam', loss='mse')

x = np.random.random(size=(10,5))
y = np.random.random(size=(10,1))

m3.fit(x,y)

我的期望是,在评估该网络时,hidden_​​b 的输出将被简单地丢弃,并且我将有效地拥有一个简单的前馈神经网络,该网络的作用是 input_1 ->hidden_​​a -> 输入_2 -> 输出。相反,我收到了一个神秘的错误:

Traceback (most recent call last):
File "test.py", line 37, in <module>
m3.fit(x,y)
File "/home/thomas/.local/lib/python3.5/site-packages/keras/engine/training.py", line 1013, in fit
self._make_train_function()
File "/home/thomas/.local/lib/python3.5/site-packages/keras/engine/training.py", line 497, in _make_train_function
loss=self.total_loss)
File "/home/thomas/.local/lib/python3.5/site-packages/keras/legacy/interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "/home/thomas/.local/lib/python3.5/site-packages/keras/optimizers.py", line 445, in get_updates
grads = self.get_gradients(loss, params)
File "/home/thomas/.local/lib/python3.5/site-packages/keras/optimizers.py", line 80, in get_gradients
raise ValueError('An operation has `None` for gradient. '
ValueError: An operation has `None` for gradient. Please make sure that all of your ops have a gradient defined (i.e. are differentiable). Common ops without gradient: K.argmax, K.round, K.eval.

知道是什么原因造成的吗?谢谢!

更新:如果将 input_1 传递给 m1 是问题所在,那么为什么会这样?

input_1 = Input((5,))
hidden_a = Dense(2)(input_1)
hidden_b = Dense(2)(input_1)

def sampling (args):
hidden_a, hidden_b = args
return hidden_a + hidden_b

z = Lambda(sampling)([hidden_a, hidden_b])

m1 = Model(input_1, [hidden_a, hidden_b, z])

input_2 = Input((2,))
output = Dense(1)(input_2)

m2 = Model(input_2, output)

m3 = Model(input_1, m2(m1(input_1)[2]))

m3.compile(optimizer='adam', loss='mse')

x = np.random.random(size=(10,5))
y = np.random.random(size=(10,1))

m3.fit(x,y)

最佳答案

您向模型 1 传递的输入已经是模型 1 的输入。

m3 = Model(input_1, m2(m1.outputs[0]))

关于machine-learning - 为什么当使用这个具有多个输出的简单模型时,Keras 会提示缺少梯度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51215838/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com