Класс SparseTensor
Класс SparseTensor представляет разреженный тензор,
в котором хранятся только ненулевые элементы. Первым
параметром передаются индексы ненулевых элементов,
вторым - их значения, третьим - плотная форма тензора.
Такой формат экономит память при работе с данными,
содержащими много нулей.
Синтаксис
tf.SparseTensor(indices, values, dense_shape)
Пример
Давайте создадим разреженный тензор с тремя ненулевыми элементами:
import tensorflow as tf
indices = [[0, 0], [1, 2], [2, 1]]
values = [1, 2, 3]
dense_shape = [3, 3]
st = tf.SparseTensor(indices, values, dense_shape)
print(st)
Результат выполнения кода:
SparseTensor(indices=tf.Tensor(
[[0 0]
[1 2]
[2 1]], shape=(3, 2), dtype=int64), values=tf.Tensor([1 2 3], shape=(3,), dtype=int32), dense_shape=tf.Tensor([3 3], shape=(2,), dtype=int64))
Пример
Давайте преобразуем разреженный тензор в плотный
с помощью метода to_dense:
import tensorflow as tf
indices = [[0, 0], [1, 2], [2, 1]]
values = [1, 2, 3]
dense_shape = [3, 3]
st = tf.SparseTensor(indices, values, dense_shape)
t = tf.sparse.to_dense(st)
print(t)
Результат выполнения кода:
tf.Tensor(
[[1 0 0]
[0 0 2]
[0 3 0]], shape=(3, 3), dtype=int32)
Пример
Давайте получим индексы, значения и плотную форму разреженного тензора через его атрибуты:
import tensorflow as tf
indices = [[0, 0], [1, 2], [2, 1]]
values = [1, 2, 3]
dense_shape = [3, 3]
st = tf.SparseTensor(indices, values, dense_shape)
print(st.indices)
print(st.values)
print(st.dense_shape)
Результат выполнения кода:
tf.Tensor(
[[0 0]
[1 2]
[2 1]], shape=(3, 2), dtype=int64)
tf.Tensor([1 2 3], shape=(3,), dtype=int32)
tf.Tensor([3 3], shape=(2,), dtype=int64)
Пример
Давайте создадим разреженный тензор из плотного
с помощью функции tf.sparse.from_dense:
import tensorflow as tf
t = tf.constant([[1, 0, 0], [0, 0, 2], [0, 3, 0]])
st = tf.sparse.from_dense(t)
print(st)
Результат выполнения кода:
SparseTensor(indices=tf.Tensor(
[[0 0]
[1 2]
[2 1]], shape=(3, 2), dtype=int64), values=tf.Tensor([1 2 3], shape=(3,), dtype=int32), dense_shape=tf.Tensor([3 3], shape=(2,), dtype=int64))
Смотрите также
-
метод
from_value,
который создает разреженный тензор из значения -
метод
eval,
который вычисляет значение разреженного тензора -
атрибут
indices,
который хранит индексы ненулевых элементов -
атрибут
values,
который хранит значения ненулевых элементов