【问题标题】:Writing a Keras layer that literally just outputs a trainable parameter编写一个仅输出可训练参数的 Keras 层
【发布时间】:2019-09-06 21:42:14
【问题描述】:

我正在尝试编写一个基本上只是普通前馈层(激活(Wx + b))的层。唯一的新颖之处是我希望该层包含一个一维参数向量(输出维度的大小),并且在调用时只需输出该一维向量而不是实际计算激活值(Wx + 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)

【问题讨论】:

    标签: python tensorflow keras keras-layer


    【解决方案1】:

    MyLayer 类有 __init__ 寻找维度。但是您发送的是tesnor。将tesnor 维度提取到self.output_dim

    【讨论】:

    • 我不明白你的意思。
    猜你喜欢
    • 1970-01-01
    • 2019-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2019-12-25
    • 1970-01-01
    相关资源
    最近更新 更多