|
| 1 | +import unittest |
| 2 | +import sys |
| 3 | + |
| 4 | +try: |
| 5 | + import py_paddle |
| 6 | + |
| 7 | + del py_paddle |
| 8 | +except ImportError: |
| 9 | + print >> sys.stderr, "It seems swig of Paddle is not installed, this " \ |
| 10 | + "unittest will not be run." |
| 11 | + sys.exit(0) |
| 12 | + |
| 13 | +import paddle.v2.parameters as parameters |
| 14 | +from paddle.proto.ParameterConfig_pb2 import ParameterConfig |
| 15 | +import random |
| 16 | +import cStringIO |
| 17 | +import numpy |
| 18 | + |
| 19 | + |
| 20 | +def __rand_param_config__(name): |
| 21 | + conf = ParameterConfig() |
| 22 | + conf.name = name |
| 23 | + size = 1 |
| 24 | + for i in xrange(2): |
| 25 | + dim = random.randint(1, 1000) |
| 26 | + conf.dims.append(dim) |
| 27 | + size *= dim |
| 28 | + conf.size = size |
| 29 | + assert conf.IsInitialized() |
| 30 | + return conf |
| 31 | + |
| 32 | + |
| 33 | +class TestParameters(unittest.TestCase): |
| 34 | + def test_serialization(self): |
| 35 | + params = parameters.Parameters() |
| 36 | + params.__append_config__(__rand_param_config__("param_0")) |
| 37 | + params.__append_config__(__rand_param_config__("param_1")) |
| 38 | + |
| 39 | + for name in params.names(): |
| 40 | + param = params.get(name) |
| 41 | + param[:] = numpy.random.uniform( |
| 42 | + -1.0, 1.0, size=params.get_shape(name)) |
| 43 | + params.set(name, param) |
| 44 | + |
| 45 | + tmp_file = cStringIO.StringIO() |
| 46 | + params.to_tar(tmp_file) |
| 47 | + tmp_file.seek(0) |
| 48 | + params_dup = parameters.Parameters.from_tar(tmp_file) |
| 49 | + |
| 50 | + self.assertEqual(params_dup.names(), params.names()) |
| 51 | + |
| 52 | + for name in params.names(): |
| 53 | + self.assertEqual(params.get_shape(name), params_dup.get_shape(name)) |
| 54 | + p0 = params.get(name) |
| 55 | + p1 = params_dup.get(name) |
| 56 | + self.assertTrue(numpy.isclose(p0, p1).all()) |
| 57 | + |
| 58 | + |
| 59 | +if __name__ == '__main__': |
| 60 | + unittest.main() |
0 commit comments