TensorFlow使用三个dense tensor来表达一个sparse tensor:indices、values、dense_shape。
假如我们有一个dense tensor:
[[1, 0, 0, 0]
[0, 0, 2, 0]
[0, 0, 0, 0]]
那么用SparseTensor表达这个数据对应的三个dense tensor如下:
-
indices:[[0, 0], [1, 2]] -
values:[1, 2] -
dense_shape:[3, 4]
可以通过以下两种方法,将sparse tensor转化为dense tensor:
-
tf.sparse_to_dense(sparse_indices, output_shape, sparse_values, default_value=0, validate_indices=True, name=None) -
tf.sparse_tensor_to_dense(sp_input, default_value=0, validate_indices=True, name=None)
SparseTensor(indices, values, dense_shape)
- indices: 一个2D的
int64 Tensor,shape为(N, ndims),指定了sparse tensor中的索引, 例如: indices=[[1,3], [2,4]]说明,dense tensor中对应索引为[1,3], [2,4]位置的元素的值不为0. - values: 一个
1D tensor,shape为(N)用来指定索引处的值. For example, given indices=[[1,3], [2,4]], the parameter values=[18, 3.6] specifies that element [1,3] of the sparse tensor has a value of 18, and element [2,4] of the tensor has a value of 3.6. - dense_shape: 一个1D的
int64 tensor,形状为ndims,指定dense tensor的形状.
相对应的有一个tf.sparse_placeholder,如果给这个sparse_placeholder喂数据呢?
sp = tf.sparse_placeholder(tf.int32)
with tf.Session() as sess:
#就这么喂就可以了
feed_dict = {sp:(indices, values, dense_shape)}
tensorflow中目前没有API提供denseTensor->SparseTensor转换
tf.sparse_tensor_to_dense(sp_input, default_value=0, validate_indices=True, name=None)
把一个SparseTensor转化为DenseTensor.
- sp_input: 一个
SparceTensor. - default_value:没有指定索引的对应的默认值.默认为0.
- validate_indices: 布尔值.如果为
True的话,将会检查sp_input的indices的lexicographic order和是否有重复. - name: 返回tensor的名字前缀.可选.
Reference:
TensorFlow SparseTensor详解
本文详细介绍了TensorFlow中SparseTensor的使用方法,包括其组成部分:indices、values、dense_shape的具体含义,以及如何通过SparseTensor将稀疏数据转换为密集型数据。此外,还提供了将SparseTensor转换为DenseTensor的两种方法。
1245

被折叠的 条评论
为什么被折叠?



