pytorch

Форк
0
/
histogram_test.py 
85 строк · 3.0 Кб
1
import unittest
2

3
import caffe2.python.hypothesis_test_util as hu
4
import hypothesis.strategies as st
5
import numpy as np
6
from caffe2.python import core, workspace
7
from hypothesis import given, settings
8

9

10
class TestHistogram(hu.HypothesisTestCase):
11
    @given(rows=st.integers(1, 1000), cols=st.integers(1, 1000), **hu.gcs_cpu_only)
12
    @settings(deadline=10000)
13
    def test_histogram__device_consistency(self, rows, cols, gc, dc):
14
        X = np.random.rand(rows, cols)
15
        bin_edges = list(np.linspace(-2, 10, num=10000))
16
        op = core.CreateOperator("Histogram", ["X"], ["histogram"], bin_edges=bin_edges)
17
        self.assertDeviceChecks(dc, op, [X], [0])
18

19
    def test_histogram__valid_inputs_0(self):
20
        workspace.FeedBlob(
21
            "X", np.array([-2.0, -2.0, 0.0, 0.0, 0.0, 1.0, 2.0, 3.0, 4.0, 6.0, 9.0])
22
        )
23
        bin_edges = [-2.0, -1.0, 0.0, 2.0, 5.0, 9.0]
24

25
        net = core.Net("test_net")
26
        net.Histogram(["X"], ["histogram"], bin_edges=bin_edges)
27

28
        workspace.RunNetOnce(net)
29
        histogram_blob = workspace.FetchBlob("histogram")
30

31
        assert list(histogram_blob) == [2, 0, 4, 3, 1]
32

33
    @given(num_tensors=st.integers(1, 5), num_bin_edges=st.integers(2, 10000))
34
    @settings(deadline=10000)
35
    def test_histogram__valid_inputs_1(self, num_tensors, num_bin_edges):
36
        self._test_histogram(
37
            [
38
                np.random.rand(np.random.randint(1, 1000), np.random.randint(1, 1000))
39
                for __ in range(num_tensors)
40
            ],
41
            list(np.logspace(-12, 5, num=num_bin_edges)),
42
        )
43

44
    def test_histogram__empty_input_tensor(self):
45
        self._test_histogram([np.array([])], list(np.linspace(-2, 2, num=10)))
46

47
    def test_histogram__non_increasing_bin_edges(self):
48
        with self.assertRaisesRegex(
49
            RuntimeError, "bin_edges must be a strictly increasing sequence of values"
50
        ):
51
            self._test_histogram(
52
                [np.random.rand(100), np.random.rand(98)], [0.0, 0.2, 0.1, 0.1]
53
            )
54

55
    def test_histogram__insufficient_bin_edges(self):
56
        with self.assertRaisesRegex(
57
            RuntimeError, "Number of bin edges must be greater than or equal to 2"
58
        ):
59
            self._test_histogram([np.random.rand(111)], [1.0])
60

61
    def _test_histogram(self, tensors, bin_edges):
62
        total_size = 0
63
        input_blob_names = []
64

65
        for idx, tensor in enumerate(tensors):
66
            total_size += np.size(tensor)
67
            tensor_blob_name = f"X{idx}"
68
            workspace.FeedBlob(tensor_blob_name, tensor)
69
            input_blob_names.append(tensor_blob_name)
70

71
        output_name = "histogram"
72
        net = core.Net("test_net")
73
        net.Histogram(input_blob_names, [output_name], bin_edges=bin_edges)
74

75
        workspace.RunNetOnce(net)
76
        histogram_blob = workspace.FetchBlob(output_name)
77

78
        assert np.size(histogram_blob) == len(bin_edges) - 1
79
        assert np.sum(histogram_blob) == total_size
80

81

82
if __name__ == "__main__":
83
    global_options = ["caffe2"]
84
    core.GlobalInit(global_options)
85
    unittest.main()
86

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.