tensorflow 用[X,1]除[X,10,10,1]矩阵

dfuffjeb  于 2023-02-05  发布在  其他
关注(0)|答案(1)|浏览(130)

我正尝试将一个[X,10,10,1]矩阵除以每个[10,10,1]矩阵的和-所以将[X,10,10,1]除以[X,1],但是使用tf.broadcast_to会产生一个“不兼容的形状”错误,如下所示:

t1 = tf.ones([128, 10, 10, 1]) 
t1_sum = tf.reduce_sum(t1, [1, 2])  # Yields a [128, 1]
t1_sum_reshaped = tf.broadcast_to(t1_sum, (t1.shape))
divided = tf.math.divide(t1, t1_sum_reshaped)

使用tf.broadcast_to时出现错误w/ X=128:不兼容的形状:[128,1]对[128,10,10,1] [操作员:广播至]
我让除法工作的变通方法如下所示,但它似乎非常慢(而且愚蠢)

t1 = tf.ones([128, 10, 10, 1])
t1_sum = tf.reduce_sum(t1, [1, 2])                                                                            # Yields a [128, 1]
t1_sum = tf.stack([t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum], axis=-2)  # Yields a [128, 10, 1]
t1_sum = tf.stack([t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum, t1_sum], axis=-2)  # Yields a [128, 10, 10, 1]
divided = tf.math.divide(t1, t1_sum)

有没有更好的办法?

u5rb5r59

u5rb5r591#

看起来你可以把keepdims=True参数添加到你的代码中,它会按预期工作:

t1 = tf.ones([128, 10, 10, 1])
t1_sum = tf.reduce_sum(t1, [1, 2], keepdims=True) # Yields a [128, 1, 1, 1]
t1_sum_reshaped = tf.broadcast_to(t1_sum, t1.shape)
divided = tf.math.divide(t1, t1_sum_reshaped)

完成此操作后,您可以删除线t1_sum_reshaped = tf.broadcast_to(t1_sum, t1.shape,因为它已经具有所需的形状。

t1 = tf.ones([128, 10, 10, 1])
t1_sum = tf.reduce_sum(t1, [1, 2], keepdims=True) # Yields a [128, 1, 1, 1]
divided = tf.math.divide(t1, t1_sum)

相关问题