简体   繁体   中英

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

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).

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.

>>> 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 :

Tensor("Shape:0", shape=(3,), dtype=int32)

Alternatively you could get the shape of output and create the shape you want manually:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM