Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable tf.size() for SparseTensor #2681

Merged
merged 1 commit into from Jun 18, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions tensorflow/python/kernel_tests/shape_ops_test.py
Expand Up @@ -91,13 +91,23 @@ def _compareSize(self, x, use_gpu=False):
self.assertAllEqual(np_ans, result)
self.assertShapeEqual(np_ans, tf_ans)

def _compareSizeSparse(self, x_np, use_gpu=False):
np_ans = np.asarray(np.size(x_np))
x_tf, unused_nnz = _sparsify(x_np)
with self.test_session(use_gpu=use_gpu):
tf_ans = tf.size(x_tf)
result = tf_ans.eval()
self.assertAllEqual(np_ans, result)
self.assertShapeEqual(np_ans, tf_ans)

def _testCpu(self, x):
self._compareShape(x, use_gpu=False)
self._compareShapeN(x, use_gpu=False)
self._compareRank(x, use_gpu=False)
self._compareSize(x, use_gpu=False)
self._compareShapeSparse(x, use_gpu=False)
self._compareRankSparse(x, use_gpu=False)
self._compareSizeSparse(x, use_gpu=False)

def _testGpu(self, x):
self._compareShape(x, use_gpu=True)
Expand All @@ -106,6 +116,7 @@ def _testGpu(self, x):
self._compareSize(x, use_gpu=True)
self._compareShapeSparse(x, use_gpu=True)
self._compareRankSparse(x, use_gpu=True)
self._compareSizeSparse(x, use_gpu=True)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

False


def _testAll(self, x):
self._testCpu(x)
Expand Down
28 changes: 28 additions & 0 deletions tensorflow/python/ops/array_ops.py
Expand Up @@ -130,6 +130,34 @@ def shape(input, name=None):
return gen_array_ops.shape(input, name=name)


def size(input, name=None):
"""Returns the size of a tensor.

This operation returns an integer representing the number of elements in
`input`.

For example:

```python
# 't' is [[[1, 1, 1], [2, 2, 2]], [[3, 3, 3], [4, 4, 4]]]]
size(t) ==> 12
```

Args:
input: A `Tensor` or `SparseTensor`.
name: A name for the operation (optional).

Returns:
A `Tensor` of type `int32`.
"""
with ops.op_scope([input], name, "Size") as name:
if isinstance(input, ops.SparseTensor):
return gen_math_ops._prod(gen_math_ops.cast(input.shape, dtypes.int32), 0,
name=name)
else:
return gen_array_ops.size(input, name=name)


def rank(input, name=None):
"""Returns the rank of a tensor.

Expand Down