Keras中的自定义内核约束

问题描述 投票:0回答:2

我想为密集层实现自定义权重约束。

我的体重矩阵的形状为(588,42)。我想做的是将行数分成84组,并为矩阵中的每84行分配相同的权重。下一组84个相同,但其中的值比第一组高,等等

因此,假设我所有的84组都用名为h_i的权重加权,即i在权重矩阵上的第i个集。这个想法是h_1 <= h_2 <= ... <= h_n。此外,我希望所有h的总和为1。

谢谢

keras customization
2个回答
0
投票

定义体重:

matrix_shape = (588,42)
rep = matrix_shape[0]/84

w = np.arange(1,rep+1)/np.arange(1,rep+1).sum()
W = np.repeat(w, 84).reshape(-1,1)*np.ones(matrix_shape)

定义一个虚拟模型:

inp = Input(shape=(100))
x = Dense(588)(inp)
out = Dense(42)(x)

model = Model(inp, out)
model.compile('adam', 'mse')

在模型中设置新的权重:

model.layers[-1].set_weights([W, np.zeros(42)])

0
投票

我按照您的逻辑重新调整权重(我使用TF 2.2)

class custom(tf.keras.constraints.Constraint):

    def __init__(self, length):
        self.length = length

    def __call__(self, W):
        w_shape = W.shape
        rep = w_shape[0]/self.length
        w = (np.arange(1,rep+1)/np.arange(1,rep+1).sum()).astype('float32')
        w = tf.reshape(tf.repeat(tf.constant(w), self.length*w_shape[1]), [w_shape[0],w_shape[1]])

        return w*W

定义模型

inp = Input(shape=(100))
x = Dense(588)(inp)
out = Dense(42, kernel_constraint=custom(84))(x)

model = Model(inp, out)
model.compile('adam', 'mse')

虚拟火车

model.fit(np.random.normal(0,1, (10, 100)), np.random.normal(0,1, (10, 42)), epochs=10)

我希望这个帮助

© www.soinside.com 2019 - 2024. All rights reserved.