假设我有一个列为N + 1张量的列N张量的列表。例如,列表为100个10x20矩阵,其形状为(100,10,20)的3级张量。我需要对每个矩阵执行相同的操作:将每个矩阵的所有元素,第i个矩阵的值的均值和中值求和。
是否可以沿轴0做tf.math.reduce_sum
,tf.math.reduce_mean
,tf.contrib.distributions.percentile
之类的事情,但同时为沿0轴的每个元素一次计算整个矩阵?
E.G .:
matricesList = tf.constant([[[1,1],[1,1]],
[[2,2],[2,2]]])
op = sum_matrices_along_axis(matrixList)
预期为op = [4,8]
答案 0 :(得分:1)
您可以将多个尺寸传递给归约运算的axis
参数:
import tensorflow as tf
matricesList = tf.constant([[[1, 1], [1, 1]],
[[2, 2], [2, 2]]])
matricesSum = tf.reduce_sum(matricesList, axis=[1, 2])
with tf.Session() as sess:
print(sess.run(matricesSum))
# [4 8]
即使您事先不知道尺寸数,也可以减少“除第一个尺寸外的所有尺寸”:
import tensorflow as tf
# The number of dimensions of tensorsList is unspecified
tensorsList = tf.placeholder(tf.int32)
# Dimensions from one to the last one
reduceDims = tf.range(1, tf.rank(tensorsList))
tensorsSum = tf.reduce_sum(tensorsList, axis=reduceDims)
with tf.Session() as sess:
matrices = [[[1, 1], [1, 1]],
[[2, 2], [2, 2]]]
print(sess.run(tensorsSum, feed_dict={tensorsList: matrices}))
# [4 8]