pytorch
84 строки · 3.2 Кб
1
2
3import unittest
4
5import caffe2.python.hypothesis_test_util as hu
6import numpy as np
7from caffe2.python import core, workspace
8
9
10class TestQuantile(hu.HypothesisTestCase):
11def _test_quantile(self, inputs, quantile, abs, tol):
12net = core.Net("test_net")
13net.Proto().type = "dag"
14input_tensors = []
15for i, input in enumerate(inputs):
16workspace.FeedBlob("t_{}".format(i), input)
17input_tensors.append("t_{}".format(i))
18net.Quantile(
19input_tensors, ["quantile_value"], quantile=quantile, abs=abs, tol=tol
20)
21workspace.RunNetOnce(net)
22quantile_value_blob = workspace.FetchBlob("quantile_value")
23assert np.size(quantile_value_blob) == 1
24quantile_value = quantile_value_blob[0]
25
26input_cat = np.concatenate([input.flatten() for input in inputs])
27input_cat = np.abs(input_cat) if abs == 1 else input_cat
28target_cnt = np.ceil(np.size(input_cat) * quantile)
29actual_cnt = np.sum(input_cat <= quantile_value)
30# prune with return value will remove no less than
31# "quantile" portion of elements
32assert actual_cnt >= target_cnt
33# Expect that (hi-lo) < tol * (|lo| + |hi|)
34# if tol < 1.0 -> hi * lo > 0, then we are expecting
35# 1. if hi >0,
36# |hi|-|lo| < tol * (|lo| + |hi|)
37# hi - lo < (2 tol) /(1 + tol) |hi| < 2 tol |hi|
38# 2. if hi < 0,
39# |lo|- |hi| < tol * (|lo| + |hi|)
40# hi - lo < (2 tol) /(1 - tol) |hi| < 2.5 tol |hi| if tol < 0.2
41quantile_value_lo = quantile_value - 2.5 * tol * np.abs(quantile_value)
42lo_cnt = np.sum(input_cat <= quantile_value_lo)
43# prune with a slightly smaller value will remove
44# less than "quantile" portion of elements
45assert lo_cnt <= target_cnt
46
47def test_quantile_1(self):
48inputs = []
49num_tensors = 5
50for i in range(num_tensors):
51dim = np.random.randint(5, 100)
52inputs.append(np.random.rand(dim))
53self._test_quantile(inputs=inputs, quantile=0.2, abs=1, tol=1e-4)
54
55def test_quantile_2(self):
56inputs = []
57num_tensors = 5
58for i in range(num_tensors):
59dim = np.random.randint(5, 100)
60inputs.append(np.random.rand(dim))
61self._test_quantile(inputs=inputs, quantile=1e-6, abs=0, tol=1e-3)
62
63def test_quantile_3(self):
64inputs = []
65num_tensors = 5
66for i in range(num_tensors):
67dim1 = np.random.randint(5, 100)
68dim2 = np.random.randint(5, 100)
69inputs.append(np.random.rand(dim1, dim2))
70self._test_quantile(inputs=inputs, quantile=1 - 1e-6, abs=1, tol=1e-5)
71
72def test_quantile_4(self):
73inputs = []
74num_tensors = 5
75for i in range(num_tensors):
76dim1 = np.random.randint(5, 100)
77dim2 = np.random.randint(5, 100)
78inputs.append(np.random.rand(dim1, dim2))
79inputs.append(np.random.rand(dim1))
80self._test_quantile(inputs=inputs, quantile=0.168, abs=1, tol=1e-4)
81
82
83if __name__ == "__main__":
84global_options = ["caffe2"]
85core.GlobalInit(global_options)
86unittest.main()
87