2017-06-15 114 views
1

我创建了一个称为CustomFunc的自定义功能,说明这里下面:https://www.cntk.ai/pythondocs/extend.html如何编写自定义函数CNTK

如果我使用它的文章的建议,它的工作原理:

model = cntk.user_function(CustomFunc(prev_node)) 

这个作品很好,模型运行没有任何问题。我的问题是,我想在cntk.layers.Sequential调用中使用此函数,并在cntk.layers.Recurrence调用中使用此函数。要做到这一点,我需要以另一种方式构建函数的组合,然后将其放入Sequential或Recurrence调用中。现在我使用一些占位符,即我做的是:

customFunToUse = cntk.user_function(CustomFunc(cntk.placeholder(), otherInputs)) 
model = cntk.layers.Sequential([cntk.layers.Dense(100), 
           customFunToUse, 
           cntk.layers.Recurrence(
           customFunToUse >> cntk.layers.LSTM(100))]) 

但是,这并不工作,并提出了各种错误:有时它是一个段错误,在其他类似型号是

"ValueError: Cannot create an NDArrayView using a view shape '[? x 10]' that has unknown dimensions for any of its axes." 
而不是

其他时间是

Evaluate: All nodes inside a recurrent loop must have a layout that is identical; mismatch found for nodes ... 

还要注意的是我的自定义功能不改变输入尺寸:给予paramters的任何金额,它会返回相同的数量和类型。该代码是这样的:

class CustomFun(UserFunction): 
    def __init__(self, *args, otherStuff, name='CustomFun'): 
     super(CustomFun, self).__init__(list(args), name=name) 
     self.otherStuff = otherStuff 

    def forward(self, arguments, outputs=None, keep_for_backward=None, device=None, as_numpy=True): 
     return None,[x/2 for x in arguments] 

    def backward(self, state, root_gradients, variables=None, as_numpy=True): 
     #it's not important right now, just a test... 
     return root_gradient 

    def infer_outputs(self): 
     #shape, type and dynamic axes of inputs are not changed by this function 

     outputVar = [output_variable(self.inputs[idx].shape, self.inputs[idx].dtype, 
      self.inputs[idx].dynamic_axes, name='out_quantLayer') for idx in range(len(self.inputs))] 
     return outputVar 

    def serialize(self): 
     return {'otherStuff': self.otherStuff} 

    @staticmethod 
    def deserialize(inputs, name, state): 
     return CustomFun(inputs, otherStuff=state['otherStuff'], name=name) 

回答

1

正确的方法是写这样的 def my_layer(x): @C.Function def apply(x): return cntk.user_function(CustomFunc(x)) return apply 不幸的是这似乎导致我的Python解释器崩溃。我已经在此打开github issue 2132。问题得到解决后,将尝试更新此答案。

更新:有一个我们没有捕捉到的小错字。在github问题页面有一个解决方案。

相关问题