我想为一个全连接层实现一个自定义的权重约束。
我的权重矩阵形状为(588,42)。我想做的操作是将矩阵的行数按84为一组进行划分,并为每组84行分配相同的权重。对于下一组84行,权重值高于第一组,依此类推。
假设我的每一组84行都有一个名为h_i的权重,其中i表示权重矩阵中的第i组。设想是h_1<=h_2<=…<=h_n。此外,我希望所有h的总和为1。
谢谢
回答:
我按照您的逻辑重新调整了权重(我使用的是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)
希望这对您有帮助