簡體   English   中英

順序 model tensorflow 中的自定義層

[英]Custom layer in sequential model tensorflow

我正在嘗試為我的 model 創建一個自定義層,它可以用於 Keras 的經典密集層。 這是我的自定義層:

class MyDenseLayer(tf.keras.layers.Layer):
    def __init__(self, num_outputs):
        super(MyDenseLayer, self).__init__()
        self.num_outputs = num_outputs
    def build(self, input_shape):
        self.kernel = self.add_weight("kernel", 
                                      shape=[int(input_shape[-1]),
                                      self.num_outputs])
    def call(self, input):
        return tf.matmul(input, self.kernel)

它現在沒有做任何“自定義”。

但是當我將它添加到我的 model

def build_model():
    model = keras.Sequential([
        MyDenseLayer(10)(normed_x_train),
        layers.Activation(tf.nn.relu),
        layers.Dense(1, activation=tf.nn.relu)
        ])
    return model

我明白了:

The added layer must be an instance of class Layer. Found: tf.Tensor(
[....])

因為可能我正在直接創建 class 自定義層的 object。 但是我在 tf 文檔中沒有找到如何添加其他屬性以使其作為普通層工作,即像layers.Dense(100, activation=tf.nn.relu)這樣的東西

有沒有辦法讓它像那樣工作?

正如他們在評論中所說,在定義 model 時不要引入輸入。 那是:

def build_model():
    model = keras.Sequential([
        MyDenseLayer(10),
        keras.layers.Activation(tf.nn.relu),
        keras.layers.Dense(1, activation=tf.nn.relu)
        ])
    return model

然后你可以嘗試:

model = build_model()
model(tf.random.uniform((100, 100)))

PS:問題已經存在好幾天了,但是@Marco Cerliani 解決了這個問題(無論如何我都可以刪除它)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM