tf.SparseTensor
TensorFlow表示稀疏张量作为三个独立的密张量: indices
,values
,和dense_shape
。在Python中,三个张量被收集到一个SparseTensor
类中以便于使用。如果你有单独的 indices
,values
和dense_shape
张量,SparseTensor
在传递给下面的操作之前将它们包装在一个对象中。
具体地说,稀疏张量tf.SparseTensor(indices, values, dense_shape)
包括以下组件,其中N
和ndims
分别是值的数量和维度的数量SparseTensor
:
indices
:一个2-D int64张量的dense_shape [N, ndims]
,它指定稀疏张量中包含非零值的元素的索引(元素为零索引)。例如,indices=[[1,3], [2,4]]
指定索引为[1,3]和[2,4]的元素具有非零值。
values
:任何类型的1-D张量和dense_shape [N]
,它为每个元素提供值indices
。例如,给定 indices=[[1,3], [2,4]]
,该参数values=[18, 3.6]
指定稀疏张量的元素[1,3]具有值18,并且张量的元素[2,4]具有值3.6。
dense_shape
:一个1-D int64张量的dense_shape [ndims]
,它指定稀疏张量的dense_shape。获取一个列表,指示每个维度中的元素数量。例如,dense_shape=[3,6]
指定二维3x6张量,dense_shape=[2,3,4]
指定三维2x3x4张量,并dense_shape=[9]
指定具有9个元素的一维张量。
相应的密集张量满足:
dense.shape = dense_shape dense[tuple(indices[i])] = values[i]
按照惯例,indices
应按行主顺序排序(或等效于元组的字典顺序indices[i]
)。SparseTensor
构造对象时不会强制执行此 操作,但大多数操作都假定正确的顺序。如果稀疏张量的排序st
错误,可以通过调用获得固定版本tf.sparse_reorder(st)
。
示例:稀疏张量
SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4]
代表密集的张量
[[1, 0, 0, 0]
[0, 0, 2, 0]
[0, 0, 0, 0]]
tf.contrib.layers.dense_to_sparse
tf.contrib.layers.dense_to_sparse(
tensor,
eos_token=0,
outputs_collections=None,
scope=None
)
定义于tensorflow/contrib/layers/python/layers/layers.py
。
将密集张量转换为稀疏张量。一个示例用法是将密集标签转换为稀疏标签,以便将它们提供给ctc_loss。
ARGS:
tensor
:int
Tensor
要转换为Sparse
。eos_token
:一个整数。它是目标标签的一部分,用于表示句子的结尾。outputs_collections
:用于添加输出的集合。scope
:name_scope的可选范围。