python - 如何使用 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
可能在这里有所帮助...
感谢您分享您的知识。
解决方案
这应该可以解决问题:
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]]]
推荐阅读
- java - 将收到的消息分成两部分
- typescript - 为打字稿函数创建可区分的联合
- mockito - 执行 Mock Controller 时出现 NullPointerexception
- arcgis - ArcGIS 要素图层超出限制
- mysql - 致命错误:XAMPP 中的最大执行时间超过 30 秒
- nativescript - 如何在xml中调用函数
- angular7 - 角度虚拟滚动 autsize,设置滚动结束
- reactjs - 导入动作类别的材质 ui 图标的问题
- android - RxJava 链中的操作无法正常工作
- wordpress - 如何从wordpress中的请求中获取授权标头