假设我有一个形状为[3, 5, 200, 300, 3]
的张量。如何将前两个昏暗合并在一起,以便我具有形状[15, 200, 300, 3]
的张量。然后我可以反向合并操作并具有原始形状。
答案 0 :(得分:3)
您可以使用tf.reshape
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))
答案 1 :(得分:0)
以下函数合并并拆分张量的前两个维,以推断张量的静态或动态形状。
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)
答案 2 :(得分:0)
大多数情况下,您可以执行此操作,而这并不依赖于具有静态形状:
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))