Python Tensorflow合并维度和反向合并

Python Tensorflow合并维度和反向合并,python,tensorflow,Python,Tensorflow,假设我有一个形状为[3,5,200,300,3]的张量。如何将前两个dim合并在一起,使其具有形状为的张量[15,200,300,3]?然后,我应该能够反向合并操作并具有原始形状。您可以使用tf.restrape a = tf.random_normal(shape=(3, 5, 200, 300, 3)) b = tf.reshape(a, shape=(15, 200, 300, 3)) ... c = tf.reshape(b, shape=(3, 5, 200, 300, 3)) 以下

假设我有一个形状为[3,5,200,300,3]的张量。如何将前两个dim合并在一起,使其具有形状为的张量
[15,200,300,3]
?然后,我应该能够反向合并操作并具有原始形状。

您可以使用
tf.restrape

a = tf.random_normal(shape=(3, 5, 200, 300, 3))
b = tf.reshape(a, shape=(15, 200, 300, 3))
...
c = tf.reshape(b, shape=(3, 5, 200, 300, 3))

以下函数合并和拆分张量的前两个维度,推断其静态或动态形状

def infer_shape(x):
    x = tf.convert_to_tensor(x)

    # If unknown rank, return dynamic shape
    if x.shape.dims is None:
        return tf.shape(x)

    static_shape = x.shape.as_list()
    dynamic_shape = tf.shape(x)

    ret = []
    for i in range(len(static_shape)):
        dim = static_shape[i]
        if dim is None:
            dim = dynamic_shape[i]
        ret.append(dim)

    return ret

def merge_first_two_dims(tensor):
    shape = infer_shape(tensor)
    shape[0] *= shape[1]
    shape.pop(1)
    return tf.reshape(tensor, shape)


def split_first_two_dims(tensor, dim_0, dim_1):
    shape = infer_shape(tensor)
    new_shape = [dim_0] + [dim_1] + shape[1:]
    return tf.reshape(tensor, new_shape)

一般来说,您可以这样做,这不依赖于具有静态形状:

a = tf.ones([3, 5, 200, 300, 3])
b = tf.reshape(a, tf.concat([[tf.shape(a)[0] * tf.shape(a)[1]], tf.shape(a)[2:]], axis=0))

当我们不知道确切的形状时,有没有办法改变尺寸的数量?(或者我们应该用tf.shape来称呼tf.reforme吗?@Khaj你可以用符号标注
tf.reforme
,所以是的,你所描述的会起作用(但是,组装符号形状有时很复杂)。如果只有一个未知维度,那么您可以通过指定-1自动推断它,例如:
tf.reformate(b,shape=(-1,20,30))