1. 程式人生 > 程式設計 >tensorflow實現tensor中滿足某一條件的數值取出組成新的tensor

tensorflow實現tensor中滿足某一條件的數值取出組成新的tensor

首先使用tf.where()將滿足條件的數值索引取出來,在numpy中,可以直接用矩陣引用索引將滿足條件的數值取出來,但是在tensorflow中這樣是不行的。所幸,tensorflow提供了tf.gather()和tf.gather_nd()函式。

看下面這一段程式碼:

import tensorflow as tf
sess = tf.Session()
def get_tensor():
  x = tf.random_uniform((5,4))
  ind = tf.where(x>0.5)
  y = tf.gather_nd(x,ind)
  return x,ind,y

在上述程式碼中,輸出分別是原始的tensor x,x中滿足特定條件(此處為>0.5)的數值的索引,以及x中滿足特定條件的數值。執行以下步驟,觀察三個tensor對應的數值:

x,y = get_tensor()
x_,ind_,y_ = sess.run([x,y])

可以得到如下結果:

可以看到,上述結果中將tensor x中大於0.5的數值取出來組成了一個新的tensor y。

如果我們將程式碼中的tf.gather_nd替換成tf.gather會發生什麼呢?由於結果不方便展示,這裡不放結果了,tf.gather適用於index為一維的情況,在本例中,index為2維,如果選用tf.gather的話,對應的x,y的維數分別如下:

x.shape = (5,4)
ind.shape = (9,2)
y.shape = (9,2,4)

以上這篇tensorflow實現tensor中滿足某一條件的數值取出組成新的tensor就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支援我們。