簡體   English   中英

python,tensorflow,如何獲得具有一半特征的張量形狀

[英]python, tensorflow, how to get a tensor shape with half the features

我需要一個張量的形狀,除了不是feature_size作為-1維度,我需要feature_size // 2

我當前使用的代碼是

_, half_output = tf.split(output,2,axis=-1)

half_shape = tf.shape(half_output)

這行得通,但是令人難以置信。 我不需要張量的一半的額外副本,我只需要那種形狀。 我已經嘗試過其他方法,但是除了這種可行的解決方案之外,其他任何方法都沒有起作用。

有人知道這樣做的簡單方法嗎?

一種將最后一個值減半的形狀的簡單方法:

half_shape = tf.shape(output[..., 1::2])

它所做的只是簡單地從第二個元素(索引1)開始,在最后一個維度中從步驟2迭代output

...不會觸及其他尺寸。 其結果是,你將有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]])

這個half_shape打印以下Tensor

張量(“ Shape:0”,shape =(3,),dtype = int32)

或者,您可以獲取output的形狀並手動創建所需的形狀:

s = output.get_shape().as_list()
half_shape = tf.TensorShape(s[:-1] + [s[-1] // 2])

這個half_shape打印一個TensorShape顯示在最后一個維度中減半的形狀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM