|
| 1 | +#!/usr/bin/env python3 |
| 2 | + |
| 3 | +import unittest |
| 4 | + |
| 5 | +from torch import Tensor |
| 6 | + |
| 7 | +from gpytorch.priors import GammaPrior, HalfCauchyPrior, LogNormalPrior, NormalPrior |
| 8 | + |
| 9 | + |
| 10 | +TRANSFORMED_ERROR_MSG = """Priors of TransformedDistributions should not have their \ |
| 11 | +'_transformed' attributes modified, these are just copies of the base attribute. \ |
| 12 | +Please modify the base attribute (e.g. {}) instead.""" |
| 13 | + |
| 14 | + |
| 15 | +class TestPrior(unittest.TestCase): |
| 16 | + def test_state_dict(self): |
| 17 | + normal = NormalPrior(0.1, 1).state_dict() |
| 18 | + self.assertTrue("loc" in normal) |
| 19 | + self.assertTrue("scale" in normal) |
| 20 | + self.assertEqual(normal["loc"], 0.1) |
| 21 | + |
| 22 | + gamma = GammaPrior(1.1, 2).state_dict() |
| 23 | + self.assertTrue("concentration" in gamma) |
| 24 | + self.assertTrue("rate" in gamma) |
| 25 | + self.assertEqual(gamma["concentration"], 1.1) |
| 26 | + |
| 27 | + ln = LogNormalPrior(2.1, 1.2).state_dict() |
| 28 | + self.assertTrue("_transformed_loc" in ln) |
| 29 | + self.assertTrue("_transformed_scale" in ln) |
| 30 | + self.assertEqual(ln["_transformed_loc"], 2.1) |
| 31 | + |
| 32 | + hc = HalfCauchyPrior(1.3).state_dict() |
| 33 | + self.assertTrue("_transformed_scale" in hc) |
| 34 | + |
| 35 | + def test_load_state_dict(self): |
| 36 | + ln1 = LogNormalPrior(loc=0.5, scale=0.1) |
| 37 | + ln2 = LogNormalPrior(loc=2.5, scale=2.1) |
| 38 | + gm1 = GammaPrior(concentration=0.5, rate=0.1) |
| 39 | + gm2 = GammaPrior(concentration=2.5, rate=2.1) |
| 40 | + hc1 = HalfCauchyPrior(scale=1.1) |
| 41 | + hc2 = HalfCauchyPrior(scale=101.1) |
| 42 | + |
| 43 | + ln2.load_state_dict(ln1.state_dict()) |
| 44 | + self.assertEqual(ln2.loc, ln1.loc) |
| 45 | + self.assertEqual(ln2.scale, ln1.scale) |
| 46 | + |
| 47 | + gm2.load_state_dict(gm1.state_dict()) |
| 48 | + self.assertEqual(gm2.concentration, gm1.concentration) |
| 49 | + self.assertEqual(gm2.rate, gm1.rate) |
| 50 | + |
| 51 | + hc2.load_state_dict(hc1.state_dict()) |
| 52 | + self.assertEqual(hc2.scale, hc1.scale) |
| 53 | + |
| 54 | + def test_transformed_attributes(self): |
| 55 | + norm = NormalPrior(loc=2.5, scale=2.1) |
| 56 | + ln = LogNormalPrior(loc=2.5, scale=2.1) |
| 57 | + hc = HalfCauchyPrior(scale=2.2) |
| 58 | + |
| 59 | + with self.assertRaisesRegex(AttributeError, "'NormalPrior' object has no attribute '_transformed_loc'"): |
| 60 | + getattr(norm, "_transformed_loc") |
| 61 | + |
| 62 | + self.assertTrue(getattr(ln, "_transformed_loc"), 2.5) |
| 63 | + norm.loc = Tensor([1.01]) |
| 64 | + ln.loc = Tensor([1.01]) |
| 65 | + self.assertEqual(ln._transformed_loc, 1.01) |
| 66 | + with self.assertRaises(AttributeError): |
| 67 | + ln._transformed_loc = 1.1 |
| 68 | + |
| 69 | + with self.assertRaises(AttributeError): |
| 70 | + hc._transformed_scale = 1.01 |
0 commit comments