keras中自定義層非常普遍。對於簡單,無狀態的自定義操作,可以通過 layers.core.lambda層來實現。對於包含了可訓練權重的自定義層,就需要自己手動去實現。
需要實現三個方法:
build(input_shape): 定義權重,這個方法必須設 self.built = true,可以通過呼叫 super([layer],self).build( ) 完成。
call( x ):寫層的功能邏輯。只需要關注傳入 call 的第乙個引數:輸入張量,除非你希望層支援 masking。
compute_output_shape(input_shape):如果層改變了輸入張量的形狀,應該在這裡定義形狀改變的邏輯,讓keras能夠自動推斷各層的形狀。
# coding=utf-8
from keras import backend as k
from keras.engine.topology import layer
import numpy as np
class mylayer(layer):
def __init__(self, output_dim, **kwargs):
self.output_dim = output_dim
super(mylayer, self).__init__(**kwargs)
def build(self, input_shape):
self.kernel = self.add_weight(shape=(input_shape[1], self.output_dim),
initializer='uniform', trainable=true,
name='kernel')
super(mylayer, self).build(input_shape)
def call(self, x):
return k.dot(x, self.kernel)
def compute_output_shape(self, input_shape):
return (input_shape[0], self.output_dim)
Keras 自定義層
keras自定義或者重寫層,需要實現三個方法 問題 參考 keras 自定義層 最後舉乙個conditional layer normalization的例子 基於conditional layer normalization的條件文字生成 自定義層需要實現三個方法 class layernorma...
keras自定義層
keras學習筆記 二 keras實現自定義層 例1,參考博文1中的自定義層attentiondecoder。def build self,input shape for model details that correspond to the matrices here.self.batch si...
Keras函式式API與自定義層
函式式api從乙個例子開始from keras.layers import x input shape 10,y dense 10 x 正常情況下怎麼使用類例項 可能你對上面的例子感到習以為常,但是看看正常情況下是怎樣使用類的 class a object def init self,var sel...