python-2.7 - 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()
自定义优化器在这里:
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
解决方案
问题似乎是输入正在形成 [3,20],但在展平后应该是 [1000, 60]。
请检查输入的形状。你也可以使用
tf.expand_dims(
input,
axis,
name=None
)
为您的输入添加维度并尝试。它应该可以解决您的问题。
推荐阅读
- php - 使用wordpress在PHP中生成表格时出现问题
- c++ - MSHTML 编辑 - 更改文本选择颜色
- javascript - 304 并且在 Heroku 上部署的应用程序上没有 json 响应
- entity-framework - 从模型到数据库的路径是什么?
- javascript - 调整表格的列宽
- css - 绑定 Vuetify 数据表的样式,以便排序箭头始终与标题在同一行 - 不在?
- python - 有没有办法从 JSON 对象中删除图层?
- php - 在 Ubuntu 中使用 VSCode 和 PHP (7) 调试器
- jquery - jQuiery 多拖插件不适用于 jqv3
- scala - Spark SQL - 更新一列时选择所有列