[英]How to concatenate two tensors with different shape in 2d convolution in tensorflow?
[英]How to concatenate two tensors having different shape with 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
可能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]]]
实际上有一个不同的技巧,在OpenAI的基线等代码库中不时使用。
假设您的高斯政策有两个张量。 mu
和std
。 对于批量大小1,标准偏差与mu
具有相同的形状,但由于对所有操作使用相同的参数化标准偏差,因此当批量大小大于1时,两者会有所不同:
mu : Size<batch_size, feat_n>
std: Size<1, feat_n>
在这种情况下,一个简单的事情(就像OpenAI基线所做的那样)是这样做的:
params = tf.concat([mu, mu * 0 + std])
零乘法将std
转换为与mu
相同的等级。
享受,祝你好运!
ps: numpy
和tensorflow
的concat
运算符不会自动应用广播,因为根据维护者的说法,当两个张量的形状不匹配时,通常是编程错误的结果。 这在numpy中并不是一件大事,因为计算得到了热切的评估。 但是对于tensorflow,这意味着您必须使用tf.shape
运算符手动显式地广播较低级别(或具有形状[1,* _]的tf.shape
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.