def RandPosdefSpMatrix(dim): """ Generate random (non-singular) matrix Arguments: dim - int matrix_sqrt - TpMatrix logdet - float Outputs: matrix - SpMatrix """ while True: tmp = Matrix(dim, dim) tmp.set_randn_() if tmp.cond() < 100: break print( "Condition number of random matrix large {}, trying again (this is normal)" .format(tmp.cond())) # tmp * tmp^T will give positive definite matrix matrix = SpMatrix(dim) matrix.add_mat2_(1.0, tmp, MatrixTransposeType.NO_TRANS, 0.0) matrix_sqrt = TpMatrix(len(matrix)) matrix_sqrt = matrix_sqrt.cholesky_(matrix) logdet_out = matrix.log_pos_def_det() return matrix, matrix_sqrt, logdet_out
def test_nnet_decodable(self): gen_config = NnetGenerationOptions() configs = generate_config_sequence(gen_config) nnet = Nnet() for j, config in enumerate(configs): print("Input config[{}]:".format(j)) print(config) istrm = istringstream.from_str(config) nnet.read_config(istrm) num_frames = 5 + random.randint(1, 100) input_dim = nnet.input_dim("input") output_dim = nnet.output_dim("output") ivector_dim = max(0, nnet.input_dim("ivector")) input = Matrix(num_frames, input_dim) set_batchnorm_test_mode(True, nnet) set_dropout_test_mode(True, nnet) input.set_randn_() ivector = Vector(ivector_dim) ivector.set_randn_() priors = Vector(output_dim if random.choice([True, False]) else 0) if len(priors) != 0: priors.set_randn_() priors.apply_exp_() output1 = Matrix(num_frames, output_dim) output2 = Matrix(num_frames, output_dim) opts = NnetSimpleComputationOptions() opts.frames_per_chunk = random.randint(5, 25) compiler = CachingOptimizingCompiler(nnet) decodable = DecodableNnetSimple(opts, nnet, priors, input, compiler, ivector if ivector_dim else None) for t in range(num_frames): decodable.get_output_for_frame(t, output1[t]) opts = NnetSimpleLoopedComputationOptions() info = DecodableNnetSimpleLoopedInfo.new_from_priors( opts, priors, nnet) decodable = DecodableNnetSimpleLooped(info, input, ivector if ivector_dim else None) for t in range(num_frames): decodable.get_output_for_frame(t, output2[t]) if (not nnet_is_recurrent(nnet) and nnet.info().find("statistics-extraction") == -1 and nnet.info().find("TimeHeightConvolutionComponent") == -1): for t in range(num_frames): self.assertTrue(approx_equal(output1[t], output2[t]))
def test__init__(self): m = Matrix() sb = SubMatrix(m) m = Matrix(5, 5) sb = SubMatrix(m) for i in range(100): m.set_randn_() self.assertAlmostEqual(m.sum(), sb.sum()) m = DoubleMatrix() sb = SubMatrix(m)
def testcopy_from_mat(self): for i in range(10): rows, cols = 10 * i, 5 * i A = Matrix(rows, cols) A.set_randn_() B = CuMatrix.new_from_size(*A.shape) B.copy_from_mat(A) self.assertAlmostEqual(A.sum(), B.sum(), places=4) A = CuMatrix.new_from_size(rows, cols) A.set_randn() B = CuMatrix.new_from_size(rows, cols) B.copy_from_cu_mat(A) self.assertAlmostEqual(A.sum(), B.sum(), places=4)