簡體   English   中英

編寫一個Keras層,實際上只輸出一個可訓練的參數

[英]Writing a Keras layer that literally just outputs a trainable parameter

我正在嘗試編寫一個基本上只是普通前饋層的圖層(激活(W x + b))。 唯一的新穎之處在於我希望圖層包含一維參數向量(輸出維度的大小),並且在調用時,只需輸出一維向量而不是實際計算激活(W x + b)。 矢量應該是可訓練的。

這是我提出的代碼:

from keras import backend as K
from keras.layers import Layer
import keras

class MyLayer(Layer):

    def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
        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=(input_shape[1], self.output_dim),
                                      initializer='uniform',
                                      trainable=True)
        self.out_estimate = self.add_weight(name='out_estimate',
                                              shape=(self.output_dim,),
                                              initializer='uniform',
                                              trainable=True)
        super(MyLayer, self).build(input_shape)  # Be sure to call this at the end

    def call(self, x):
        return self.out_estimate

    def compute_output_shape(self, input_shape):
        return (self.output_dim,)
from keras.models import  Model
from keras import layers
from keras import Input

input_tensor = layers.Input(shape=(784,))
output_tensor = MyLayer(10)(input_tensor)

model = Model(input_tensor, output_tensor)
model.summary()
model.compile(optimizer='rmsprop', loss='categorical_crossentropy')
model.fit(train_images, train_labels, epochs=1, batch_size=128)

這是輸出:

ValueError:檢查目標時出錯:預期my_layer_69有1個維度,但得到的是帶有形狀的數組(60000,10)

MyLayer類有__init__查找維度。 但是你正在發送一個tesnor tesnor維度解壓縮為self.output_dim

暫無
暫無

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

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