gpt4 book ai didi

python - 如何使用 TensorFlow 连接两个具有不同形状的张量?

转载 作者:太空宇宙 更新时间:2023-11-04 09:41:15 25 4
gpt4 key购买 nike

您好,我是 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_dimstf.reshape 可能对这里有帮助...

感谢您分享您的知识。

最佳答案

这应该可以解决问题:

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]]]

关于python - 如何使用 TensorFlow 连接两个具有不同形状的张量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51602194/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com