[英]python, tensorflow, how to get a tensor shape with half the features
I need the shape of a tensor, except instead of feature_size as the -1 dimension I need feature_size//2 我需要一个张量的形状,除了不是feature_size作为-1维度,我需要feature_size // 2
The code I'm currently using is 我当前使用的代码是
_, half_output = tf.split(output,2,axis=-1)
half_shape = tf.shape(half_output)
This works but it's incredibly inelegant. 这行得通,但是令人难以置信。 I don't need an extra copy of half the tensor, I just need that shape. 我不需要张量的一半的额外副本,我只需要那种形状。 I've tried to do this other ways but nothing besides this bosh solution has worked yet. 我已经尝试过其他方法,但是除了这种可行的解决方案之外,其他任何方法都没有起作用。
Anyone know a simple way to do this? 有人知道这样做的简单方法吗?
A simple way to get the shape with the last value halved: 一种将最后一个值减半的形状的简单方法:
half_shape = tf.shape(output[..., 1::2])
What it does is simply iterate output
in its last dimension with step 2, starting from the second element (index 1). 它所做的只是简单地从第二个元素(索引1)开始,在最后一个维度中从步骤2迭代output
。
The ...
doesn't touch other dimensions. ...
不会触及其他尺寸。 As a result, you will have output[..., 1::2]
with the same dimensions as output
, except for the last one, which will be sampled like the following example, resulting in half the original value. 其结果是,你将有output[..., 1::2]
与相同尺寸的output
,除了最后一个,这将如以下示例进行采样,从而产生一半的原始值。
>>> a = np.random.rand(5,5)
>>> a
array([[ 0.21553665, 0.62008421, 0.67069869, 0.74136913, 0.97809012],
[ 0.70765302, 0.14858418, 0.47908281, 0.75706245, 0.70175868],
[ 0.13786186, 0.23760233, 0.31895335, 0.69977537, 0.40196103],
[ 0.7601455 , 0.09566717, 0.02146819, 0.80189659, 0.41992885],
[ 0.88053697, 0.33472285, 0.84303012, 0.10148065, 0.46584882]])
>>> a[..., 1::2]
array([[ 0.62008421, 0.74136913],
[ 0.14858418, 0.75706245],
[ 0.23760233, 0.69977537],
[ 0.09566717, 0.80189659],
[ 0.33472285, 0.10148065]])
This half_shape
prints the following Tensor
: 这个half_shape
打印以下Tensor
:
Tensor("Shape:0", shape=(3,), dtype=int32) 张量(“ Shape:0”,shape =(3,),dtype = int32)
Alternatively you could get the shape of output
and create the shape you want manually: 或者,您可以获取output
的形状并手动创建所需的形状:
s = output.get_shape().as_list()
half_shape = tf.TensorShape(s[:-1] + [s[-1] // 2])
This half_shape
prints a TensorShape
showing the shape halved in the last dimension. 这个half_shape
打印一个TensorShape
显示在最后一个维度中减半的形状。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.