如何从TensorFlow中的SparsetSensor中选择行?

2024-10-04 03:25:37 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有两个SparseTensor,如下所示:

[[1, 0, 0, 0],
 [2, 0, 0, 0],
 [1, 2, 0, 0]]

以及

^{pr2}$

我想从它们中提取前两行。我需要非零项的索引和值都是SparseTensors,这样我就可以将结果传递给tf.nn.embedding_lookup_sparse。我该怎么做?在

我的申请是: 我想用单词嵌入,这在TensorFlow中是非常直接的。但现在我想使用稀疏嵌入,即:对于普通单词,它们有自己的嵌入。对于稀有词,它们的嵌入是普通词嵌入的稀疏线性组合。 所以我需要两本食谱来说明稀疏嵌入是如何组成的。在前面提到的例子中,cookbook说:对于第一个单词,它的嵌入由它自己的权重为1.0的嵌入组成。第二个词的情况类似。对于最后一个词,它说:这个词的嵌入是前两个词嵌入的线性组合,相应的权重分别为0.3和0.7。 我需要提取一行,然后将索引和权重提供给tf.nn.embedding_lookup_sparse,以获得最终的嵌入。在TensorFlow中怎么做?在

或者我需要解决它,例如:预处理我的数据并处理TensorFlow中的食谱?在


Tags: tftensorflow情况nnembeddinglookup单词例子
3条回答

它不应该表现得更像这样:

此版本将保持选定索引中索引的顺序和频率,因此可以多次选择同一行:

import tensorflow as tf
tf.enable_eager_execution()

def sparse_gather(indices, values, selected_indices, axis=0):
    """
    indices: [[idx_ax0, idx_ax1, idx_ax2, ..., idx_axk], ... []]
    values:  [ value1,                                 , ..., valuen]
    """
    mask = tf.equal(indices[:, axis][tf.newaxis, :], selected_indices[:, tf.newaxis])
    to_select = tf.where(mask)[:, 1]
    return tf.gather(indices, to_select, axis=0), tf.gather(values, to_select, axis=0)


indices = tf.constant([[1, 0], [2, 0], [3, 0], [7, 0]])
values = tf.constant([1.0, 2.0, 3.0, 7.0], dtype=tf.float32)
needed_row_ids = tf.constant([7, 3, 2, 2, 3, 7])
slice_indices, slice_values = sparse_gather(indices, values, needed_row_ids)
print(slice_indices, slice_values)

sp作为2d SparseTensor的名称。首先可以为要提取的SparseTensor行创建一个指示符张量,即

mask = tf.concat([tf.constant([True, True]), tf.fill([sp.dense_shape[0] - 2],
    False)], axis=0)

下次使用tf.聚集要将其传播到稀疏索引,请执行以下操作:

^{pr2}$

最后

values = tf.boolean_mask(sp.values, mask_sp)
indices = tf.boolean_mask(sp.indices, mask_sp)
dense_shape = [sp.dense_shape[0] - 2, sp.dense_shape[1]]
output_sp = tf.SparseTensor(indices=indices, values=values, dense_shape=dense_shape)

我找了一位对这个领域了解更多的工程师,他告诉我的是:

我不确定我们是否有一个有效的实现,但这里有一个使用动态分区和聚集操作的不太理想的实现。在

def sparse_slice(indices, values, needed_row_ids):
   num_rows = tf.shape(indices)[0]
   partitions = tf.cast(tf.equal(indices[:,0], needed_row_ids), tf.int32)
   rows_to_gather = tf.dynamic_partition(tf.range(num_rows), partitions, 2)[1]
   slice_indices = tf.gather(indices, rows_to_gather)
   slice_values = tf.gather(values, rows_to_gather)
   return slice_indices, slice_values

with tf.Session().as_default():
  indices = tf.constant([[0,0], [1, 0], [2, 0], [2, 1]])
  values = tf.constant([1.0, 1.0, 0.3, 0.7], dtype=tf.float32)
  needed_row_ids = tf.constant([1])
  slice_indices, slice_values = sparse_slice(indices, values, needed_row_ids)
  print(slice_indices.eval(), slice_values.eval())

更新:

工程师还发送了一个示例来帮助处理多行,感谢您指出这一点!在

^{pr2}$

相关问题 更多 >