Tensorflow- tensor的列操作


幾個point

  1. [:,i]類似python直接的index 列操作是可行的,
  2. 注意i不能是variable,如果是使用slice
  3. slice操作會保持和輸入tensor一樣的shape 返回 1對應的列操作會降維
  4. Slice 使用-1 表示該維度元素全選類似:

   

import tensorflow as tf

sess = tf.InteractiveSession()

In [12]:

t = tf.constant([[1, 2, 3], [4, 5, 6]], dtype=tf.float32)

In [19]:

   

tf.expand_dims(t, 1).eval()

Out[19]:

array([[[ 1., 2., 3.]],

[[ 4., 5., 6.]]], dtype=float32)

In [14]:

t.eval().shape

Out[14]:

(2, 3)

In [18]:

tf.expand_dims(t, 1).eval().shape

Out[18]:

(2, 1, 3)

In [17]:

tf.concat(1, [tf.zeros([2,1]), t]).eval()

Out[17]:

array([[ 0., 1., 2., 3.],
[ 0., 4., 5., 6.]], dtype=float32)

In [20]:

   

t[:,1].eval()

Out[20]:

array([ 2., 5.], dtype=float32)

In [26]:

   

tf.reshape(t[:,1],[-1, 1]).eval()

Out[26]:

array([[ 2.],
[ 5.]], dtype=float32)

In [25]:

tf.reshape(t[:,1],[-1, 1]).eval().shape

Out[25]:

(2, 1)

In [34]:

tf.expand_dims(t[:,1],1).eval()

Out[34]:

array([[ 2.],
[ 5.]], dtype=float32)

In [28]:

tf.expand_dims(t[:,1],1).eval().shape

Out[28]:

(2, 1)

In [29]:

   

tf.gather(t, 1).eval()

Out[29]:

array([ 4., 5., 6.], dtype=float32)

In [35]:

tf.slice(t, [0, 1], [-1, 1]).eval()

Out[35]:

array([[ 2., 3.],
[ 5., 6.]], dtype=float32)

   

   

建議使用slice,不過有的時候希望自動降維的時候 直接用[:,]操作更方便比如

輸入tensor

#[batch_size, num_negs, emb_dim]

neg_comment_feature = tf.reduce_mean(neg_comment_feature,2)

   

下面希望

#[batch_size, emb_dim] <= [batch_size, num_negs, emb_dim]

可能的幾種方式

for i in xrange(num_negs):

neg_comment_feature_i = tf.reshape(tf.slice(neg_comment_feature, [0, i, 0], [-1, 1, emb_dim]), [-1, emb_dim])

neg_comment_feature_i = tf.reshape(tf.slice(neg_comment_feature, [0, i, 0], [-1, 1, -1]), [-1, emb_dim])

neg_comment_feature_i = neg_comment_feature[:,i,:] #直接降維

   


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM