class ParameterTest(unittest.TestCase): @classmethod def setUpClass(cls): pass @classmethod def tearDownClass(cls): pass def setUp(self): self.dev = D.Naive() Device.set_default(self.dev) self.p = Parameter([8], I.Constant(0)) self.p.value.reset_by_vector([1, 2, 3, 4, 5, 6, 7, 8]) def tearDown(self): pass def test_parameter_stats(self): self.p.add_stats("stat1", Shape([2, 3])) self.p.add_stats("stat2", Shape([2, 4])) st1 = self.p.stats["stat1"] st1.reset(0) self.assertTrue((st1.to_ndarrays()[0] == np.zeros([2, 3])).all()) self.p.stats["stat1"] = tF.input(np.ones([2, 3])) self.assertTrue((st1.to_ndarrays()[0] == np.ones([2, 3])).all()) self.assertIn("stat1", self.p.stats) self.assertIn("stat2", self.p.stats) self.assertNotIn("stat3", self.p.stats) with self.assertRaises(NotImplementedError): del self.p.stats["stat1"] with self.assertRaises(AttributeError): self.p.stats = ParameterStatistics(self.p) def test_parameter_value(self): self.assertTrue( (self.p.value.to_ndarrays() == np.array([1, 2, 3, 4, 5, 6, 7, 8])).all()) val = self.p.value self.p.value += tF.input(np.ones([8])) self.assertTrue( (val.to_ndarrays()[0] == np.array([2, 3, 4, 5, 6, 7, 8, 9])).all()) with self.assertRaises(NotImplementedError): del self.p.value def test_parameter_gradient(self): self.p.reset_gradient() self.assertTrue((self.p.gradient.to_ndarrays() == np.zeros([8])).all()) grad = self.p.gradient self.p.gradient += tF.input(np.ones([8])) self.assertTrue((grad.to_ndarrays()[0] == np.ones([8])).all()) with self.assertRaises(NotImplementedError): del self.p.gradient
def test_ModelTest_CheckSaveLoadWithStats(self): shape = Shape([2, 2]) values1 = [1, 2, 3, 4] values2 = [5, 6, 7, 8] stats1 = [10, 20, 30, 40] stats2 = [50, 60, 70, 80] tmp = tempfile.NamedTemporaryFile() m1 = Model() m2 = Model() p1 = Parameter(shape, I.Constant(0)) p1.value += tF.raw_input(shape, values1) p2 = Parameter(shape, I.Constant(0)) p2.value += tF.raw_input(shape, values2) p1.add_stats("a", shape) p2.add_stats("b", shape) p1.stats["a"].reset_by_vector(stats1); p2.stats["b"].reset_by_vector(stats2); m1.add("p", p1) m2.add("p", p2) m1.add("sm", m2) m1.save(tmp.name) m1 = Model() m2 = Model() p1 = Parameter() p2 = Parameter() m1.add("p", p1) m2.add("p", p2) m1.add("sm", m2) m1.load(tmp.name) self.assertTrue(p1.valid()) self.assertTrue(p2.valid()) self.assertEqual(shape, p1.shape()) self.assertEqual(shape, p2.shape()) self.assertEqual(values1, p1.value.to_list()) self.assertEqual(values2, p2.value.to_list()) self.assertTrue("a" in p1.stats) self.assertTrue("b" in p2.stats) self.assertEqual(stats1, p1.stats["a"].to_list()) self.assertEqual(stats2, p2.stats["b"].to_list())