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

标签 machine-learning keras artificial-intelligence

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

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/

相关文章:

algorithm - 国际象棋 AI 如何确定任何一位棋手是否可以平局?

statistics - 代表分类置信度

python - 以 3D 张量时间序列作为输入的二元分类 Keras 神经网络模型

python - 如何判断哪个 Keras 模型更好?

Keras模型.编译: metrics to be evaluated by the model

python - 在tensorflow代码中使用keras层

machine-learning - 不同分辨率的迁移学习深度CNN

data-structures - KD树的实现

python - “顺序”对象没有属性 'loss' - 当我使用 GridSearchCV 调整我的 Keras 模型时

artificial-intelligence - 我应该使用哪种语言?