【问题标题】:How to use custom Theano layers in Keras?如何在 Keras 中使用自定义 Theano 层?
【发布时间】:2017-10-30 15:04:02
【问题描述】:

我在 Theano 中定义了自定义层。我想在我的 Keras 模型中使用它们。我怎样才能做到这一点? Theano 中的这些层(定义为类)是否必须遵循某种格式?

我找不到任何资源。如果有人可以指导我,那将非常有帮助。

【问题讨论】:

    标签: tensorflow keras theano


    【解决方案1】:

    纯操作:

    如果这些层是纯操作,可以使用kerasLambda层。

    这个想法是创建一个接受一个张量(或张量列表)的函数,并在这个函数中执行所有操作:

    def customFunc(x):
    
        #tensor operations with the input tensor x   
        #you can use either keras.backend functions or theano functions    
        #paste the theano functions here
    
        #you can also attempt to call the theano layer here, passing x as input
    
        return result
    

    然后您从这个函数创建一个 Lambda 层:

    model.add(Lambda(customFunc, output_shape=someShape))
    

    具有可训练权重的层:

    但是,如果层具有可训练的权重,则必须创建一个 keras custom layer

    这是一个你在build方法中定义权重并在call方法中执行操作的类:

    class MyLayer(Layer):
    
        def __init__(self, yourOwnParameters, **kwargs):
            self.yourOwnParameters = yourOwnParameters
            super(MyLayer, self).__init__(**kwargs)
    
        def build(self, input_shape):
            # Create a trainable weight variable for this layer.
            self.kernel = self.add_weight(name='kernel', 
                                      shape=someKernelShape,
                                      initializer='uniform',
                                      trainable=True)
    
            #because of self.add_weight call:
            #I'm not sure if you can use the theano layer unchanged
    
            super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!
    
        def call(self, x):
    
            #paste the theano operations here
            return resultFromOperationsWith(x)
    
        def compute_output_shape(self, input_shape):
            return calculateSomeOutputShapeFromTheInputShape()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-12-07
      • 2015-09-15
      • 1970-01-01
      • 2020-03-27
      • 1970-01-01
      • 1970-01-01
      • 2016-02-25
      相关资源
      最近更新 更多