在Keras中,如何对权重矩阵的每一行应用softmax函数?

2024-04-19 19:27:20 发布

您现在位置:Python中文网/ 问答频道 /正文

from keras.models import Model
from keras.models import Input
from keras.layers import Dense

a = Input(shape=(3,))
b = Dense(2, use_bias=False)(a)
model = Model(inputs=a, outputs=b)

假设上面代码中Dense层的权重是[[2, 3], [3, 1], [-1, 1]]。如果我们给[[2, 1, 3]]作为model的输入,那么输出将是:

no softmax

但是我想将softmax函数应用到Dense层的每一行,这样输出将是:

with softmax

我该怎么做?在


Tags: fromimportfalseinputmodelusemodelslayers
1条回答
网友
1楼 · 发布于 2024-04-19 19:27:20

实现所需内容的一种方法是通过子类化Dense层并重写其call方法来定义自定义层:

from keras import backend as K

class CustomDense(Dense):
    def __init__(self, units, **kwargs):
        super(CustomDense, self).__init__(units, **kwargs)

    def call(self, inputs):
        output = K.dot(inputs, K.softmax(self.kernel, axis=-1))
        if self.use_bias:
            output = K.bias_add(output, self.bias, data_format='channels_last')
        if self.activation is not None:
            output = self.activation(output)
        return output

测试以确保其工作正常:

^{pr2}$

使用numpy验证它:

soft_w = np.exp(w) / np.sum(np.exp(w), axis=-1, keepdims=True)
print(np.dot(inp, soft_w))

[[4.06107115 1.93892885]]

相关问题 更多 >