提交 bfecc533 authored 作者: nouiz's avatar nouiz

Merge pull request #220 from yaoli/EnsureSortedIndicesReview

Ensure sorted indices reviewed
...@@ -254,25 +254,35 @@ class EnsureSortedIndices(Op): ...@@ -254,25 +254,35 @@ class EnsureSortedIndices(Op):
""" """
Remove explicit zeros from a sparse matrix, and resort indices Remove explicit zeros from a sparse matrix, and resort indices
""" """
inplace=False
def __init__(self, inplace): def __init__(self, inplace):
self.inplace=inplace self.inplace = inplace
if self.inplace: if self.inplace:
self.view_map = {0:[0]} self.view_map = {0:[0]}
def make_node(self, x): def make_node(self, x):
return gof.Apply(self, [x], [x.type()]) return gof.Apply(self, [x], [x.type()])
def perform(self,node, (x,), (z,)): def perform(self, node, inputs, output_storage):
x = inputs[0]
z = output_storage[0]
if self.inplace: if self.inplace:
x.sort_indices() x.sort_indices()
z[0] = x z[0] = x
else: else:
z[0] = x.sorted_indices() z[0] = x.sorted_indices()
def grad(self, (x,), (gz,)): def grad(self, inputs, output_grad):
return [gz] return [output_grad[0]]
def infer_shape(self, node, i0_shapes):
return i0_shapes
def __str__(self):
if self.inplace:
return self.__class__.__name__ + "{inplace}"
else:
return self.__class__.__name__ + "{no_inplace}"
ensure_sorted_indices = EnsureSortedIndices(inplace=False) ensure_sorted_indices = EnsureSortedIndices(inplace=False)
......
...@@ -16,7 +16,7 @@ from theano import function, tensor ...@@ -16,7 +16,7 @@ from theano import function, tensor
import theano import theano
from theano.sparse.sandbox import sp from theano.sparse.sandbox import sp
from theano.tests import unittest_tools as utt from theano.tests import unittest_tools as utt
from theano.sparse.tests.test_basic import random_lil
class TestSP(unittest.TestCase): class TestSP(unittest.TestCase):
def test_convolution(self): def test_convolution(self):
...@@ -413,6 +413,27 @@ def test_diagonal(): ...@@ -413,6 +413,27 @@ def test_diagonal():
assert numpy.all(n == f(range(K)).toarray()) assert numpy.all(n == f(range(K)).toarray())
def test_ensure_sorted_indices():
x = 2000
y = 2000
sparsity = 1000
for i in range(2):
# testing both csc and csr
if i is 0:
# csc
input_tensor = theano.sparse.csc_dmatrix()
sample = scipy.sparse.csc_matrix(random_lil((x,y),'float64',sparsity))
else:
# csr
input_tensor = theano.sparse.csr_dmatrix()
sample = scipy.sparse.csr_matrix(random_lil((x,y),'float64',sparsity))
sort_op = sp.ensure_sorted_indices(input_tensor)
f = theano.function([input_tensor], sort_op)
sorted_scipy = sample.sorted_indices()
sorted_theano = f(sample)
assert numpy.all(sorted_theano.todense() == sorted_scipy.todense())
def test_diagonal_grad(): def test_diagonal_grad():
def d(x): def d(x):
return sp.sp_sum(sp.square_diagonal(x), sparse_grad=True) return sp.sp_sum(sp.square_diagonal(x), sparse_grad=True)
......
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论