在TensorFlow中将张量扩展为另一个具有不同尺寸的张量

时间:2018-03-15 08:10:26

标签: python tensorflow

我们说我有一个形状为[a,b]的张量,另一个形状为[a,c],其中c<b。我想将两者合并到尺寸为[a, b+c]的张量。如何在TensorFlow中实现这一目标?

简单地使用tf.concat在这种情况下不会工作,因为它期望除0之外的所有维度都相等:

All dimensions except 0 must match. Input 1 has shape [a b] and doesn't match input 0 with shape [a c]

1 个答案:

答案 0 :(得分:1)

此代码运作良好:

a = tf.constant([[1, 2, 3], [6, 7, 8]], tf.float32)
b = tf.constant([[4, 5], [9, 10]], tf.float32)
c = tf.concat([a,b], axis=-1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(c))

或者这个:

a = np.array([[1, 2, 3], [6, 7, 8]], np.float32)
b = np.array([[4, 5], [9, 10]], np.float32)
aph = tf.placeholder(tf.float32, shape = [None, None])
bph = tf.placeholder(tf.float32, shape = [None, None])
c = tf.concat([aph,bph], axis = -1)
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(sess.run(c, feed_dict={aph: a, bph: b}))