TensorFlow of SparseTensor objects

In TensorFlow in, SparseTensor object represents a sparse matrix. SparseTensor objects to represent sparse dense matrix by three indices, values ​​and dense_shape, dense matrices of these three meanings described below:

1. indices: a two-dimensional data type int64 Tensor target, which is the Shape [N, ndims]. The indices are stored index value of zero, i.e., in addition to the sparse matrix stored in the position indices, other positions are zero.

2. values: Tensor one-dimensional objects, which is a Shape [N]. It is the value corresponding to the index position indices sparse matrix.

3. dense_shape: a one-dimensional data type int64 Tensor objects, the dimension [ndims], specifies the current sparse matrix corresponding to Shape.

For example, the object sparse matrix SparseTensor (indices = [[0, 0], [1, 1]], value = [1, 1], dense_shape = [3, 3]) corresponding to the following matrix:

 [[1. 0. 0.]
 [0. 1. 0.]
 [0. 0. 0.]]

Tf.sparse_tensor_to_dense function for a sparse matrix SparseTensor object into a dense matrix, tf.sparse_tensor_to_dense function has the following prototype:

tf.sparse_tensor_to_dense(
     sp_input,
     default_value=0,
     validate_indices=True,
     name=None
)

Type and meaning of the parameters as follows:

sp_input: SparseTensor objects, for converting a dense matrix input.

default_value: scalar type. Sp_input sparse matrix indices do not specify the location in the element values, the default is 0.

validate_indices: bool type, used to set whether the index values ​​sorted in alphabetic order.

name: string type. Tensor prefix name of the object returned.

 

Sample code:

import tensorflow as tf

# 定义Tensor对象
indices_tf = tf.constant([[0, 0], [1, 1]], dtype=tf.int64)
values_tf = tf.constant([1, 2], dtype=tf.float32)
dense_shape_tf = tf.constant([3, 3], dtype=tf.int64)

sparse_tf = tf.SparseTensor(indices=indices_tf,
                            values=values_tf,
                            dense_shape=dense_shape_tf)
dense_tf = tf.sparse_tensor_to_dense(sparse_tf, default_value=0)
with tf.Session() as sess:
    sparse, dense = sess.run([sparse_tf, dense_tf])
    print('sparse:\n', sparse)
    print('dense:\n', dense)

Output:

sparse:
 SparseTensorValue(indices=array([[0, 0],
       [1, 1]], dtype=int64), values=array([1., 2.], dtype=float32), dense_shape=array([3, 3], dtype=int64))

dense:
 [[1. 0. 0.]
 [0. 2. 0.]
 [0. 0. 0.]]

 

Published 105 original articles · won praise 17 · views 110 000 +

Guess you like

Origin blog.csdn.net/qq_38890412/article/details/104087552