首页 > 解决方案 > Flatten 和 Dense 层之间的矩阵大小不兼容

问题描述

我正在尝试使用 Keras 实现多代理 A2C 算法。
使用 Keras 后端函数 (K.fction) 时出现问题。

我给出了形状为 (None, 3, 4, 5) 的输入。
此输入通过Flatten(),然后连接到Dense()

当我使用 时它工作正常model.predict(input),但是当我使用 K.function 使用自定义优化器时出现问题。

我在 K.function 中输入了形状为 (1000, 3, 4, 5)model.input的输入,但出现了 Matrix size-incompatible 错误:

tensorflow.python.framework.errors_impl.InvalidArgumentError: Matrix size-incompatible: In[0]: [3,20], In[1]: [60,64]
    [[{{node dense_1/Relu}}]]

它看起来Flatten()不能正常工作。

网络看起来像这样:

def build_network(self):
    inp = Input(shape=(3,4,5))
    x = Flatten()(inp)
    x = Dense(64, activation='relu')(x)
    x = Dense(128, activation='relu')(x)
    x = Dense(128, activation='relu')(x)
    out = Dense(9, activation='softmax')(x)

    return Model(inp, out)

self.model = self.build_network()

model.summary()

自定义优化器在这里:

import keras.backend as K

def optimizer(self):
    weighted_actions = K.sum(self.action_pl * self.model.ouput, axis=1)
    eligibility = K.log(weighted_actions + 1e-10) * K.stop_gradient(self.advantages_pl)
    entropy = K.sum(self.model.output * K.log(self.model.output + 1e-10), axis=1)
    loss = 0.001 * entropy - K.sum(eligibility)

    _out = K.zeros(shape=(1))
    updates = self.rms_optimizer.get_updates(self.model.trainable_weights, [], loss)

    return K.fucntion([self.model.input, self.action_pl, self.advantages_pl], _out, updates=updates)

self.opt = self.optimizer()

self.opt([input, actions, advantages]) # Error occured here. input.shape = (1000,3,4,5)

我不知道它为什么会发生以及如何解决这个问题。

任何建议将被认真考虑。

环境:Ubuntu16.04 Python2.7 Keras:2.3.0 tensorflow 1.14.0

标签: python-2.7tensorflowkeras

解决方案


问题似乎是输入正在形成 [3,20],但在展平后应该是 [1000, 60]。

请检查输入的形状。你也可以使用

tf.expand_dims(
    input,
    axis,
    name=None
)

为您的输入添加维度并尝试。它应该可以解决您的问题。


推荐阅读