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_random.py 16 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. import json
  2. import unittest
  3. import os.path
  4. import pickle
  5. import sys
  6. import numpy
  7. import d3m
  8. from d3m import container, utils
  9. from d3m.metadata import base
  10. TEST_PRIMITIVES_DIR = os.path.join(os.path.dirname(__file__), 'data', 'primitives')
  11. sys.path.insert(0, TEST_PRIMITIVES_DIR)
  12. from test_primitives.random import RandomPrimitive
  13. EXPECTED_PRIMITIVE_DESCRIPTION_JSON = r"""
  14. {
  15. "id": "df3153a1-4411-47e2-bbc0-9d5e9925ad79",
  16. "version": "0.1.0",
  17. "name": "Random Samples",
  18. "keywords": [
  19. "test primitive"
  20. ],
  21. "source": {
  22. "name": "Test team",
  23. "contact": "mailto:author@example.com",
  24. "uris": [
  25. "https://gitlab.com/datadrivendiscovery/tests-data/blob/master/primitives/test_primitives/random.py",
  26. "https://gitlab.com/datadrivendiscovery/tests-data.git"
  27. ]
  28. },
  29. "installation": [
  30. {
  31. "type": "PIP",
  32. "package_uri": "git+https://gitlab.com/datadrivendiscovery/tests-data.git@__GIT_COMMIT__#egg=test_primitives&subdirectory=primitives"
  33. }
  34. ],
  35. "location_uris": [
  36. "https://gitlab.com/datadrivendiscovery/tests-data/raw/__GIT_COMMIT__/primitives/test_primitives/random.py"
  37. ],
  38. "python_path": "d3m.primitives.data_generation.random.Test",
  39. "algorithm_types": [
  40. "MERSENNE_TWISTER",
  41. "NORMAL_DISTRIBUTION"
  42. ],
  43. "primitive_family": "DATA_GENERATION",
  44. "schema": "https://metadata.datadrivendiscovery.org/schemas/v0/primitive.json",
  45. "original_python_path": "test_primitives.random.RandomPrimitive",
  46. "primitive_code": {
  47. "class_type_arguments": {
  48. "Outputs": "d3m.container.pandas.DataFrame",
  49. "Params": "NoneType",
  50. "Hyperparams": "test_primitives.random.Hyperparams",
  51. "Inputs": "d3m.container.list.List"
  52. },
  53. "interfaces_version": "__INTERFACES_VERSION__",
  54. "interfaces": [
  55. "generator.GeneratorPrimitiveBase",
  56. "base.PrimitiveBase"
  57. ],
  58. "hyperparams": {
  59. "mu": {
  60. "type": "d3m.metadata.hyperparams.Hyperparameter",
  61. "default": 0.0,
  62. "structural_type": "float",
  63. "semantic_types": [
  64. "https://metadata.datadrivendiscovery.org/types/ControlParameter",
  65. "https://metadata.datadrivendiscovery.org/types/TuningParameter"
  66. ]
  67. },
  68. "sigma": {
  69. "type": "d3m.metadata.hyperparams.Hyperparameter",
  70. "default": 1.0,
  71. "structural_type": "float",
  72. "semantic_types": [
  73. "https://metadata.datadrivendiscovery.org/types/ControlParameter",
  74. "https://metadata.datadrivendiscovery.org/types/TuningParameter"
  75. ]
  76. }
  77. },
  78. "arguments": {
  79. "hyperparams": {
  80. "type": "test_primitives.random.Hyperparams",
  81. "kind": "RUNTIME"
  82. },
  83. "random_seed": {
  84. "type": "int",
  85. "kind": "RUNTIME",
  86. "default": 0
  87. },
  88. "timeout": {
  89. "type": "typing.Union[NoneType, float]",
  90. "kind": "RUNTIME",
  91. "default": null
  92. },
  93. "iterations": {
  94. "type": "typing.Union[NoneType, int]",
  95. "kind": "RUNTIME",
  96. "default": null
  97. },
  98. "produce_methods": {
  99. "type": "typing.Sequence[str]",
  100. "kind": "RUNTIME"
  101. },
  102. "inputs": {
  103. "type": "d3m.container.list.List",
  104. "kind": "PIPELINE"
  105. },
  106. "params": {
  107. "type": "NoneType",
  108. "kind": "RUNTIME"
  109. }
  110. },
  111. "class_methods": {},
  112. "instance_methods": {
  113. "__init__": {
  114. "kind": "OTHER",
  115. "arguments": [
  116. "hyperparams",
  117. "random_seed"
  118. ],
  119. "returns": "NoneType"
  120. },
  121. "fit": {
  122. "kind": "OTHER",
  123. "arguments": [
  124. "timeout",
  125. "iterations"
  126. ],
  127. "returns": "d3m.primitive_interfaces.base.CallResult[NoneType]",
  128. "description": "A noop.\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."
  129. },
  130. "fit_multi_produce": {
  131. "kind": "OTHER",
  132. "arguments": [
  133. "produce_methods",
  134. "inputs",
  135. "timeout",
  136. "iterations"
  137. ],
  138. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  139. "description": "A method calling ``fit`` and after that multiple produce methods at once.\n\nParameters\n----------\nproduce_methods : Sequence[str]\n A list of names of produce methods to call.\ninputs : List\n The inputs given to all produce methods.\ntimeout : float\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 : int\n How many of internal iterations should the primitive do for both fitting and producing\n outputs of all produce methods.\n\nReturns\n-------\nMultiCallResult\n A dict of values for each produce method wrapped inside ``MultiCallResult``."
  140. },
  141. "get_params": {
  142. "kind": "OTHER",
  143. "arguments": [],
  144. "returns": "NoneType",
  145. "description": "A noop.\n\nReturns\n-------\nAn instance of parameters."
  146. },
  147. "multi_produce": {
  148. "kind": "OTHER",
  149. "arguments": [
  150. "produce_methods",
  151. "inputs",
  152. "timeout",
  153. "iterations"
  154. ],
  155. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  156. "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``."
  157. },
  158. "produce": {
  159. "kind": "PRODUCE",
  160. "arguments": [
  161. "inputs",
  162. "timeout",
  163. "iterations"
  164. ],
  165. "returns": "d3m.primitive_interfaces.base.CallResult[d3m.container.pandas.DataFrame]",
  166. "singleton": false,
  167. "inputs_across_samples": [],
  168. "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``."
  169. },
  170. "set_params": {
  171. "kind": "OTHER",
  172. "arguments": [
  173. "params"
  174. ],
  175. "returns": "NoneType",
  176. "description": "A noop.\n\nParameters\n----------\nparams:\n An instance of parameters."
  177. },
  178. "set_training_data": {
  179. "kind": "OTHER",
  180. "arguments": [],
  181. "returns": "NoneType",
  182. "description": "A noop.\n\nParameters\n----------\noutputs:\n The outputs."
  183. }
  184. },
  185. "class_attributes": {
  186. "logger": "logging.Logger",
  187. "metadata": "d3m.metadata.base.PrimitiveMetadata"
  188. },
  189. "instance_attributes": {
  190. "hyperparams": "d3m.metadata.hyperparams.Hyperparams",
  191. "random_seed": "int",
  192. "docker_containers": "typing.Dict[str, d3m.primitive_interfaces.base.DockerContainer]",
  193. "volumes": "typing.Dict[str, str]",
  194. "temporary_directory": "typing.Union[NoneType, str]"
  195. }
  196. },
  197. "structural_type": "test_primitives.random.RandomPrimitive",
  198. "description": "A primitive which draws random samples from a normal distribution.\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.",
  199. "digest": "__DIGEST__"
  200. }
  201. """.replace('__INTERFACES_VERSION__', d3m.__version__).replace('__GIT_COMMIT__', utils.current_git_commit(TEST_PRIMITIVES_DIR)).replace('__DIGEST__', RandomPrimitive.metadata.query()['digest'])
  202. class TestRandomPrimitive(unittest.TestCase):
  203. def call_primitive(self, primitive, method_name, **kwargs):
  204. return getattr(primitive, method_name)(**kwargs)
  205. def test_basic(self):
  206. hyperparams_class = RandomPrimitive.metadata.get_hyperparams()
  207. primitive = RandomPrimitive(random_seed=42, hyperparams=hyperparams_class.defaults())
  208. inputs = container.List(list(range(4)), generate_metadata=True)
  209. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  210. self.assertTrue(numpy.allclose(call_metadata.value.values, container.ndarray([0.496714153011, -0.138264301171, 0.647688538101, 1.52302985641]).reshape((4, 1))))
  211. self.assertEqual(call_metadata.has_finished, True)
  212. self.assertEqual(call_metadata.iterations_done, None)
  213. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS, 0))['structural_type'], numpy.float64)
  214. def test_pickle(self):
  215. # This test is not really useful anymore because primitive now does not keep random state
  216. # anymore but outputs depend only on inputs, and not on previous calls to "produce" method.
  217. hyperparams_class = RandomPrimitive.metadata.get_hyperparams()
  218. primitive = RandomPrimitive(random_seed=42, hyperparams=hyperparams_class.defaults())
  219. inputs = container.List(list(range(4)), generate_metadata=True)
  220. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  221. self.assertTrue(numpy.allclose(call_metadata.value.values, container.ndarray([0.496714153011, -0.138264301171, 0.647688538101, 1.52302985641]).reshape(4, 1)))
  222. pickled_primitive = pickle.dumps(primitive)
  223. inputs = container.List(list(range(4, 8)), generate_metadata=True)
  224. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  225. self.assertTrue(numpy.allclose(call_metadata.value.values, container.ndarray([-0.23415337, -0.23413696, 1.57921282, 0.76743473]).reshape(4, 1)))
  226. unpickled_primitive = pickle.loads(pickled_primitive)
  227. call_metadata = self.call_primitive(unpickled_primitive, 'produce', inputs=inputs)
  228. self.assertTrue(numpy.allclose(call_metadata.value.values, container.ndarray([-0.23415337, -0.23413696, 1.57921282, 0.76743473]).reshape(4, 1)))
  229. def test_metadata(self):
  230. expected_description = json.loads(EXPECTED_PRIMITIVE_DESCRIPTION_JSON)
  231. # We stringify to JSON and parse it to make sure the description can be stringified to JSON.
  232. description = json.loads(json.dumps(RandomPrimitive.metadata.to_json_structure()))
  233. self.maxDiff = None
  234. self.assertEqual(expected_description, description)
  235. if __name__ == '__main__':
  236. unittest.main()

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