
这是在两个张量之间实现加权平均的一种可能性,其中权重可以自动获知。我还介绍了权重必须合计为1的约束。要实现这一点,我们必须简单地对权重应用softmax。在下面的虚拟示例中,我将此方法结合使用了两个完全连接的分支的输出,但是您可以在所有其他情况下进行管理
这里是自定义层:
class WeightedAverage(Layer): def __init__(self, n_output): super(WeightedAverage, self).__init__() self.W = tf.Variable(initial_value=tf.random.uniform(shape=[1,1,n_output], minval=0, maxval=1), trainable=True) # (1,1,n_inputs) def call(self, inputs): # inputs is a list of tensor of shape [(n_batch, n_feat), ..., (n_batch, n_feat)] # expand last dim of each input passed [(n_batch, n_feat, 1), ..., (n_batch, n_feat, 1)] inputs = [tf.expand_dims(i, -1) for i in inputs] inputs = Concatenate(axis=-1)(inputs) # (n_batch, n_feat, n_inputs) weights = tf.nn.softmax(self.W, axis=-1) # (1,1,n_inputs) # weights sum up to one on last dim return tf.reduce_sum(weights*inputs, axis=-1) # (n_batch, n_feat)
这里是回归问题的完整示例:
inp1 = Input((100,))inp2 = Input((100,))x1 = Dense(32, activation='relu')(inp1)x2 = Dense(32, activation='relu')(inp2)x = [x1,x2]W_Avg = WeightedAverage(n_output=len(x))(x)out = Dense(1)(W_Avg)m = Model([inp1,inp2], out)m.compile('adam','mse')n_sample = 1000X1 = np.random.uniform(0,1, (n_sample,100))X2 = np.random.uniform(0,1, (n_sample,100))y = np.random.uniform(0,1, (n_sample,1))m.fit([X1,X2], y, epochs=10)最后,您还可以通过以下方式可视化权重的值:
tf.nn.softmax(m.get_weights()[-3]).numpy()
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)