栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

加权平均值:TensorFlow 2.2.0中的自定义图层权重不变

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

加权平均值:TensorFlow 2.2.0中的自定义图层权重不变

这是在两个张量之间实现加权平均的一种可能性,其中权重可以自动获知。我还介绍了权重必须合计为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()


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645902.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号