我有一个张量的shape=(?, 2)
和dtype=float32
。在实际操作中,这个形状是12000,2,但这个数值可能会变化。
tf.segment_mean
似乎能满足我的需求,将张量分割成12个部分,每部分1000个元素,然后计算平均值,最终生成一个形状为[12,2]
的张量。
不幸的是,为了使用segment_mean
,我需要提供segment_id
作为参数。由于元素数量是动态的,segment_ids
必须动态生成。
我尝试使用tf.scan
来生成segment_ids
,但没有成功。我的方向正确吗?还是有更好的方法来做这件事?
为了澄清:
import tensorflow as tf sess = tf.InteractiveSession() tens1 = tf.constant([ [0.1, 1], [0.2, 0], [0.3, 0], [0.4, 0], [0.5, 0], [0.6, 1], [0.7, 0], [0.7, 0], [0.8, 0], [0.9, 0], [0.7, 1], [0.8, 0], [0.7, 0], [0.8, 0], [0.7, 0], [0.8, 0], [0.9, 0], [0.7, 1], [0.8, 0], [0.7, 0], [0.8, 0], [0.9, 0], [0.7, 1], [0.8, 0], [0.97,0] ]) #seg_ids = tf.scan(lambda a, x: x % 12, tens1) # 这行代码是错误的 #希望能够从张量的大小动态推断出segment_ids seg_ids = [0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11] segmean = tf.segment_mean(tens1, seg_ids) print segmean.eval()
回答:
如果你的输入tensor_1
是12的倍数,你可以使用以下方法实现segment mean
:
tensor_2 = tf.reduce_mean(tf.reshape(tensor_1, shape=[12, -1, 2]), axis=1)
由于实际情况并非如此,我们可以将它填充到最接近的12的整数倍,然后应用上述方法。
sec_len = 12_shape = tf.shape(tensor_1)pad_size = tf.cast(tf.ceil(_shape[0] / sec_len)*sec_len, tf.int32) - _shape[0]zero_padding = tf.zeros((pad_size, _shape[1]), dtype=tensor_1.dtype)padded = tf.concat([tensor_1, zero_padding], 0)tensor_2 = tf.reduce_mean(tf.reshape(padded, shape=[sec_len, -1, 2]), axis=1)