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_null.py 20 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import json
  2. import unittest
  3. import os.path
  4. import sys
  5. import numpy as np
  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.null import NullTransformerPrimitive, NullDataFrameUnsupervisedLearnerPrimitive
  12. EXPECTED_PRIMITIVE_DESCRIPTION_JSON = r"""
  13. {
  14. "id": "e0f83c35-fe3d-4fa6-92cf-f7421408eab5",
  15. "version": "0.1.0",
  16. "name": "Produce the same as the input",
  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/null.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/add_primitives.py"
  36. ],
  37. "python_path": "d3m.primitives.operator.null.TransformerTest",
  38. "algorithm_types": [
  39. "IDENTITY_FUNCTION"
  40. ],
  41. "primitive_family": "OPERATOR",
  42. "schema": "https://metadata.datadrivendiscovery.org/schemas/v0/primitive.json",
  43. "original_python_path": "test_primitives.null.NullTransformerPrimitive",
  44. "primitive_code": {
  45. "class_type_arguments": {
  46. "Inputs": "d3m.container.list.List",
  47. "Outputs": "d3m.container.list.List",
  48. "Hyperparams": "test_primitives.null.Hyperparams",
  49. "Params": "NoneType"
  50. },
  51. "interfaces_version": "__INTERFACES_VERSION__",
  52. "interfaces": [
  53. "transformer.TransformerPrimitiveBase",
  54. "base.PrimitiveBase"
  55. ],
  56. "hyperparams": {},
  57. "arguments": {
  58. "hyperparams": {
  59. "type": "test_primitives.null.Hyperparams",
  60. "kind": "RUNTIME"
  61. },
  62. "random_seed": {
  63. "type": "int",
  64. "kind": "RUNTIME",
  65. "default": 0
  66. },
  67. "docker_containers": {
  68. "type": "typing.Union[NoneType, typing.Dict[str, d3m.primitive_interfaces.base.DockerContainer]]",
  69. "kind": "RUNTIME",
  70. "default": null
  71. },
  72. "volumes": {
  73. "type": "typing.Union[NoneType, typing.Dict[str, str]]",
  74. "kind": "RUNTIME",
  75. "default": null
  76. },
  77. "temporary_directory": {
  78. "type": "typing.Union[NoneType, str]",
  79. "kind": "RUNTIME",
  80. "default": null
  81. },
  82. "timeout": {
  83. "type": "typing.Union[NoneType, float]",
  84. "kind": "RUNTIME",
  85. "default": null
  86. },
  87. "iterations": {
  88. "type": "typing.Union[NoneType, int]",
  89. "kind": "RUNTIME",
  90. "default": null
  91. },
  92. "produce_methods": {
  93. "type": "typing.Sequence[str]",
  94. "kind": "RUNTIME"
  95. },
  96. "inputs": {
  97. "type": "d3m.container.list.List",
  98. "kind": "PIPELINE"
  99. },
  100. "params": {
  101. "type": "NoneType",
  102. "kind": "RUNTIME"
  103. }
  104. },
  105. "class_methods": {},
  106. "instance_methods": {
  107. "__init__": {
  108. "kind": "OTHER",
  109. "arguments": [
  110. "hyperparams",
  111. "random_seed",
  112. "docker_containers",
  113. "volumes",
  114. "temporary_directory"
  115. ],
  116. "returns": "NoneType",
  117. "description": "All primitives should accept all their hyper-parameters in a constructor as one value,\nan instance of type ``Hyperparams``.\n\nProvided random seed should control all randomness used by this primitive.\nPrimitive should behave exactly the same for the same random seed across multiple\ninvocations. You can call `numpy.random.RandomState(random_seed)` to obtain an\ninstance of a random generator using provided seed. If your primitive does not\nuse randomness, consider not exposing this argument in your primitive's constructor\nto signal that.\n\nPrimitives can be wrappers around or use one or more Docker images which they can\nspecify as part of ``installation`` field in their metadata. Each Docker image listed\nthere has a ``key`` field identifying that image. When primitive is created,\n``docker_containers`` contains a mapping between those keys and connection information\nwhich primitive can use to connect to a running Docker container for a particular Docker\nimage and its exposed ports. Docker containers might be long running and shared between\nmultiple instances of a primitive. If your primitive does not use Docker images,\nconsider not exposing this argument in your primitive's constructor.\n\n**Note**: Support for primitives using Docker containers has been put on hold.\nCurrently it is not expected that any runtime running primitives will run\nDocker containers for a primitive.\n\nPrimitives can also use additional static files which can be added as a dependency\nto ``installation`` metadata. When done so, given volumes are provided to the\nprimitive through ``volumes`` argument to the primitive's constructor as a\ndict mapping volume keys to file and directory paths where downloaded and\nextracted files are available to the primitive. All provided files and directories\nare read-only. If your primitive does not use static files, consider not exposing\nthis argument in your primitive's constructor.\n\nPrimitives can also use the provided temporary directory to store any files for\nthe duration of the current pipeline run phase. Directory is automatically\ncleaned up after the current pipeline run phase finishes. Do not store in this\ndirectory any primitive's state you would like to preserve between \"fit\" and\n\"produce\" phases of pipeline execution. Use ``Params`` for that. The main intent\nof this temporary directory is to store files referenced by any ``Dataset`` object\nyour primitive might create and followup primitives in the pipeline should have\naccess to. When storing files into this directory consider using capabilities\nof Python's `tempfile` module to generate filenames which will not conflict with\nany other files stored there. Use provided temporary directory as ``dir`` argument\nto set it as base directory to generate additional temporary files and directories\nas needed. If your primitive does not use temporary directory, consider not exposing\nthis argument in your primitive's constructor.\n\nNo other arguments to the constructor are allowed (except for private arguments)\nbecause we want instances of primitives to be created without a need for any other\nprior computation.\n\nModule in which a primitive is defined should be kept lightweight and on import not do\nany (pre)computation, data loading, or resource allocation/reservation. Any loading\nand resource allocation/reservation should be done in the constructor. Any (pre)computation\nshould be done lazily when needed once requested through other methods and not in the constructor."
  118. },
  119. "fit": {
  120. "kind": "OTHER",
  121. "arguments": [
  122. "timeout",
  123. "iterations"
  124. ],
  125. "returns": "d3m.primitive_interfaces.base.CallResult[NoneType]",
  126. "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."
  127. },
  128. "fit_multi_produce": {
  129. "kind": "OTHER",
  130. "arguments": [
  131. "produce_methods",
  132. "inputs",
  133. "timeout",
  134. "iterations"
  135. ],
  136. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  137. "description": "A method calling ``fit`` and after that multiple produce methods at once.\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 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``."
  138. },
  139. "get_params": {
  140. "kind": "OTHER",
  141. "arguments": [],
  142. "returns": "NoneType",
  143. "description": "A noop.\n\nReturns\n-------\nAn instance of parameters."
  144. },
  145. "multi_produce": {
  146. "kind": "OTHER",
  147. "arguments": [
  148. "produce_methods",
  149. "inputs",
  150. "timeout",
  151. "iterations"
  152. ],
  153. "returns": "d3m.primitive_interfaces.base.MultiCallResult",
  154. "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``."
  155. },
  156. "produce": {
  157. "kind": "PRODUCE",
  158. "arguments": [
  159. "inputs",
  160. "timeout",
  161. "iterations"
  162. ],
  163. "returns": "d3m.primitive_interfaces.base.CallResult[d3m.container.list.List]",
  164. "singleton": false,
  165. "inputs_across_samples": [],
  166. "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``."
  167. },
  168. "set_params": {
  169. "kind": "OTHER",
  170. "arguments": [
  171. "params"
  172. ],
  173. "returns": "NoneType",
  174. "description": "A noop.\n\nParameters\n----------\nparams:\n An instance of parameters."
  175. },
  176. "set_training_data": {
  177. "kind": "OTHER",
  178. "arguments": [],
  179. "returns": "NoneType",
  180. "description": "A noop.\n\nParameters\n----------"
  181. }
  182. },
  183. "class_attributes": {
  184. "logger": "logging.Logger",
  185. "metadata": "d3m.metadata.base.PrimitiveMetadata"
  186. },
  187. "instance_attributes": {
  188. "hyperparams": "d3m.metadata.hyperparams.Hyperparams",
  189. "random_seed": "int",
  190. "docker_containers": "typing.Dict[str, d3m.primitive_interfaces.base.DockerContainer]",
  191. "volumes": "typing.Dict[str, str]",
  192. "temporary_directory": "typing.Union[NoneType, str]"
  193. }
  194. },
  195. "structural_type": "test_primitives.null.NullTransformerPrimitive",
  196. "description": "A primitive which passes through inputs as outputs.\n\nIt does not really care if inputs is list.\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.",
  197. "digest": "__DIGEST__"
  198. }
  199. """.replace('__INTERFACES_VERSION__', d3m.__version__).replace('__GIT_COMMIT__', utils.current_git_commit(TEST_PRIMITIVES_DIR)).replace('__DIGEST__', NullTransformerPrimitive.metadata.query()['digest'])
  200. class TestNullPrimitives(unittest.TestCase):
  201. def call_primitive(self, primitive, method_name, extra_arguments=None, **kwargs):
  202. primitive_arguments = primitive.metadata.query()['primitive_code'].get('arguments', {})
  203. if extra_arguments is None:
  204. extra_arguments = {}
  205. arguments = {}
  206. for argument_name, argument_value in dict(extra_arguments, **kwargs).items():
  207. if primitive_arguments[argument_name]['kind'] == base.PrimitiveArgumentKind.PIPELINE:
  208. arguments[argument_name] = argument_value.metadata
  209. else:
  210. arguments[argument_name] = type(argument_value)
  211. return getattr(primitive, method_name)(**kwargs)
  212. def test_null_transformer(self):
  213. hyperparams_class = NullTransformerPrimitive.metadata.get_hyperparams()
  214. primitive = NullTransformerPrimitive(hyperparams=hyperparams_class.defaults())
  215. inputs = container.List([10, 20, 30], generate_metadata=True)
  216. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  217. self.assertSequenceEqual(call_metadata.value, [10, 20, 30])
  218. self.assertEqual(call_metadata.has_finished, True)
  219. self.assertEqual(call_metadata.iterations_done, None)
  220. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  221. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS,))['structural_type'], int)
  222. def test_null_transformer_metadata(self):
  223. expected_description = json.loads(EXPECTED_PRIMITIVE_DESCRIPTION_JSON)
  224. # We stringify to JSON and parse it to make sure the description can be stringified to JSON.
  225. description = json.loads(json.dumps(NullTransformerPrimitive.metadata.to_json_structure()))
  226. self.maxDiff = None
  227. self.assertEqual(expected_description, description)
  228. def test_null_dataframe_unsupervised_learner(self):
  229. hyperparams_class = NullDataFrameUnsupervisedLearnerPrimitive.metadata.get_hyperparams()
  230. primitive = NullDataFrameUnsupervisedLearnerPrimitive(hyperparams=hyperparams_class.defaults())
  231. inputs = container.DataFrame([10, 20, 30], generate_metadata=True)
  232. call_metadata = self.call_primitive(primitive, 'produce', inputs=inputs)
  233. self.assertSequenceEqual(call_metadata.value.values.tolist(), [[10], [20], [30]])
  234. self.assertEqual(call_metadata.has_finished, True)
  235. self.assertEqual(call_metadata.iterations_done, None)
  236. self.assertEqual(call_metadata.value.metadata.query(())['dimension']['length'], 3)
  237. self.assertEqual(call_metadata.value.metadata.query((base.ALL_ELEMENTS, 0,))['structural_type'], np.int64)
  238. if __name__ == '__main__':
  239. unittest.main()

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