首页 > 解决方案 > 如何使用 TensorFlow 连接两个具有不同形状的张量?

问题描述

您好,我是 TensorFlow 的新手,我想将 2D 张量连接到 3D 张量。我不知道如何通过利用 TensorFlow 函数来做到这一点。

tensor_3d = [[[1,2], [3,4]], [[5,6], [7,8]]]  # shape (2, 2, 2)
tensor_2d = [[10,11], [12,13]]                # shape (2, 2)

out: [[[1,2,10,11], [3,4,10,11]], [[5,6,12,13], [7,8,12,13]]]  # shape (2, 2, 4)

我会通过使用循环和新的 numpy 数组来使其工作,但这样我就不会使用 TensorFlow 转换。关于如何使这成为可能的任何建议?我看不到转换如何:tf.expand_dims或者tf.reshape可能在这里有所帮助...

感谢您分享您的知识。

标签: pythonnumpytensorflowneural-network

解决方案


这应该可以解决问题:

import tensorflow as tf

a = tf.constant([[[1,2], [3,4]], [[5,6], [7,8]]]) 
b = tf.constant([[10,11], [12,13]])

c = tf.expand_dims(b, axis=1) # Add dimension
d = tf.tile(c, multiples=[1,2,1]) # Duplicate in this dimension
e = tf.concat([a,d], axis=-1) # Concatenate on innermost dimension

with tf.Session() as sess:
    print(e.eval())

给出:

[[[ 1  2 10 11]
[ 3  4 10 11]]

[[ 5  6 12 13]
[ 7  8 12 13]]]

推荐阅读