pytorch
85 строк · 3.0 Кб
1import unittest2
3import caffe2.python.hypothesis_test_util as hu4import hypothesis.strategies as st5import numpy as np6from caffe2.python import core, workspace7from hypothesis import given, settings8
9
10class TestHistogram(hu.HypothesisTestCase):11@given(rows=st.integers(1, 1000), cols=st.integers(1, 1000), **hu.gcs_cpu_only)12@settings(deadline=10000)13def test_histogram__device_consistency(self, rows, cols, gc, dc):14X = np.random.rand(rows, cols)15bin_edges = list(np.linspace(-2, 10, num=10000))16op = core.CreateOperator("Histogram", ["X"], ["histogram"], bin_edges=bin_edges)17self.assertDeviceChecks(dc, op, [X], [0])18
19def test_histogram__valid_inputs_0(self):20workspace.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)23bin_edges = [-2.0, -1.0, 0.0, 2.0, 5.0, 9.0]24
25net = core.Net("test_net")26net.Histogram(["X"], ["histogram"], bin_edges=bin_edges)27
28workspace.RunNetOnce(net)29histogram_blob = workspace.FetchBlob("histogram")30
31assert 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)35def test_histogram__valid_inputs_1(self, num_tensors, num_bin_edges):36self._test_histogram(37[38np.random.rand(np.random.randint(1, 1000), np.random.randint(1, 1000))39for __ in range(num_tensors)40],41list(np.logspace(-12, 5, num=num_bin_edges)),42)43
44def test_histogram__empty_input_tensor(self):45self._test_histogram([np.array([])], list(np.linspace(-2, 2, num=10)))46
47def test_histogram__non_increasing_bin_edges(self):48with self.assertRaisesRegex(49RuntimeError, "bin_edges must be a strictly increasing sequence of values"50):51self._test_histogram(52[np.random.rand(100), np.random.rand(98)], [0.0, 0.2, 0.1, 0.1]53)54
55def test_histogram__insufficient_bin_edges(self):56with self.assertRaisesRegex(57RuntimeError, "Number of bin edges must be greater than or equal to 2"58):59self._test_histogram([np.random.rand(111)], [1.0])60
61def _test_histogram(self, tensors, bin_edges):62total_size = 063input_blob_names = []64
65for idx, tensor in enumerate(tensors):66total_size += np.size(tensor)67tensor_blob_name = f"X{idx}"68workspace.FeedBlob(tensor_blob_name, tensor)69input_blob_names.append(tensor_blob_name)70
71output_name = "histogram"72net = core.Net("test_net")73net.Histogram(input_blob_names, [output_name], bin_edges=bin_edges)74
75workspace.RunNetOnce(net)76histogram_blob = workspace.FetchBlob(output_name)77
78assert np.size(histogram_blob) == len(bin_edges) - 179assert np.sum(histogram_blob) == total_size80
81
82if __name__ == "__main__":83global_options = ["caffe2"]84core.GlobalInit(global_options)85unittest.main()86