Tensorflow- tensor的列操作

时间:2023-03-09 01:42:05
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,:] #直接降维