【问题标题】:In Keras, how to apply softmax function on each row of the weight matrix?在 Keras 中,如何对权重矩阵的每一行应用 softmax 函数?
【发布时间】:2019-04-15 20:10:33
【问题描述】:
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 的输入,那么输出将是:

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

我该怎么做?

【问题讨论】:

  • 您的意思是您希望将 softmax 应用于 Dense 层的权重而不是其输出,对吧?
  • @today 是的,完全正确。

标签: python machine-learning keras keras-layer softmax


【解决方案1】:

实现您所寻找的一种方法是通过子类化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

测试以确保它有效:

model = Sequential()
model.add(CustomDense(2, use_bias=False, input_shape=(3,)))

model.compile(loss='mse', optimizer='adam')

import numpy as np

w = np.array([[2,3], [3,1], [1,-1]])
inp = np.array([[2,1,3]])

model.layers[0].set_weights([w])
print(model.predict(inp))

# output
[[4.0610714 1.9389288]]

使用 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]]

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 2018-07-04
    • 1970-01-01
    • 2011-01-19
    • 2013-02-23
    • 1970-01-01
    • 2020-05-05
    相关资源
    最近更新 更多