当尺寸不匹配时,如何在张量流中压缩张量

时间:2018-05-19 08:02:06

标签: python tensorflow

我有两个张量,一个是形状[无,20,2],另一个是形状[无,1]。 我想以锁步方式对每个子张量进行操作,以产生一个值,这样我最终会得到一个形状的张量[无,1]。

在python的土地上,我会压缩这两个,并迭代结果。

所以,为了清楚起见,我想编写一个函数,它采用[20,2]形张量和[1]形张量,并产生[1]形张量,然后应用此函数用于[无,20,2]和[无,1]张量,以产生[无,1]张量。

希望我表达得足够好;更高的维度有时让我头晕目眩。

1 个答案:

答案 0 :(得分:1)

这对我有用(TensorFlow版本1.4.0)

tf.reset_default_graph()
sess = tf.Session()

# Define placeholders with undefined first dimension.
a = tf.placeholder(dtype=tf.float32, shape=[None, 3, 4])
b = tf.placeholder(dtype=tf.float32, shape=[None, 1])

# Create some input data.
a_input = np.arange(24).reshape(2, 3, 4)
b_input = np.arange(2).reshape(2, 1)

# TensorFlow map function.
def f_tf(x):
    return tf.reduce_sum(x[0]) + tf.reduce_sum(x[1])
# Numpy map function (for validation of results).
def f_numpy(x):
    return np.sum(x[0]) + np.sum(x[1])

# Run TensorFlow function.
s = tf.map_fn(f, [a, b], dtype=tf.float32)
sess.run(s, feed_dict={a: a_input, b: b_input})
  

array([66。,211。],dtype = float32)

# Run Numpy function. 
for inp in zip(a_input, b_input):
    print(f_numpy(inp))
  

66   211

相关问题