Python numpy.testing() Examples
The following are 30
code examples of numpy.testing().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: ScipySpecialTestCases.py From ufora with Apache License 2.0 | 6 votes |
def test_hyp2f1_2(self): def f(a, b, c, z): return scipy.special.hyp2f1(a, b, c, z) a,b,c,z = 2.8346157367796936, 0.0102, 3.8346157367796936, 0.9988460588541513 res1 = self.evaluateWithExecutor(f, a, b, c, z) res2 = f(a, b, c, z) numpy.testing.assert_almost_equal( res1, res2 ) numpy.testing.assert_almost_equal( res1, 1.0182383750413575 )
Example #2
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_masked_topk_selects_top_scored_items_and_respects_masking(self): items = torch.randn([3, 4, 5]).clamp(min=0.0, max=1.0) items[0, :2, :] = 1 items[1, 2:, :] = 1 items[2, 2:, :] = 1 scores = items.sum(-1) mask = torch.ones([3, 4]).bool() mask[1, 0] = 0 mask[1, 3] = 0 pruned_scores, pruned_mask, pruned_indices = util.masked_topk(scores, mask, 2) # Second element in the batch would have indices 2, 3, but # 3 and 0 are masked, so instead it has 1, 2. numpy.testing.assert_array_equal( pruned_indices.data.numpy(), numpy.array([[0, 1], [1, 2], [2, 3]]) ) numpy.testing.assert_array_equal(pruned_mask.data.numpy(), numpy.ones([3, 2])) # scores should be the result of index_selecting the pruned_indices. correct_scores = util.batched_index_select(scores.unsqueeze(-1), pruned_indices).squeeze(-1) self.assert_array_equal_with_mask(correct_scores, pruned_scores, pruned_mask)
Example #3
Source File: test_slinalg.py From D-VAE with MIT License | 6 votes |
def test_cholesky_and_cholesky_grad_shape(): if not imported_scipy: raise SkipTest("Scipy needed for the Cholesky op.") rng = numpy.random.RandomState(utt.fetch_seed()) x = tensor.matrix() for l in (cholesky(x), Cholesky(lower=True)(x), Cholesky(lower=False)(x)): f_chol = theano.function([x], l.shape) g = tensor.grad(l.sum(), x) f_cholgrad = theano.function([x], g.shape) topo_chol = f_chol.maker.fgraph.toposort() topo_cholgrad = f_cholgrad.maker.fgraph.toposort() if config.mode != 'FAST_COMPILE': assert sum([node.op.__class__ == Cholesky for node in topo_chol]) == 0 assert sum([node.op.__class__ == CholeskyGrad for node in topo_cholgrad]) == 0 for shp in [2, 3, 5]: m = numpy.cov(rng.randn(shp, shp + 10)).astype(config.floatX) yield numpy.testing.assert_equal, f_chol(m), (shp, shp) yield numpy.testing.assert_equal, f_cholgrad(m), (shp, shp)
Example #4
Source File: test_warnings.py From lambda-packs with MIT License | 6 votes |
def test_warning_calls(): # combined "ignore" and stacklevel error base = Path(numpy.__file__).parent for path in base.rglob("*.py"): if base / "testing" in path.parents: continue if path == base / "__init__.py": continue if path == base / "random" / "__init__.py": continue # use tokenize to auto-detect encoding on systems where no # default encoding is defined (e.g. LANG='C') with tokenize.open(str(path)) as file: tree = ast.parse(file.read()) FindFuncs(path).visit(tree)
Example #5
Source File: testutils.py From lambda-packs with MIT License | 6 votes |
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """ Asserts that comparison between two masked arrays is satisfied. The comparison is elementwise. """ # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return np.testing.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header)
Example #6
Source File: testutils.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """ Asserts that comparison between two masked arrays is satisfied. The comparison is elementwise. """ # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return np.testing.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header)
Example #7
Source File: testutils.py From recruit with Apache License 2.0 | 6 votes |
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """ Asserts that comparison between two masked arrays is satisfied. The comparison is elementwise. """ # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return np.testing.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header)
Example #8
Source File: test_hmm.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def test_backward_probability(): from numpy.testing import assert_array_almost_equal model, states, symbols, seq = _wikipedia_example_hmm() bp = 2**model._backward_probability(seq) # examples in wikipedia are normalized bp = (bp.T / bp.sum(axis=1)).T wikipedia_results = [ # Forward-backward algorithm doesn't need b0_5, # so .backward_probability doesn't compute it. # [0.6469, 0.3531], [0.5923, 0.4077], [0.3763, 0.6237], [0.6533, 0.3467], [0.6273, 0.3727], [0.5, 0.5], ] assert_array_almost_equal(wikipedia_results, bp, 4)
Example #9
Source File: test_slinalg.py From D-VAE with MIT License | 6 votes |
def test_eigvalsh(): if not imported_scipy: raise SkipTest("Scipy needed for the geigvalsh op.") import scipy.linalg A = theano.tensor.dmatrix('a') B = theano.tensor.dmatrix('b') f = function([A, B], eigvalsh(A, B)) rng = numpy.random.RandomState(utt.fetch_seed()) a = rng.randn(5, 5) a = a + a.T for b in [10 * numpy.eye(5, 5) + rng.randn(5, 5)]: w = f(a, b) refw = scipy.linalg.eigvalsh(a, b) numpy.testing.assert_array_almost_equal(w, refw) # We need to test None separatly, as otherwise DebugMode will # complain, as this isn't a valid ndarray. b = None B = theano.tensor.NoneConst f = function([A], eigvalsh(A, B)) w = f(a) refw = scipy.linalg.eigvalsh(a, b) numpy.testing.assert_array_almost_equal(w, refw)
Example #10
Source File: test_nlinalg.py From D-VAE with MIT License | 6 votes |
def test_diag(self): # test that it builds a matrix with given diagonal when using # vector inputs x = theano.tensor.vector() y = diag(x) assert y.owner.op.__class__ == AllocDiag # test that it extracts the diagonal when using matrix input x = theano.tensor.matrix() y = extract_diag(x) assert y.owner.op.__class__ == ExtractDiag # other types should raise error x = theano.tensor.tensor3() ok = False try: y = extract_diag(x) except TypeError: ok = True assert ok # not testing the view=True case since it is not used anywhere.
Example #11
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_flattened_index_select(self): indices = numpy.array([[1, 2], [3, 4]]) targets = torch.ones([2, 6, 3]).cumsum(1) - 1 # Make the second batch double its index so they're different. targets[1, :, :] *= 2 indices = torch.tensor(indices, dtype=torch.long) selected = util.flattened_index_select(targets, indices) assert list(selected.size()) == [2, 2, 2, 3] ones = numpy.ones([3]) numpy.testing.assert_array_equal(selected[0, 0, 0, :].data.numpy(), ones) numpy.testing.assert_array_equal(selected[0, 0, 1, :].data.numpy(), ones * 2) numpy.testing.assert_array_equal(selected[0, 1, 0, :].data.numpy(), ones * 3) numpy.testing.assert_array_equal(selected[0, 1, 1, :].data.numpy(), ones * 4) numpy.testing.assert_array_equal(selected[1, 0, 0, :].data.numpy(), ones * 2) numpy.testing.assert_array_equal(selected[1, 0, 1, :].data.numpy(), ones * 4) numpy.testing.assert_array_equal(selected[1, 1, 0, :].data.numpy(), ones * 6) numpy.testing.assert_array_equal(selected[1, 1, 1, :].data.numpy(), ones * 8) # Check we only accept 2D indices. with pytest.raises(ConfigurationError): util.flattened_index_select(targets, torch.ones([3, 4, 5]))
Example #12
Source File: test_warnings.py From vnpy_crypto with MIT License | 6 votes |
def test_warning_calls(): # combined "ignore" and stacklevel error base = Path(numpy.__file__).parent for path in base.rglob("*.py"): if base / "testing" in path.parents: continue if path == base / "__init__.py": continue if path == base / "random" / "__init__.py": continue # use tokenize to auto-detect encoding on systems where no # default encoding is defined (e.g. LANG='C') with tokenize.open(str(path)) as file: tree = ast.parse(file.read()) FindFuncs(path).visit(tree)
Example #13
Source File: testutils.py From Mastering-Elasticsearch-7.0 with MIT License | 6 votes |
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """ Asserts that comparison between two masked arrays is satisfied. The comparison is elementwise. """ # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return np.testing.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header)
Example #14
Source File: test_hmm.py From razzy-spinner with GNU General Public License v3.0 | 6 votes |
def test_forward_probability2(): from numpy.testing import assert_array_almost_equal model, states, symbols, seq = _wikipedia_example_hmm() fp = 2**model._forward_probability(seq) # examples in wikipedia are normalized fp = (fp.T / fp.sum(axis=1)).T wikipedia_results = [ [0.8182, 0.1818], [0.8834, 0.1166], [0.1907, 0.8093], [0.7308, 0.2692], [0.8673, 0.1327], ] assert_array_almost_equal(wikipedia_results, fp, 4)
Example #15
Source File: LogisticRegressionTests.py From ufora with Apache License 2.0 | 6 votes |
def binary_logistic_regression_probabilities(self, method): X, y = self.exampleData() def f(): fit = BinaryLogisticRegressionFitter( C=1.0/len(X), hasIntercept=True, method=method ).fit(X, y) return fit.predict_probability(X) expectedPredictedProbabilities = [0.45810128, 0.58776695, 0.6510714] computedProbabilities = self.evaluateWithExecutor(f) numpy.testing.assert_allclose( computedProbabilities, expectedPredictedProbabilities, rtol=0.1 )
Example #16
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_sort_tensor_by_length(self): tensor = torch.rand([5, 7, 9]) tensor[0, 3:, :] = 0 tensor[1, 4:, :] = 0 tensor[2, 1:, :] = 0 tensor[3, 5:, :] = 0 sequence_lengths = torch.LongTensor([3, 4, 1, 5, 7]) sorted_tensor, sorted_lengths, reverse_indices, _ = util.sort_batch_by_length( tensor, sequence_lengths ) # Test sorted indices are padded correctly. numpy.testing.assert_array_equal(sorted_tensor[1, 5:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[2, 4:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[3, 3:, :].data.numpy(), 0.0) numpy.testing.assert_array_equal(sorted_tensor[4, 1:, :].data.numpy(), 0.0) assert sorted_lengths.data.equal(torch.LongTensor([7, 5, 4, 3, 1])) # Test restoration indices correctly recover the original tensor. assert sorted_tensor.index_select(0, reverse_indices).data.equal(tensor.data)
Example #17
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_weighted_sum_works_on_simple_input(self): batch_size = 1 sentence_length = 5 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, sentence_length, embedding_dim) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.FloatTensor([[0.3, 0.4, 0.1, 0, 1.2]]) aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, embedding_dim) expected_array = ( 0.3 * sentence_array[0, 0] + 0.4 * sentence_array[0, 1] + 0.1 * sentence_array[0, 2] + 0.0 * sentence_array[0, 3] + 1.2 * sentence_array[0, 4] ) numpy.testing.assert_almost_equal(aggregated_array, [expected_array], decimal=5)
Example #18
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_weighted_sum_handles_higher_order_input(self): batch_size = 1 length_1 = 5 length_2 = 6 length_3 = 2 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, length_1, length_2, length_3, embedding_dim) attention_array = numpy.random.rand(batch_size, length_1, length_2, length_3) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.from_numpy(attention_array).float() aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, length_1, length_2, embedding_dim) expected_array = ( attention_array[0, 3, 2, 0] * sentence_array[0, 3, 2, 0] + attention_array[0, 3, 2, 1] * sentence_array[0, 3, 2, 1] ) numpy.testing.assert_almost_equal(aggregated_array[0, 3, 2], expected_array, decimal=5)
Example #19
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_weighted_sum_handles_3d_attention_with_3d_matrix(self): batch_size = 1 length_1 = 5 length_2 = 2 embedding_dim = 4 sentence_array = numpy.random.rand(batch_size, length_2, embedding_dim) attention_array = numpy.random.rand(batch_size, length_1, length_2) sentence_tensor = torch.from_numpy(sentence_array).float() attention_tensor = torch.from_numpy(attention_array).float() aggregated_array = util.weighted_sum(sentence_tensor, attention_tensor).data.numpy() assert aggregated_array.shape == (batch_size, length_1, embedding_dim) for i in range(length_1): expected_array = ( attention_array[0, i, 0] * sentence_array[0, 0] + attention_array[0, i, 1] * sentence_array[0, 1] ) numpy.testing.assert_almost_equal(aggregated_array[0, i], expected_array, decimal=5)
Example #20
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_sequence_cross_entropy_with_logits_smooths_labels_correctly(self): tensor = torch.rand([1, 3, 4]) targets = torch.LongTensor(numpy.random.randint(0, 3, [1, 3])) weights = torch.ones([2, 3]) loss = util.sequence_cross_entropy_with_logits( tensor, targets, weights, label_smoothing=0.1 ) correct_loss = 0.0 for prediction, label in zip(tensor.squeeze(0), targets.squeeze(0)): prediction = torch.nn.functional.log_softmax(prediction, dim=-1) correct_loss += prediction[label] * 0.9 # incorrect elements correct_loss += prediction.sum() * 0.1 / 4 # Average over sequence. correct_loss = -correct_loss / 3 numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy())
Example #21
Source File: NumpyTestCases.py From ufora with Apache License 2.0 | 6 votes |
def test_numpy_dot_product_2b(self): random.seed(44) listLength = 20 arr1 = [random.uniform(-10, 10) for _ in range(0, listLength)] arr2 = [random.uniform(-10, 10) for _ in range(0, listLength)] def f(): a = numpy.array(arr1) b = numpy.array(arr2) return a.dot(b) r1 = self.evaluateWithExecutor(f) r2 = f() numpy.testing.assert_allclose(r1, r2)
Example #22
Source File: NumpyTestCases.py From ufora with Apache License 2.0 | 6 votes |
def test_numpy_dot_product_2a(self): random.seed(44) listLength = 20 arr1 = [random.uniform(-10, 10) for _ in range(0, listLength)] arr2 = [random.uniform(-10, 10) for _ in range(0, listLength)] def f(): a = numpy.array(arr1) b = numpy.array(arr2) return numpy.dot(a, b) r1 = self.evaluateWithExecutor(f) r2 = f() numpy.testing.assert_allclose(r1, r2)
Example #23
Source File: util_test.py From allennlp with Apache License 2.0 | 6 votes |
def test_sequence_cross_entropy_with_logits_gamma_correctly(self): batch = 1 length = 3 classes = 4 gamma = abs(numpy.random.randn()) # [0, +inf) tensor = torch.rand([batch, length, classes]) targets = torch.LongTensor(numpy.random.randint(0, classes, [batch, length])) weights = torch.ones([batch, length]) loss = util.sequence_cross_entropy_with_logits(tensor, targets, weights, gamma=gamma) correct_loss = 0.0 for logit, label in zip(tensor.squeeze(0), targets.squeeze(0)): p = torch.nn.functional.softmax(logit, dim=-1) pt = p[label] ft = (1 - pt) ** gamma correct_loss += -pt.log() * ft # Average over sequence. correct_loss = correct_loss / length numpy.testing.assert_array_almost_equal(loss.data.numpy(), correct_loss.data.numpy())
Example #24
Source File: testutils.py From vnpy_crypto with MIT License | 6 votes |
def assert_array_compare(comparison, x, y, err_msg='', verbose=True, header='', fill_value=True): """ Asserts that comparison between two masked arrays is satisfied. The comparison is elementwise. """ # Allocate a common mask and refill m = mask_or(getmask(x), getmask(y)) x = masked_array(x, copy=False, mask=m, keep_mask=False, subok=False) y = masked_array(y, copy=False, mask=m, keep_mask=False, subok=False) if ((x is masked) and not (y is masked)) or \ ((y is masked) and not (x is masked)): msg = build_err_msg([x, y], err_msg=err_msg, verbose=verbose, header=header, names=('x', 'y')) raise ValueError(msg) # OK, now run the basic tests on filled versions return np.testing.assert_array_compare(comparison, x.filled(fill_value), y.filled(fill_value), err_msg=err_msg, verbose=verbose, header=header)
Example #25
Source File: LogisticRegressionTests.py From ufora with Apache License 2.0 | 5 votes |
def binary_logistic_regression_coefficients(self, method): X, y = self.exampleData() def f(): fit = BinaryLogisticRegressionFitter( C=1.0/len(X), hasIntercept=True, method=method ).fit(X, y) return fit.intercept, fit.coefficients computedIntercept, computedCoefficients = self.evaluateWithExecutor(f) expectedIntercept = -0.10102151 expectedCoefficients = numpy.array([-0.26901034, -0.25372016]) numpy.testing.assert_almost_equal( computedIntercept, expectedIntercept, decimal=4 ) numpy.testing.assert_allclose( computedCoefficients, expectedCoefficients, rtol=0.1 )
Example #26
Source File: util_test.py From allennlp with Apache License 2.0 | 5 votes |
def test_get_sequence_lengths_from_binary_mask(self): binary_mask = torch.tensor( [ [True, True, True, False, False, False], [True, True, False, False, False, False], [True, True, True, True, True, True], [True, False, False, False, False, False], ] ) lengths = util.get_lengths_from_binary_sequence_mask(binary_mask) numpy.testing.assert_array_equal(lengths.numpy(), numpy.array([3, 2, 6, 1]))
Example #27
Source File: asserts.py From afnumpy with BSD 2-Clause "Simplified" License | 5 votes |
def fassert(af_a, np_a): numpy.testing.assert_allclose(numpy.array(af_a), np_a) massert(af_a, np_a)
Example #28
Source File: LogisticRegressionTests.py From ufora with Apache License 2.0 | 5 votes |
def binary_logistic_regression_predict(self, method): X, y = self.exampleData() def f(): fit = BinaryLogisticRegressionFitter( C=1.0/len(X), hasIntercept=True, method=method ).fit(X, y) return fit.predict(X) numpy.testing.assert_array_equal( self.evaluateWithExecutor(f), numpy.array([0, 1, 1]) )
Example #29
Source File: util_test.py From allennlp with Apache License 2.0 | 5 votes |
def test_bucket_values(self): indices = torch.LongTensor([1, 2, 7, 1, 56, 900]) bucketed_distances = util.bucket_values(indices) numpy.testing.assert_array_equal( bucketed_distances.numpy(), numpy.array([1, 2, 5, 1, 8, 9]) )
Example #30
Source File: ScipySpecialTestCases.py From ufora with Apache License 2.0 | 5 votes |
def test_betaln_2(self): def f(a, b): return scipy.special.betaln(a, b) res1 = self.evaluateWithExecutor(f, 2, 4) res2 = numpy.log(abs(scipy.special.beta(2,4))) numpy.testing.assert_almost_equal(res1, res2, 8)