如何解决Python Keras自编码器中"total size of new array must be unchanged"错误
错误原因
你遇到的维度不匹配错误,核心问题是解码器侧reshape2的输入输出元素总数没有对齐:
- 编码器侧经过两次卷积后,
encoded的特征shape为(None, 1, 1, n_filter*2),flatten后总元素数为n_filter*2 - 你之前参数正常是因为刚好满足
n_filter*2 = 32*2 = 64 = n_dense1,所以dense2输出的n_dense1长度刚好和reshape需要的元素数匹配 - 一旦修改
n_filter或n_dense1,两者数值不相等,reshape前后元素总数不一致,就会抛出该错误
修复方案
修改解码器侧dense2的输出维度,直接对齐编码器flatten后的总元素数即可,不需要和n_dense1绑定:
把原代码中解码器部分的
# Decoder dense2 = Dense(n_dense1, activation="selu", name="dense2")(output) dim_reconstruct = tuple(encoded.get_shape().as_list()) reshape2 = Reshape(dim_reconstruct[1:], name="reshape2")(dense2)
替换为:
# Decoder # 输出维度对齐encoder编码后的总元素数 dense2 = Dense(n_filter*2, activation="selu", name="dense2")(output) dim_reconstruct = tuple(encoded.get_shape().as_list()) reshape2 = Reshape(dim_reconstruct[1:], name="reshape2")(dense2)
如果需要保留dense2输出为n_dense1的结构,也可以在reshape前新增一层全连接层做维度过渡:
# Decoder dense2 = Dense(n_dense1, activation="selu", name="dense2")(output) # 新增过渡层对齐维度 transition = Dense(n_filter*2, activation="selu", name="transition")(dense2) dim_reconstruct = tuple(encoded.get_shape().as_list()) reshape2 = Reshape(dim_reconstruct[1:], name="reshape2")(transition)
修改后不管怎么调整n_filter和n_dense1的数值,都不会出现reshape维度不匹配的问题。
内容的提问来源于stack exchange,提问作者Elsa
相关产品推荐
相关产品推荐

