【发布时间】:2016-11-02 13:24:23
【问题描述】:
这个问题也作为一个问题存在:https://github.com/fchollet/keras/issues/4266
我正在尝试实现卷积 - LSTM。
它是一个循环层,它接受图像作为输入并使用卷积来计算 LSTM 中的各种门。
所以我试图继承Recurrent并改变输入维度。
为了做到这一点,我阅读了writing a custom layer 上的文档,并按照建议阅读源代码以了解幕后发生的事情。
我阅读了recurrent.py 的代码并认为结构很清楚:您从Recurrent 继承但您没有覆盖调用,而是提供了一个自定义stepfunction 和Recurrent将负责将步骤应用于序列中的每个条目。
作为起点,我采用了 GRU 的代码,并尝试使其适应我的需要。 我想结合 2D 卷积和 GRU(通常是 LSTM,但这并不重要——我决定实现 C-GRU)
我们的想法是在模型中使用通常的 2D 卷积,输出 3 个特征。这 3 个特征将用作 GRU 中的 r、z 和 h 激活。在自定义层中,我只需要跟踪状态。我的层甚至没有可训练的权重,它们包含在卷积中。
对原始 GRUcode 的显着更改是:
def step(self, x, states):
# the previous state is a 2D vector
h_tm1 = states[0] # previous memory
z=self.inner_activation(x[:,0,:,:])
r=self.inner_activation(x[:,1,:,:])
hh=self.activation(x[:,2,:,:])
h = z * h_tm1 + (1 - z) * hh
return h, [h]
如您所见,我只是重用了卷积中的特征。乘法应该按元素执行。我将对此进行调试以确保它具有预期的行为。
由于状态变为二维,我也在更改initial_state:
def get_initial_states(self, x):
initial_state=K.zeros_like(x) # (samples, timesteps, input_dim)
# input_dim = (3, x_dim, y_dim)
initial_state=K.sum(initial_state, axis=(1,2)) # (samples, x_dim, y_dim)
return initial_state
output_shape 似乎是为循环网络硬编码的。我正在覆盖它:
def get_output_shape_for(self, input_shape):
#TODO: this is hardcoding for th layout
return (input_shape[0],1,input_shape[2],input_shape[3])
另一个硬编码是input_spec。
在构造函数中,在调用 super 之后,我用我的输入维度覆盖它:
class CGRU(Recurrent):
def __init__(self,
init='glorot_uniform', inner_init='orthogonal',
activation='tanh', inner_activation='hard_sigmoid', **kwargs):
self.init = initializations.get(init)
self.inner_init = initializations.get(inner_init)
self.activation = activations.get(activation)
self.inner_activation = activations.get(inner_activation)
#removing the regularizers and the dropout
super(CGRU, self).__init__(**kwargs)
# this seems necessary in order to accept 5 input dimensions
# (samples, timesteps, features, x, y)
self.input_spec=[InputSpec(ndim=5)]
还有其他一些小的变化。 你可以在这里找到完整的代码:http://pastebin.com/60ztPis3
运行时,会产生以下错误消息:
theano.tensor.var.AsTensorError: ('Cannot convert [None] to TensorType', )
pastebin 上的完整错误信息:http://pastebin.com/Cdmr20Yn
我正在尝试调试代码。但这相当困难,它深入到 Keras 源代码中。
一件事:执行永远不会到达我的自定义stepfunction。所以显然配置中的某些东西出了问题。在Recurrent 的call 函数中,input_shape 是一个带有条目(None, 40,1,40,40) 的元组
这是正确的。我的序列有 40 个元素。每个都是具有 1 个特征和 40x40 分辨率的图像。我正在使用“th”布局。
这是Recurrent 的call 函数。
我的代码到达了对K.rnn 的调用,设置对我来说看起来不错。 Input_spec 似乎是正确的。
但是在K.rnn 期间它崩溃了。没有达到我的阶跃函数。
def call(self, x, mask=None):
# input shape: (nb_samples, time (padded with zeros), input_dim)
# note that the .build() method of subclasses MUST define
# self.input_spec with a complete input shape.
input_shape = self.input_spec[0].shape
if self.stateful:
initial_states = self.states
else:
initial_states = self.get_initial_states(x)
constants = self.get_constants(x)
preprocessed_input = self.preprocess_input(x)
last_output, outputs, states = K.rnn(self.step, preprocessed_input,
initial_states,
go_backwards=self.go_backwards,
mask=mask,
constants=constants,
unroll=self.unroll,
input_length=input_shape[1])
此时我迷路了。 在我看来,我缺少配置的某些部分。
更新:
嗯,现在我遇到了一个奇怪的问题: 我的代码现在是:
# this is the actual input, fed to the network
inputs = Input((1, 40, 40, 40))
# now reshape to a sequence
reshaped = Reshape((40, 1, 40, 40))(inputs)
conv_inputs = Input((1, 40, 40))
conv1 = Convolution2D(3, 3, 3, activation='relu', border_mode='same')(conv_inputs)
convmodel = Model(input=conv_inputs, output=conv1)
convmodel.summary()
#apply the segmentation to each layer
time_dist=TimeDistributed(convmodel)(reshaped)
from cgru import CGRU
up=CGRU(go_backwards=False, return_sequences=True, name="up")
up=up(time_dist)
output=Reshape([1,40,40,40])(up)
model=Model(input=inputs, output=output)
print(model.summary())
在以 Theano 为后端的计算机上,这是可行的。 模型总结为:
________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_1 (InputLayer) (None, 1, 40, 40, 40) 0
____________________________________________________________________________________________________
reshape_1 (Reshape) (None, 40, 1, 40, 40) 0 input_1[0][0]
____________________________________________________________________________________________________
timedistributed_1 (TimeDistribute(None, 40, 3, 40, 40) 30 reshape_1[0][0]
____________________________________________________________________________________________________
up (CGRU) (None, 40, 1, 40, 40) 0 timedistributed_1[0][0]
____________________________________________________________________________________________________
reshape_2 (Reshape) (None, 1, 40, 40, 40) 0 up[0][0]
====================================================================================================
Total params: 30
____________________________________________________________________________________________________
但是在以 tensorflow 作为后端的电脑上,代码失败了。
我为convmodel 添加了model.summary()。到目前为止,它的工作原理:
Layer (type) Output Shape Param # Connected to
====================================================================================================
input_4 (InputLayer) (None, 1, 40, 40) 0
____________________________________________________________________________________________________
convolution2d_2 (Convolution2D) (None, 3, 40, 40) 30 input_4[0][0]
====================================================================================================
Total params: 30
但随后程序崩溃:
ValueError:形状 (?, ?, 40, 40) 和 (40, ?, 40) 不兼容
似乎 Theano 和 Tensorflow 对 batch_size 有不同(且不兼容)的占位符? 请注意,我将 Keras 配置为在这两种情况下都使用“th”图像布局。
【问题讨论】:
标签: python machine-learning theano keras