溫馨提示×

Keras中如何定義一個自定義的層

小樊
134
2024-03-14 10:54:29
欄目: 深度學習

要定義一個自定義的層,需要繼承keras.layers.Layer類,并重寫__init__call方法。下面是一個簡單的示例:

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import Layer

class MyCustomLayer(Layer):
    def __init__(self, output_dim, activation=None, **kwargs):
        self.output_dim = output_dim
        self.activation = keras.activations.get(activation)
        super(MyCustomLayer, self).__init__(**kwargs)

    def build(self, input_shape):
        self.kernel = self.add_weight(name='kernel', 
                                      shape=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        super(MyCustomLayer, self).build(input_shape)

    def call(self, inputs):
        output = tf.matmul(inputs, self.kernel)
        if self.activation is not None:
            output = self.activation(output)
        return output

    def compute_output_shape(self, input_shape):
        return (input_shape[0], self.output_dim)

在這個示例中,我們定義了一個自定義的層MyCustomLayer,它具有一個可調節的輸出維度和激活函數。在__init__方法中設置了輸出維度和激活函數,并在build方法中創建了權重矩陣。在call方法中實現了層的前向傳播邏輯,并在最后返回輸出。最后,compute_output_shape方法用于計算輸出的形狀。

定義好自定義的層后,可以像使用其他內置的層一樣將其添加到模型中進行訓練。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女