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.

BKFilter.py 17 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. from typing import Any, Callable, List, Dict, Union, Optional, Sequence, Tuple
  2. from numpy import ndarray
  3. from collections import OrderedDict
  4. from scipy import sparse
  5. import os
  6. import sklearn
  7. import numpy
  8. import typing
  9. import time
  10. from d3m import container
  11. from d3m.primitive_interfaces import base, transformer
  12. from d3m.metadata import base as metadata_base, hyperparams
  13. from d3m.container.numpy import ndarray as d3m_ndarray
  14. from d3m.container import DataFrame as d3m_dataframe
  15. from d3m.metadata import hyperparams, params, base as metadata_base
  16. from d3m import utils
  17. from d3m.base import utils as base_utils
  18. from d3m.exceptions import PrimitiveNotFittedError
  19. from d3m.primitive_interfaces.base import CallResult, DockerContainer
  20. import os.path
  21. import time
  22. import statsmodels.api as sm
  23. __all__ = ('BKFilter',)
  24. Inputs = container.DataFrame
  25. Outputs = container.DataFrame
  26. class Hyperparams(hyperparams.Hyperparams):
  27. # Tuning
  28. low = hyperparams.UniformInt(
  29. lower=0,
  30. upper=100000000,
  31. default=6,
  32. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  33. description="Minimum period for oscillations, ie., Baxter and King suggest that the Burns-Mitchell U.S. business cycle has 6 for quarterly data and 1.5 for annual data.",
  34. )
  35. high = hyperparams.UniformInt(
  36. lower=0,
  37. upper=100000000,
  38. default=32,
  39. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  40. description="Maximum period for oscillations BK suggest that the U.S. business cycle has 32 for quarterly data and 8 for annual data.",
  41. )
  42. K = hyperparams.UniformInt(
  43. lower=0,
  44. upper=100000000,
  45. default=1,
  46. semantic_types=['https://metadata.datadrivendiscovery.org/types/TuningParameter'],
  47. description="Lead-lag length of the filter. Baxter and King propose a truncation length of 12 for quarterly data and 3 for annual data.",
  48. )
  49. # Control
  50. columns_using_method= hyperparams.Enumeration(
  51. values=['name', 'index'],
  52. default='index',
  53. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  54. description="Choose to use columns by names or indecies. If 'name', \"use_columns\" or \"exclude_columns\" is used. If 'index', \"use_columns_name\" or \"exclude_columns_name\" is used."
  55. )
  56. use_columns_name = hyperparams.Set(
  57. elements=hyperparams.Hyperparameter[str](''),
  58. default=(),
  59. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  60. description="A set of column names to force primitive to operate on. If any specified column cannot be parsed, it is skipped.",
  61. )
  62. exclude_columns_name = hyperparams.Set(
  63. elements=hyperparams.Hyperparameter[str](''),
  64. default=(),
  65. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  66. description="A set of column names to not operate on. Applicable only if \"use_columns_name\" is not provided.",
  67. )
  68. use_columns = hyperparams.Set(
  69. elements=hyperparams.Hyperparameter[int](-1),
  70. default=(),
  71. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  72. description="A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.",
  73. )
  74. exclude_columns = hyperparams.Set(
  75. elements=hyperparams.Hyperparameter[int](-1),
  76. default=(),
  77. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  78. description="A set of column indices to not operate on. Applicable only if \"use_columns\" is not provided.",
  79. )
  80. return_result = hyperparams.Enumeration(
  81. values=['append', 'replace', 'new'],
  82. default='append',
  83. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  84. description="Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.",
  85. )
  86. use_semantic_types = hyperparams.UniformBool(
  87. default=False,
  88. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  89. description="Controls whether semantic_types metadata will be used for filtering columns in input dataframe. Setting this to false makes the code ignore return_result and will produce only the output dataframe"
  90. )
  91. add_index_columns = hyperparams.UniformBool(
  92. default=False,
  93. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  94. description="Also include primary index columns if input data has them. Applicable only if \"return_result\" is set to \"new\".",
  95. )
  96. error_on_no_input = hyperparams.UniformBool(
  97. default=True,
  98. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter'],
  99. description="Throw an exception if no input column is selected/provided. Defaults to true to behave like sklearn. To prevent pipelines from breaking set this to False.",
  100. )
  101. return_semantic_type = hyperparams.Enumeration[str](
  102. values=['https://metadata.datadrivendiscovery.org/types/Attribute', 'https://metadata.datadrivendiscovery.org/types/ConstructedAttribute'],
  103. default='https://metadata.datadrivendiscovery.org/types/Attribute',
  104. description='Decides what semantic type to attach to generated attributes',
  105. semantic_types=['https://metadata.datadrivendiscovery.org/types/ControlParameter']
  106. )
  107. class BKFilter(transformer.TransformerPrimitiveBase[Inputs, Outputs, Hyperparams]):
  108. """
  109. Filter a time series using the Baxter-King bandpass filter.
  110. Parameters
  111. ----------
  112. low: int
  113. Minimum period for oscillations, ie., Baxter and King suggest that the Burns-Mitchell U.S. business cycle has 6 for quarterly data and 1.5 for annual data.
  114. high: int
  115. Maximum period for oscillations BK suggest that the U.S. business cycle has 32 for quarterly data and 8 for annual data.
  116. K: int
  117. Lead-lag length of the filter. Baxter and King propose a truncation length of 12 for quarterly data and 3 for annual data.
  118. use_columns: Set
  119. A set of column indices to force primitive to operate on. If any specified column cannot be parsed, it is skipped.
  120. exclude_columns: Set
  121. A set of column indices to not operate on. Applicable only if \"use_columns\" is not provided.
  122. return_result: Enumeration
  123. Should parsed columns be appended, should they replace original columns, or should only parsed columns be returned? This hyperparam is ignored if use_semantic_types is set to false.
  124. use_semantic_types: Bool
  125. Controls whether semantic_types metadata will be used for filtering columns in input dataframe. Setting this to false makes the code ignore return_result and will produce only the output dataframe.
  126. add_index_columns: Bool
  127. Also include primary index columns if input data has them. Applicable only if \"return_result\" is set to \"new\".
  128. error_on_no_input: Bool(
  129. Throw an exception if no input column is selected/provided. Defaults to true to behave like sklearn. To prevent pipelines from breaking set this to False.
  130. return_semantic_type: Enumeration[str](
  131. Decides what semantic type to attach to generated attributes'
  132. """
  133. __author__: "DATA Lab at Texas A&M University"
  134. metadata = metadata_base.PrimitiveMetadata({
  135. "name": "Baxter-King Filter Primitive",
  136. "python_path": "d3m.primitives.tods.feature_analysis.bk_filter",
  137. "source": {'name': 'DATA Lab at Texas A&M University', 'contact': 'mailto:khlai037@tamu.edu',
  138. 'uris': ['https://gitlab.com/lhenry15/tods.git', 'https://gitlab.com/lhenry15/tods/-/blob/Junjie/anomaly-primitives/anomaly_primitives/DuplicationValidation.py']},
  139. "algorithm_types": [metadata_base.PrimitiveAlgorithmType.BK_FILTER,],
  140. "primitive_family": metadata_base.PrimitiveFamily.FEATURE_CONSTRUCTION,
  141. "id": "b2bfadc5-dbca-482c-b188-8585e5f245c4",
  142. "hyperparams_to_tune": ['low', 'high', 'K'],
  143. "version": "0.0.1",
  144. })
  145. def produce(self, *, inputs: Inputs, timeout: float = None, iterations: int = None) -> CallResult[Outputs]:
  146. """
  147. Process the testing data.
  148. Args:
  149. inputs: Container DataFrame.
  150. Returns:
  151. Container DataFrame after BKFilter.
  152. """
  153. # Get cols to fit.
  154. self._fitted = False
  155. self._training_inputs, self._training_indices = self._get_columns_to_fit(inputs, self.hyperparams)
  156. self._input_column_names = self._training_inputs.columns
  157. if len(self._training_indices) > 0:
  158. # self._clf.fit(self._training_inputs)
  159. self._fitted = True
  160. else:
  161. if self.hyperparams['error_on_no_input']:
  162. raise RuntimeError("No input columns were selected")
  163. self.logger.warn("No input columns were selected")
  164. if not self._fitted:
  165. raise PrimitiveNotFittedError("Primitive not fitted.")
  166. sk_inputs = inputs
  167. if self.hyperparams['use_semantic_types']:
  168. sk_inputs = inputs.iloc[:, self._training_indices]
  169. output_columns = []
  170. if len(self._training_indices) > 0:
  171. sk_output = self._bkfilter(sk_inputs, low=self.hyperparams['low'], high=self.hyperparams['high'], K=self.hyperparams['K'])
  172. if sparse.issparse(sk_output):
  173. sk_output = sk_output.toarray()
  174. outputs = self._wrap_predictions(inputs, sk_output)
  175. if len(outputs.columns) == len(self._input_column_names):
  176. outputs.columns = self._input_column_names
  177. output_columns = [outputs]
  178. else:
  179. if self.hyperparams['error_on_no_input']:
  180. raise RuntimeError("No input columns were selected")
  181. self.logger.warn("No input columns were selected")
  182. outputs = base_utils.combine_columns(return_result=self.hyperparams['return_result'],
  183. add_index_columns=self.hyperparams['add_index_columns'],
  184. inputs=inputs, column_indices=self._training_indices,
  185. columns_list=output_columns)
  186. # self._write(outputs)
  187. # self.logger.warning('produce was called3')
  188. return CallResult(outputs)
  189. @classmethod
  190. def _get_columns_to_fit(cls, inputs: Inputs, hyperparams: Hyperparams):
  191. """
  192. Select columns to fit.
  193. Args:
  194. inputs: Container DataFrame
  195. hyperparams: d3m.metadata.hyperparams.Hyperparams
  196. Returns:
  197. list
  198. """
  199. if not hyperparams['use_semantic_types']:
  200. return inputs, list(range(len(inputs.columns)))
  201. inputs_metadata = inputs.metadata
  202. def can_produce_column(column_index: int) -> bool:
  203. return cls._can_produce_column(inputs_metadata, column_index, hyperparams)
  204. use_columns = []
  205. exclude_columns = []
  206. # if hyperparams['columns_using_method'] == 'name':
  207. # inputs_cols = inputs.columns.values.tolist()
  208. # for i in range(len(inputs_cols)):
  209. # if inputs_cols[i] in hyperparams['use_columns_name']:
  210. # use_columns.append(i)
  211. # elif inputs_cols[i] in hyperparams['exclude_columns_name']:
  212. # exclude_columns.append(i)
  213. # else:
  214. use_columns=hyperparams['use_columns']
  215. exclude_columns=hyperparams['exclude_columns']
  216. columns_to_produce, columns_not_to_produce = base_utils.get_columns_to_use(inputs_metadata, use_columns=use_columns, exclude_columns=exclude_columns, can_use_column=can_produce_column)
  217. return inputs.iloc[:, columns_to_produce], columns_to_produce
  218. # return columns_to_produce
  219. @classmethod
  220. def _can_produce_column(cls, inputs_metadata: metadata_base.DataMetadata, column_index: int, hyperparams: Hyperparams) -> bool:
  221. """
  222. Output whether a column can be processed.
  223. Args:
  224. inputs_metadata: d3m.metadata.base.DataMetadata
  225. column_index: int
  226. Returns:
  227. bool
  228. """
  229. column_metadata = inputs_metadata.query((metadata_base.ALL_ELEMENTS, column_index))
  230. accepted_structural_types = (int, float, numpy.integer, numpy.float64)
  231. accepted_semantic_types = set()
  232. accepted_semantic_types.add("https://metadata.datadrivendiscovery.org/types/Attribute")
  233. if not issubclass(column_metadata['structural_type'], accepted_structural_types):
  234. return False
  235. semantic_types = set(column_metadata.get('semantic_types', []))
  236. if len(semantic_types) == 0:
  237. cls.logger.warning("No semantic types found in column metadata")
  238. return False
  239. # Making sure all accepted_semantic_types are available in semantic_types
  240. if len(accepted_semantic_types - semantic_types) == 0:
  241. return True
  242. return False
  243. @classmethod
  244. def _update_predictions_metadata(cls, inputs_metadata: metadata_base.DataMetadata, outputs: Optional[Outputs],
  245. target_columns_metadata: List[OrderedDict]) -> metadata_base.DataMetadata:
  246. """
  247. Updata metadata for selected columns.
  248. Args:
  249. inputs_metadata: metadata_base.DataMetadata
  250. outputs: Container Dataframe
  251. target_columns_metadata: list
  252. Returns:
  253. d3m.metadata.base.DataMetadata
  254. """
  255. outputs_metadata = metadata_base.DataMetadata().generate(value=outputs)
  256. for column_index, column_metadata in enumerate(target_columns_metadata):
  257. column_metadata.pop("structural_type", None)
  258. outputs_metadata = outputs_metadata.update_column(column_index, column_metadata)
  259. return outputs_metadata
  260. def _wrap_predictions(self, inputs: Inputs, predictions: ndarray) -> Outputs:
  261. """
  262. Wrap predictions into dataframe
  263. Args:
  264. inputs: Container Dataframe
  265. predictions: array-like data (n_samples, n_features)
  266. Returns:
  267. Dataframe
  268. """
  269. outputs = d3m_dataframe(predictions, generate_metadata=True)
  270. target_columns_metadata = self._add_target_columns_metadata(outputs.metadata, self.hyperparams)
  271. outputs.metadata = self._update_predictions_metadata(inputs.metadata, outputs, target_columns_metadata)
  272. return outputs
  273. @classmethod
  274. def _add_target_columns_metadata(cls, outputs_metadata: metadata_base.DataMetadata, hyperparams):
  275. """
  276. Add target columns metadata
  277. Args:
  278. outputs_metadata: metadata.base.DataMetadata
  279. hyperparams: d3m.metadata.hyperparams.Hyperparams
  280. Returns:
  281. List[OrderedDict]
  282. """
  283. outputs_length = outputs_metadata.query((metadata_base.ALL_ELEMENTS,))['dimension']['length']
  284. target_columns_metadata: List[OrderedDict] = []
  285. for column_index in range(outputs_length):
  286. column_name = "output_{}".format(column_index)
  287. column_metadata = OrderedDict()
  288. semantic_types = set()
  289. semantic_types.add(hyperparams["return_semantic_type"])
  290. column_metadata['semantic_types'] = list(semantic_types)
  291. column_metadata["name"] = str(column_name)
  292. target_columns_metadata.append(column_metadata)
  293. return target_columns_metadata
  294. def _write(self, inputs:Inputs):
  295. inputs.to_csv(str(time.time())+'.csv')
  296. def _bkfilter(self, X, low, high, K):
  297. """
  298. Perform BKFilter
  299. Args:
  300. X: slected rows to be performed
  301. K, low, high: Parameters of BKFilter
  302. Returns:
  303. Dataframe, results of BKFilter
  304. """
  305. transformed_X = utils.pandas.DataFrame()
  306. for col in X.columns:
  307. cycle = sm.tsa.filters.bkfilter(X[col], low=low, high=high, K=K)
  308. cycle_df = utils.pandas.DataFrame(cycle)
  309. transformed_X = utils.pandas.concat([transformed_X,cycle_df], axis=1)
  310. return transformed_X

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