In [1]:
from __future__ import print_function
import tensorflow as tf
import numpy as np
In [2]:
from datetime import date
date.today()
Out[2]:
In [3]:
author = "kyubyong. https://github.com/Kyubyong/tensorflow-exercises"
In [4]:
tf.__version__
Out[4]:
In [5]:
np.__version__
Out[5]:
In [6]:
sess = tf.InteractiveSession()
Q1. Convert tensor x into a SparseTensor
.
In [61]:
x = tf.constant([[1, 0, 0, 0],
[0, 0, 2, 0],
[0, 0, 0, 0]], dtype=tf.int32)
sp = tf.SparseTensor(indices=[[0, 0], [1, 2]], values=[1, 2], dense_shape=[3, 4])
print(sp.eval())
Q2. Investigate the dtype
, indices
, dense_shape
and values
of the SparseTensor sp
in Q1.
In [62]:
print("dtype:", sp.dtype)
print("indices:", sp.indices.eval())
print("dense_shape:", sp.dense_shape.eval())
print("values:", sp.values.eval())
Q3. Let's write a custom function that converts a SparseTensor to Tensor. Complete it.
In [63]:
def dense_to_sparse(tensor):
indices = tf.where(tf.not_equal(tensor, 0))
return tf.SparseTensor(indices=indices,
values=tf.gather_nd(tensor, indices) - 1, # for zero-based index
dense_shape=tf.to_int64(tf.shape(tensor)))
# Test
print(dense_to_sparse(x).eval())
Q4. Convert the SparseTensor sp
to a Tensor using tf.sparse_to_dense
.
In [65]:
output = tf.sparse_to_dense(sparse_indices=[[0, 0], [1, 2]], sparse_values=[1, 2], output_shape=[3, 4])
print(output.eval())
print("Check if this is identical with x:\n", x.eval())
Q5. Convert the SparseTensor sp
to a Tensor using tf.sparse_tensor_to_dense
.
In [67]:
output = tf.sparse_tensor_to_dense(s)
print(output.eval())
print("Check if this is identical with x:\n", x.eval())
In [ ]: