def testMatrixApprox(self): tol = 10**-6 A = numpy.random.rand(10, 10) A = A.dot(A.T) n = 5 inds = numpy.sort(numpy.random.permutation(A.shape[0])[0:n]) AHat = Nystrom.matrixApprox(A, inds) n = 10 AHat2 = Nystrom.matrixApprox(A, n) self.assertTrue(numpy.linalg.norm(A - AHat2) < numpy.linalg.norm(A - AHat)) self.assertTrue(numpy.linalg.norm(A - AHat2) < tol) #Test on a sparse matrix As = scipy.sparse.csr_matrix(A) n = 5 inds = numpy.sort(numpy.random.permutation(A.shape[0])[0:n]) AHat = Nystrom.matrixApprox(As, inds) n = 10 AHat2 = Nystrom.matrixApprox(As, n) self.assertTrue(SparseUtils.norm(As - AHat2) < SparseUtils.norm(As - AHat)) self.assertTrue(SparseUtils.norm(As - AHat2) < tol) #Compare dense and sparse solutions for n in range(1, 9): inds = numpy.sort(numpy.random.permutation(A.shape[0])[0:n]) AHats = Nystrom.matrixApprox(As, inds) AHat = Nystrom.matrixApprox(A, inds) self.assertTrue(numpy.linalg.norm(AHat - numpy.array(AHats.todense())) < tol)
def testNorm(self): numRows = 10 numCols = 10 for k in range(10): A = scipy.sparse.rand(numRows, numCols, 0.1, "csr") norm = SparseUtils.norm(A) norm2 = 0 for i in range(numRows): for j in range(numCols): norm2 += A[i, j]**2 norm2 = numpy.sqrt(norm2) norm3 = numpy.linalg.norm(numpy.array(A.todense())) self.assertAlmostEquals(norm, norm2) self.assertAlmostEquals(norm, norm3)