如何重塑具有多个“无"维度的张量? [英] How to reshape a tensor with multiple `None` dimensions?
问题描述
我遇到了将中间 4D 张量流张量 X
重塑为 3D 张量 Y
的问题,其中
I encountered a problem to reshape an intermediate 4D tensorflow tensor X
to a 3D tensor Y
, where
X
的形状是( batch_size, nb_rows, nb_cols, nb_filters )
Y
的形状是( batch_size, nb_rows*nb_cols, nb_filters )
batch_size = None
X
is of shape( batch_size, nb_rows, nb_cols, nb_filters )
Y
is of shape( batch_size, nb_rows*nb_cols, nb_filters )
batch_size = None
当然,当nb_rows
和nb_cols
是已知整数时,我可以毫无问题地重塑X
.但是,在我的应用程序中,我需要处理这种情况
Of course, when nb_rows
and nb_cols
are known integers, I can reshape X
without any problem. However, in my application I need to deal with the case
nb_rows = nb_cols = None
我该怎么办?我尝试了 Y = tf.reshape( X, (-1, -1, nb_filters))
但它显然无法正常工作.
What should I do? I tried Y = tf.reshape( X, (-1, -1, nb_filters))
but it clearly fails to work.
对我来说,这个操作是确定性的,因为它总是将两个中间轴压缩成一个,同时保持第一个轴和最后一个轴不变.有人可以帮我吗?
For me, this operation is deterministic because it always squeezes the two middle axes into a single one while keeping the first axis and the last axis unchanged. Can anyone help me?
推荐答案
此时可以通过tf.shape(X)
访问X
的动态形状:
In this case you can access to the dynamic shape of X
through tf.shape(X)
:
shape = [tf.shape(X)[k] for k in range(4)]
Y = tf.reshape(X, [shape[0], shape[1]*shape[2], shape[3]])
这篇关于如何重塑具有多个“无"维度的张量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!