2016-12-17 63 views
7

我试图在CNTK中实现一个LSTM(使用Python)来对一个序列进行分类。CNTK在LSTM中抱怨动态轴

输入:

    号码
  • 特点是固定长度的序列(时间序列)

  • 标签是独热值的矢量

网络:

input = input_variable(input_dim) 
label = input_variable(num_output_classes) 
h = Recurrence(LSTM(lstm_dim)) (input) 
final_output = C.sequence.last(h) 
z = Dense(num_output_classes) (final_output) 
loss = C.cross_entropy_with_softmax(z, label) 

输出: 该序列的标签相匹配的概率

所有的大小是固定的,所以我不认为我需要任何动力轴并没有指定任何。

然而,CNTK不开心,我得到:

return cross_entropy_with_softmax(output_vector, target_vector, axis, name) 
RuntimeError: Currently if an operand of a elementwise operation has any dynamic axes, those must match the dynamic axes of the other operands 

如果(按照一些例子)我定义标签与动态轴

label = input_variable(num_output_classes, dynamic_axes=[C.Axis.default_batch_axis()]) 

它不再抱怨这个,并进一步获取到:

tf = np.split(training_features,num_minibatches) 
tl = np.split(training_labels, num_minibatches) 

for i in range(num_minibatches*num_passes): # multiply by the 
    features = np.ascontiguousarray(tf[i%num_minibatches]) 
    labels = np.ascontiguousarray(tl[i%num_minibatches]) 

    # Specify the mapping of input variables in the model to actual minibatch data to be trained with 
    trainer.train_minibatch({input : features, label : labels}) 

但与此错误死亡:

File "C:\Users\Dev\Anaconda3\envs\cntk-py34\lib\site-packages\cntk\cntk_py.py", line 1745, in train_minibatch 
    return _cntk_py.Trainer_train_minibatch(self, *args) 
RuntimeError: Node '__v2libuid__Plus561__v2libname__Plus552' (Plus operation): DataFor: FrameRange's dynamic axis is inconsistent with matrix: {numTimeSteps:1, numParallelSequences:100, sequences:[{seqId:0, s:0, begin:0, end:1}, {seqId:1, s:1, begin:0, end:1}, {seqId:2, s:2, begin:0, end:1}, {seqId:3, s:3, begin:0, end:1}, {seq... 

我需要做些什么来解决这个问题?

回答

8

如果我正确理解这个,你有一维输入序列。如果是这样,那么你的烦恼源于这条线

input = input_variable(input_dim) 

它声明一个input_dim维矢量序列。如果您将其更改为

input = input_variable(1) 

那么我相信您的初始尝试应该工作。

更新:上述方法本身并不够好,因为采用序列最后一个元素的操作会创建一个输出,其动态轴与创建标签的默认动态轴不同。一个简单的办法是定义你所定义的输出z这样

label = input_variable(num_output_classes, dynamic_axes=z.dynamic_axes) 

这工作没有任何抱怨,我以后的标签。然后,我给了一些像这样的虚拟数据(假设4的小批量序列长度为5和3类)

x = np.arange(20.0, dtype=np.float32).reshape(4,5,1) 
y = np.array([1,0,0,0,1,0,0,0,1,0,0,1], dtype=np.float32).reshape(4,1,3) 
loss.eval({input: x, label:y }) 

它按预期工作。

+0

我试过了,它仍然在抱怨 – Tiny

+0

RuntimeError:目前如果一个元素操作的操作数有任何动态轴,那些操作数必须与其他操作数的动态轴相匹配 – Tiny

+0

我已经在实际尝试之后更新了答案。 –