Recurrentshop 和 Keras:多维 RNN 导致维度不匹配错误

Posted

技术标签:

【中文标题】Recurrentshop 和 Keras:多维 RNN 导致维度不匹配错误【英文标题】:Recurrentshop and Keras: multi-dimensional RNN results in a dimensions mismatch error 【发布时间】:2018-06-17 17:04:00 【问题描述】:

我对 Recurrentshop 和 Keras 有疑问。我正在尝试在循环模型中使用串联和多维张量,无论我如何安排输入、形状和批处理形状,都会遇到维度问题。

最少的代码:

from keras.layers import *
from keras.models import *
from recurrentshop import *
from keras.layers import Concatenate

input_shape=(128,128,3)

x_t = Input(shape=(128,128,3,))
h_tm1 = Input(shape=(128,128,3, ))

h_t1 = Concatenate()([x_t, h_tm1])
last = Conv2D(3, kernel_size=(3,3), strides=(1,1), padding='same',     name='conv2')(h_t1)

# Build the RNN
rnn = RecurrentModel(input=x_t, initial_states=[h_tm1], output=last,     final_states=[last], state_initializer=['zeros'])

x = Input(shape=(128,128,3, ))
y = rnn(x)

model = Model(x, y)

model.predict(np.random.random((1, 128, 128, 3)))

错误代码:

ValueError: Shape must be rank 3 but it is rank 4 for 'recurrent_model_1/concatenate_1/concat' (op:ConcatV2) with input shapes: [?,128,3], [?,128,128,3], [].

请帮忙。

【问题讨论】:

【参考方案1】:

试试这个(更改的行已注释):

from recurrentshop import *
from keras.layers import Concatenate

x_t = Input(shape=(128, 128, 3,))
h_tm1 = Input(shape=(128, 128, 3,))

h_t1 = Concatenate()([x_t, h_tm1])
last = Conv2D(3, kernel_size=(3, 3), strides=(1, 1), padding='same', name='conv2')(h_t1)

rnn = RecurrentModel(input=x_t,
                     initial_states=[h_tm1],
                     output=last,
                     final_states=[last],
                     state_initializer=['zeros'])

x = Input(shape=(1, 128, 128, 3,))  # a series of 3D tensors -> 4D
y = rnn(x)

model = Model(x, y)
model.predict(np.random.random((1, 1, 128, 128, 3)))  # a batch of x -> 5D

【讨论】:

以上是关于Recurrentshop 和 Keras:多维 RNN 导致维度不匹配错误的主要内容,如果未能解决你的问题,请参考以下文章

Keras LSTM 多维输入

Keras LSTM实现多维输入输出时序预测实践详解

Keras:循环网络的正确数据格式是啥?

keras---cnn---rnn---lstm

Mac下Theano, Keras, Tensorflow等机器学习包的安装介绍 总252期-量化试验071

如何在 Keras 中生成 class_labels.txt 以在 CoreML 模型中使用?