📜  Python – tensorflow.IndexedSlices()(1)

📅  最后修改于: 2023-12-03 15:19:03.636000             🧑  作者: Mango

Python - tensorflow.IndexedSlices()

The tensorflow.IndexedSlices() function is a way to represent a tensor where most of the elements are zero. This can be useful when working with sparse tensors, where large amounts of data are zero and don't need to be stored in memory.

Syntax
tf.IndexedSlices(values, indices, dense_shape=None)
  • values: A Tensor representing the values in the sparse tensor.
  • indices: A Tensor representing the indices in the sparse tensor.
  • dense_shape: An optional list, tuple or 1-D Tensor representing the shape of the dense tensor. If None, dense_shape is inferred from the indices.
Example
import tensorflow as tf

# Create a SparseTensor with values [1, 2, 3] at indices [0, 2, 4]
values = tf.constant([1, 2, 3])
indices = tf.constant([0, 2, 4])
sparse_tensor = tf.IndexedSlices(values, indices)

# Convert the SparseTensor to a dense tensor
dense_tensor = tf.sparse.to_dense(sparse_tensor)

with tf.Session() as sess:
    print(sess.run(dense_tensor))

The output of this code will be a dense tensor with shape (5,) and values [1, 0, 2, 0, 3]. This is because the SparseTensor has nonzero values at indices 0, 2, and 4, and zeros everywhere else.

Conclusion

The tensorflow.IndexedSlices() function is a useful tool for working with sparse tensors. By representing only the nonzero elements, it can save memory and computation time.