You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

test_monomial.py 25 kB

first commit Former-commit-id: 08bc23ba02cffbce3cf63962390a65459a132e48 [formerly 0795edd4834b9b7dc66db8d10d4cbaf42bbf82cb] [formerly b5010b42541add7e2ea2578bf2da537efc457757 [formerly a7ca09c2c34c4fc8b3d8e01fcfa08eeeb2cae99d]] [formerly 615058473a2177ca5b89e9edbb797f4c2a59c7e5 [formerly 743d8dfc6843c4c205051a8ab309fbb2116c895e] [formerly bb0ea98b1e14154ef464e2f7a16738705894e54b [formerly 960a69da74b81ef8093820e003f2d6c59a34974c]]] [formerly 2fa3be52c1b44665bc81a7cc7d4cea4bbf0d91d5 [formerly 2054589f0898627e0a17132fd9d4cc78efc91867] [formerly 3b53730e8a895e803dfdd6ca72bc05e17a4164c1 [formerly 8a2fa8ab7baf6686d21af1f322df46fd58c60e69]] [formerly 87d1e3a07a19d03c7d7c94d93ab4fa9f58dada7c [formerly f331916385a5afac1234854ee8d7f160f34b668f] [formerly 69fb3c78a483343f5071da4f7e2891b83a49dd18 [formerly 386086f05aa9487f65bce2ee54438acbdce57650]]]] Former-commit-id: a00aed8c934a6460c4d9ac902b9a74a3d6864697 [formerly 26fdeca29c2f07916d837883983ca2982056c78e] [formerly 0e3170d41a2f99ecf5c918183d361d4399d793bf [formerly 3c12ad4c88ac5192e0f5606ac0d88dd5bf8602dc]] [formerly d5894f84f2fd2e77a6913efdc5ae388cf1be0495 [formerly ad3e7bc670ff92c992730d29c9d3aa1598d844e8] [formerly 69fb3c78a483343f5071da4f7e2891b83a49dd18]] Former-commit-id: 3c19c9fae64f6106415fbc948a4dc613b9ee12f8 [formerly 467ddc0549c74bb007e8f01773bb6dc9103b417d] [formerly 5fa518345d958e2760e443b366883295de6d991c [formerly 3530e130b9fdb7280f638dbc2e785d2165ba82aa]] Former-commit-id: 9f5d473d42a435ec0d60149939d09be1acc25d92 [formerly be0b25c4ec2cde052a041baf0e11f774a158105d] Former-commit-id: 9eca71cb73ba9edccd70ac06a3b636b8d4093b04
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import json
  2. import pickle
  3. import unittest
  4. import os.path
  5. import sys
  6. import d3m
  7. from d3m import container, utils
  8. from d3m.metadata import base
  9. TEST_PRIMITIVES_DIR = os.path.join(os.path.dirname(__file__), 'data', 'primitives')
  10. sys.path.insert(0, TEST_PRIMITIVES_DIR)
  11. from test_primitives.monomial import MonomialPrimitive
  12. EXPECTED_PRIMITIVE_DESCRIPTION_JSON = r"""
  13. {
  14. "id": "4a0336ae-63b9-4a42-860e-86c5b64afbdd",
  15. "version": "0.1.0",
  16. "name": "Monomial Regressor",
  17. "keywords": [
  18. "test primitive"
  19. ],
  20. "source": {
  21. "name": "Test team",
  22. "contact": "mailto:author@example.com",
  23. "uris": [
  24. "https://gitlab.com/datadrivendiscovery/tests-data/blob/master/primitives/test_primitives/monomial.py",
  25. "https://gitlab.com/datadrivendiscovery/tests-data.git"
  26. ]
  27. },
  28. "installation": [
  29. {
  30. "type": "PIP",
  31. "package_uri": "git+https://gitlab.com/datadrivendiscovery/tests-data.git@__GIT_COMMIT__#egg=test_primitives&subdirectory=primitives"
  32. }
  33. ],
  34. "location_uris": [
  35. "https://gitlab.com/datadrivendiscovery/tests-data/raw/__GIT_COMMIT__/primitives/test_primitives/monomial.py"
  36. ],
  37. "python_path": "d3m.primitives.regression.monomial.Test",
  38. "algorithm_types": [
  39. "LINEAR_REGRESSION"
  40. ],
  41. "primitive_family": "REGRESSION",
  42. "schema": "https://metadata.datadrivendiscovery.org/schemas/v0/primitive.json",
  43. "original_python_path": "test_primitives.monomial.MonomialPrimitive",
  44. "primitive_code": {
  45. "class_type_arguments": {
  46. "Inputs": "d3m.container.list.List",
  47. "Outputs": "d3m.container.list.List",
  48. "Params": "test_primitives.monomial.Params",
  49. "Hyperparams": "test_primitives.monomial.Hyperparams"
  50. },
  51. "interfaces_version": "__INTERFACES_VERSION__",
  52. "interfaces": [
  53. "supervised_learning.SupervisedLearnerPrimitiveBase",
  54. "base.PrimitiveBase"
  55. ],
  56. "hyperparams": {
  57. "bias": {
  58. "type": "d3m.metadata.hyperparams.Hyperparameter",
  59. "default": 0.0,
  60. "structural_type": "float",
  61. "semantic_types": [
  62. "https://metadata.datadrivendiscovery.org/types/TuningParameter"
  63. ]
  64. }
  65. },
  66. "arguments": {
  67. "hyperparams": {
  68. "type": "test_primitives.monomial.Hyperparams",
  69. "kind": "RUNTIME"
  70. },
  71. "timeout": {
  72. "type": "typing.Union[NoneType, float]",
  73. "kind": "RUNTIME",
  74. "default": null
  75. },
  76. "iterations": {
  77. "type": "typing.Union[NoneType, int]",
  78. "kind": "RUNTIME",
  79. "default": null
  80. },
  81. "produce_methods": {
  82. "type": "typing.Sequence[str]",
  83. "kind": "RUNTIME"
  84. },
  85. "random_seed": {
  86. "default": 0,
  87. "kind": "RUNTIME",
  88. "type": "int"
  89. },
  90. "inputs": {
  91. "type": "d3m.container.list.List",
  92. "kind": "PIPELINE"
  93. },
  94. "outputs": {
  95. "type": "d3m.container.list.List",
  96. "kind": "PIPELINE"
  97. },
  98. "params": {
  99. "type": "test_primitives.monomial.Params",
  100. "kind": "RUNTIME"
  101. }
  102. },
  103. "class_methods": {},
  104. "instance_methods": {
  105. "__init__": {
  106. "kind": "OTHER",
  107. "arguments": [
  108. "hyperparams",
  109. "random_seed"
  110. ],
  111. "returns": "NoneType"
  112. },
  113. "fit": {
  114. "kind": "OTHER",
  115. "arguments": [
  116. "timeout",
  117. "iterations"
  118. ],
  119. "returns": "d3m.primitive_interfaces.base.CallResult[NoneType]",
  120. "description": "Fits primitive using inputs and outputs (if any) using currently set training data.\n\nThe returned value should be a ``CallResult`` object with ``value`` set to ``None``.\n\nIf ``fit`` has already been called in the past on different training data,\nthis method fits it **again from scratch** using currently set training data.\n\nOn the other hand, caller can call ``fit`` multiple times on the same training data\nto continue fitting.\n\nIf ``fit`` fully fits using provided training data, there is no point in making further\ncalls to this method with same training data, and in fact further calls can be noops,\nor a primitive can decide to fully refit from scratch.\n\nIn the case fitting can continue with same training data (even if it is maybe not reasonable,\nbecause the internal metric primitive is using looks like fitting will be degrading), if ``fit``\nis called again (without setting training data), the primitive has to continue fitting.\n\nCaller can provide ``timeout`` information to guide the length of the fitting process.\nIdeally, a primitive should adapt its fitting process to try to do the best fitting possible\ninside the time allocated. If this is not possible and the primitive reaches the timeout\nbefore fitting, it should raise a ``TimeoutError`` exception to signal that fitting was\nunsuccessful in the given time. The state of the primitive after the exception should be\nas the method call has never happened and primitive should continue to operate normally.\nThe purpose of ``timeout`` is to give opportunity to a primitive to cleanly manage\nits state instead of interrupting execution from outside. Maintaining stable internal state\nshould have precedence over respecting the ``timeout`` (caller can terminate the misbehaving\nprimitive from outside anyway). If a longer ``timeout`` would produce different fitting,\nthen ``CallResult``'s ``has_finished`` should be set to ``False``.\n\nSome primitives have internal fitting iterations (for example, epochs). For those, caller\ncan provide how many of primitive's internal iterations should a primitive do before returning.\nPrimitives should make iterations as small as reasonable. If ``iterations`` is ``None``,\nthen there is no limit on how many iterations the primitive should do and primitive should\nchoose the best amount of iterations on its own (potentially controlled through\nhyper-parameters). If ``iterations`` is a number, a primitive has to do those number of\niterations (even if not reasonable), if possible. ``timeout`` should still be respected\nand potentially less iterations can be done because of that. Primitives with internal\niterations should make ``CallResult`` contain correct values.\n\nFor primitives which do not have internal iterations, any value of ``iterations``\nmeans that they should fit fully, respecting only ``timeout``.\n\nParameters\n----------\ntimeout:\n A maximum time this primitive should be fitting during this method call, in seconds.\niterations:\n How many of internal iterations should the primitive do.\n\nReturns\n-------\nA ``CallResult`` with ``None`` value."
  121. },
  122. "fit_multi_produce": {
  123. "kind": "OTHER",
  124. "arguments": [
  125. "produce_methods",
  126. "inputs",
  127. "outputs",
  128. "timeout",
  129. "iterations"
  130. ],
  131. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  132. "description": "A method calling ``fit`` and after that multiple produce methods at once.\n\nThis method allows primitive author to implement an optimized version of both fitting\nand producing a primitive on same data.\n\nIf any additional method arguments are added to primitive's ``set_training_data`` method\nor produce method(s), or removed from them, they have to be added to or removed from this\nmethod as well. This method should accept an union of all arguments accepted by primitive's\n``set_training_data`` method and produce method(s) and then use them accordingly when\ncomputing results.\n\nThe default implementation of this method just calls first ``set_training_data`` method,\n``fit`` method, and all produce methods listed in ``produce_methods`` in order and is\npotentially inefficient.\n\nParameters\n----------\nproduce_methods:\n A list of names of produce methods to call.\ninputs:\n The inputs given to ``set_training_data`` and all produce methods.\noutputs:\n The outputs given to ``set_training_data``.\ntimeout:\n A maximum time this primitive should take to both fit the primitive and produce outputs\n for all produce methods listed in ``produce_methods`` argument, in seconds.\niterations:\n How many of internal iterations should the primitive do for both fitting and producing\n outputs of all produce methods.\n\nReturns\n-------\nA dict of values for each produce method wrapped inside ``MultiCallResult``."
  133. },
  134. "get_params": {
  135. "kind": "OTHER",
  136. "arguments": [],
  137. "returns": "test_primitives.monomial.Params",
  138. "description": "Returns parameters of this primitive.\n\nParameters are all parameters of the primitive which can potentially change during a life-time of\na primitive. Parameters which cannot are passed through constructor.\n\nParameters should include all data which is necessary to create a new instance of this primitive\nbehaving exactly the same as this instance, when the new instance is created by passing the same\nparameters to the class constructor and calling ``set_params``.\n\nNo other arguments to the method are allowed (except for private arguments).\n\nReturns\n-------\nAn instance of parameters."
  139. },
  140. "multi_produce": {
  141. "kind": "OTHER",
  142. "arguments": [
  143. "produce_methods",
  144. "inputs",
  145. "timeout",
  146. "iterations"
  147. ],
  148. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  149. "description": "A method calling multiple produce methods at once.\n\nWhen a primitive has multiple produce methods it is common that they might compute the\nsame internal results for same inputs but return different representations of those results.\nIf caller is interested in multiple of those representations, calling multiple produce\nmethods might lead to recomputing same internal results multiple times. To address this,\nthis method allows primitive author to implement an optimized version which computes\ninternal results only once for multiple calls of produce methods, but return those different\nrepresentations.\n\nIf any additional method arguments are added to primitive's produce method(s), they have\nto be added to this method as well. This method should accept an union of all arguments\naccepted by primitive's produce method(s) and then use them accordingly when computing\nresults.\n\nThe default implementation of this method just calls all produce methods listed in\n``produce_methods`` in order and is potentially inefficient.\n\nIf primitive should have been fitted before calling this method, but it has not been,\nprimitive should raise a ``PrimitiveNotFittedError`` exception.\n\nParameters\n----------\nproduce_methods:\n A list of names of produce methods to call.\ninputs:\n The inputs given to all produce methods.\ntimeout:\n A maximum time this primitive should take to produce outputs for all produce methods\n listed in ``produce_methods`` argument, in seconds.\niterations:\n How many of internal iterations should the primitive do.\n\nReturns\n-------\nA dict of values for each produce method wrapped inside ``MultiCallResult``."
  150. },
  151. "produce": {
  152. "kind": "PRODUCE",
  153. "arguments": [
  154. "inputs",
  155. "timeout",
  156. "iterations"
  157. ],
  158. "returns": "d3m.primitive_interfaces.base.CallResult[d3m.container.list.List]",
  159. "singleton": false,
  160. "inputs_across_samples": [],
  161. "description": "Produce primitive's best choice of the output for each of the inputs.\n\nThe output value should be wrapped inside ``CallResult`` object before returning.\n\nIn many cases producing an output is a quick operation in comparison with ``fit``, but not\nall cases are like that. For example, a primitive can start a potentially long optimization\nprocess to compute outputs. ``timeout`` and ``iterations`` can serve as a way for a caller\nto guide the length of this process.\n\nIdeally, a primitive should adapt its call to try to produce the best outputs possible\ninside the time allocated. If this is not possible and the primitive reaches the timeout\nbefore producing outputs, it should raise a ``TimeoutError`` exception to signal that the\ncall was unsuccessful in the given time. The state of the primitive after the exception\nshould be as the method call has never happened and primitive should continue to operate\nnormally. The purpose of ``timeout`` is to give opportunity to a primitive to cleanly\nmanage its state instead of interrupting execution from outside. Maintaining stable internal\nstate should have precedence over respecting the ``timeout`` (caller can terminate the\nmisbehaving primitive from outside anyway). If a longer ``timeout`` would produce\ndifferent outputs, then ``CallResult``'s ``has_finished`` should be set to ``False``.\n\nSome primitives have internal iterations (for example, optimization iterations).\nFor those, caller can provide how many of primitive's internal iterations\nshould a primitive do before returning outputs. Primitives should make iterations as\nsmall as reasonable. If ``iterations`` is ``None``, then there is no limit on\nhow many iterations the primitive should do and primitive should choose the best amount\nof iterations on its own (potentially controlled through hyper-parameters).\nIf ``iterations`` is a number, a primitive has to do those number of iterations,\nif possible. ``timeout`` should still be respected and potentially less iterations\ncan be done because of that. Primitives with internal iterations should make\n``CallResult`` contain correct values.\n\nFor primitives which do not have internal iterations, any value of ``iterations``\nmeans that they should run fully, respecting only ``timeout``.\n\nIf primitive should have been fitted before calling this method, but it has not been,\nprimitive should raise a ``PrimitiveNotFittedError`` exception.\n\nParameters\n----------\ninputs:\n The inputs of shape [num_inputs, ...].\ntimeout:\n A maximum time this primitive should take to produce outputs during this method call, in seconds.\niterations:\n How many of internal iterations should the primitive do.\n\nReturns\n-------\nThe outputs of shape [num_inputs, ...] wrapped inside ``CallResult``."
  162. },
  163. "set_params": {
  164. "kind": "OTHER",
  165. "arguments": [
  166. "params"
  167. ],
  168. "returns": "NoneType",
  169. "description": "Sets parameters of this primitive.\n\nParameters are all parameters of the primitive which can potentially change during a life-time of\na primitive. Parameters which cannot are passed through constructor.\n\nNo other arguments to the method are allowed (except for private arguments).\n\nParameters\n----------\nparams:\n An instance of parameters."
  170. },
  171. "set_training_data": {
  172. "kind": "OTHER",
  173. "arguments": [
  174. "inputs",
  175. "outputs"
  176. ],
  177. "returns": "NoneType",
  178. "description": "Sets current training data of this primitive.\n\nThis marks training data as changed even if new training data is the same as\nprevious training data.\n\nStandard sublasses in this package do not adhere to the Liskov substitution principle when\ninheriting this method because they do not necessary accept all arguments found in the base\nclass. This means that one has to inspect which arguments are accepted at runtime, or in\nother words, one has to inspect which exactly subclass a primitive implements, if\nyou are accepting a wider range of primitives. This relaxation is allowed only for\nstandard subclasses found in this package. Primitives themselves should not break\nthe Liskov substitution principle but should inherit from a suitable base class.\n\nParameters\n----------\ninputs:\n The inputs.\noutputs:\n The outputs."
  179. }
  180. },
  181. "class_attributes": {
  182. "logger": "logging.Logger",
  183. "metadata": "d3m.metadata.base.PrimitiveMetadata"
  184. },
  185. "instance_attributes": {
  186. "hyperparams": "d3m.metadata.hyperparams.Hyperparams",
  187. "random_seed": "int",
  188. "docker_containers": "typing.Dict[str, d3m.primitive_interfaces.base.DockerContainer]",
  189. "volumes": "typing.Dict[str, str]",
  190. "temporary_directory": "typing.Union[NoneType, str]"
  191. },
  192. "params": {
  193. "a": "float"
  194. }
  195. },
  196. "structural_type": "test_primitives.monomial.MonomialPrimitive",
  197. "description": "A primitive which fits output = a * input.\n\nAttributes\n----------\nmetadata:\n Primitive's metadata. Available as a class attribute.\nlogger:\n Primitive's logger. Available as a class attribute.\nhyperparams:\n Hyperparams passed to the constructor.\nrandom_seed:\n Random seed passed to the constructor.\ndocker_containers:\n A dict mapping Docker image keys from primitive's metadata to (named) tuples containing\n container's address under which the container is accessible by the primitive, and a\n dict mapping exposed ports to ports on that address.\nvolumes:\n A dict mapping volume keys from primitive's metadata to file and directory paths\n where downloaded and extracted files are available to the primitive.\ntemporary_directory:\n An absolute path to a temporary directory a primitive can use to store any files\n for the duration of the current pipeline run phase. Directory is automatically\n cleaned up after the current pipeline run phase finishes.",
  198. "digest": "__DIGEST__"
  199. }
  200. """.replace('__INTERFACES_VERSION__', d3m.__version__).replace('__GIT_COMMIT__', utils.current_git_commit(TEST_PRIMITIVES_DIR)).replace('__DIGEST__', MonomialPrimitive.metadata.query()['digest'])
  201. class TestMonomialPrimitive(unittest.TestCase):
  202. def call_primitive(self, primitive, method_name, **kwargs):
  203. return getattr(primitive, method_name)(**kwargs)
  204. def test_basic(self):
  205. hyperparams_class = MonomialPrimitive.metadata.get_hyperparams()
  206. primitive = MonomialPrimitive(hyperparams=hyperparams_class.defaults())
  207. inputs = container.List([1, 2, 3, 4, 5, 6], generate_metadata=True)
  208. outputs = container.List([2, 4, 6, 8, 10, 12], generate_metadata=True)
  209. self.call_primitive(primitive, 'set_training_data', inputs=inputs, outputs=outputs)
  210. call_metadata = self.call_primitive(primitive, 'fit')
  211. self.assertEqual(call_metadata.has_finished, True)
  212. self.assertEqual(call_metadata.iterations_done, None)
  213. inputs = container.List([10, 20, 30], generate_metadata=True)
  214. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  215. self.assertSequenceEqual(call_metadata.value, [20, 40, 60])
  216. self.assertEqual(call_metadata.has_finished, True)
  217. self.assertEqual(call_metadata.iterations_done, None)
  218. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  219. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS,))['structural_type'], float)
  220. call_metadata = primitive.multi_produce(produce_methods=('produce',), inputs=inputs)
  221. self.assertEqual(len(call_metadata.values), 1)
  222. self.assertSequenceEqual(call_metadata.values['produce'], [20, 40, 60])
  223. self.assertEqual(call_metadata.has_finished, True)
  224. self.assertEqual(call_metadata.iterations_done, None)
  225. def test_hyperparameter(self):
  226. hyperparams_class = MonomialPrimitive.metadata.get_hyperparams()
  227. primitive = MonomialPrimitive(hyperparams=hyperparams_class(bias=1))
  228. inputs = container.List([1, 2, 3, 4, 5, 6], generate_metadata=True)
  229. outputs = container.List([2, 4, 6, 8, 10, 12], generate_metadata=True)
  230. self.call_primitive(primitive, 'set_training_data', inputs=inputs, outputs=outputs)
  231. call_metadata = self.call_primitive(primitive, 'fit')
  232. self.assertEqual(call_metadata.has_finished, True)
  233. self.assertEqual(call_metadata.iterations_done, None)
  234. inputs = container.List([10, 20, 30], generate_metadata=True)
  235. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  236. self.assertSequenceEqual(call_metadata.value, [21, 41, 61])
  237. self.assertEqual(call_metadata.has_finished, True)
  238. self.assertEqual(call_metadata.iterations_done, None)
  239. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  240. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS,))['structural_type'], float)
  241. def test_recreation(self):
  242. hyperparams_class = MonomialPrimitive.metadata.get_hyperparams()
  243. primitive = MonomialPrimitive(hyperparams=hyperparams_class(bias=1))
  244. inputs = container.List([1, 2, 3, 4, 5, 6], generate_metadata=True)
  245. outputs = container.List([2, 4, 6, 8, 10, 12], generate_metadata=True)
  246. self.call_primitive(primitive, 'set_training_data', inputs=inputs, outputs=outputs)
  247. call_metadata = self.call_primitive(primitive, 'fit')
  248. self.assertEqual(call_metadata.has_finished, True)
  249. self.assertEqual(call_metadata.iterations_done, None)
  250. params = self.call_primitive(primitive, 'get_params')
  251. pickled_params = pickle.dumps(params)
  252. unpickled_params = pickle.loads(pickled_params)
  253. self.assertEqual(params, unpickled_params)
  254. pickled_hyperparams = pickle.dumps(primitive.hyperparams)
  255. unpickled_hyperparams = pickle.loads(pickled_hyperparams)
  256. self.assertEqual(primitive.hyperparams, unpickled_hyperparams)
  257. primitive = MonomialPrimitive(hyperparams=unpickled_hyperparams)
  258. self.call_primitive(primitive, 'set_params', params=unpickled_params)
  259. inputs = container.List([10, 20, 30], generate_metadata=True)
  260. call_metadata =self.call_primitive(primitive, 'produce', inputs=inputs)
  261. self.assertSequenceEqual(call_metadata.value, [21, 41, 61])
  262. self.assertEqual(call_metadata.has_finished, True)
  263. self.assertEqual(call_metadata.iterations_done, None)
  264. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  265. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS,))['structural_type'], float)
  266. def test_pickle(self):
  267. hyperparams_class = MonomialPrimitive.metadata.get_hyperparams()
  268. primitive = MonomialPrimitive(hyperparams=hyperparams_class(bias=1))
  269. inputs = container.List([1, 2, 3, 4, 5, 6], generate_metadata=True)
  270. outputs = container.List([2, 4, 6, 8, 10, 12], generate_metadata=True)
  271. self.call_primitive(primitive, 'set_training_data', inputs=inputs, outputs=outputs)
  272. call_metadata = self.call_primitive(primitive, 'fit')
  273. self.assertEqual(call_metadata.has_finished, True)
  274. self.assertEqual(call_metadata.iterations_done, None)
  275. pickled_primitive = pickle.dumps(primitive)
  276. unpickled_primitive = pickle.loads(pickled_primitive)
  277. self.assertEqual(primitive.hyperparams, unpickled_primitive.hyperparams)
  278. self.assertEqual(primitive.random_seed, unpickled_primitive.random_seed)
  279. self.assertEqual(primitive.docker_containers, unpickled_primitive.docker_containers)
  280. inputs = container.List([10, 20, 30], generate_metadata=True)
  281. call_metadata =self.call_primitive(unpickled_primitive, 'produce', inputs=inputs)
  282. self.assertSequenceEqual(call_metadata.value, [21, 41, 61])
  283. self.assertEqual(call_metadata.has_finished, True)
  284. self.assertEqual(call_metadata.iterations_done, None)
  285. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  286. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS,))['structural_type'], float)
  287. def test_metadata(self):
  288. expected_description = json.loads(EXPECTED_PRIMITIVE_DESCRIPTION_JSON)
  289. # We stringify to JSON and parse it to make sure the description can be stringified to JSON.
  290. description = json.loads(json.dumps(MonomialPrimitive.metadata.to_json_structure()))
  291. self.maxDiff = None
  292. self.assertEqual(expected_description, description)
  293. if __name__ == '__main__':
  294. unittest.main()

全栈的自动化机器学习系统,主要针对多变量时间序列数据的异常检测。TODS提供了详尽的用于构建基于机器学习的异常检测系统的模块,它们包括:数据处理(data processing),时间序列处理( time series processing),特征分析(feature analysis),检测算法(detection algorithms),和强化模块( reinforcement module)。这些模块所提供的功能包括常见的数据预处理、时间序列数据的平滑或变换,从时域或频域中抽取特征、多种多样的检测算