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: