feature_selection_param.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. import copy
  4. #
  5. # Copyright 2019 The FATE Authors. All Rights Reserved.
  6. #
  7. # Licensed under the Apache License, Version 2.0 (the "License");
  8. # you may not use this file except in compliance with the License.
  9. # You may obtain a copy of the License at
  10. #
  11. # http://www.apache.org/licenses/LICENSE-2.0
  12. #
  13. # Unless required by applicable law or agreed to in writing, software
  14. # distributed under the License is distributed on an "AS IS" BASIS,
  15. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  16. # See the License for the specific language governing permissions and
  17. # limitations under the License.
  18. #
  19. from pipeline.param.base_param import BaseParam
  20. from pipeline.param import consts
  21. class UniqueValueParam(BaseParam):
  22. """
  23. Use the difference between max-value and min-value to judge.
  24. Parameters
  25. ----------
  26. eps: float, default: 1e-5
  27. The column(s) will be filtered if its difference is smaller than eps.
  28. """
  29. def __init__(self, eps=1e-5):
  30. self.eps = eps
  31. def check(self):
  32. descr = "Unique value param's"
  33. self.check_positive_number(self.eps, descr)
  34. return True
  35. class IVValueSelectionParam(BaseParam):
  36. """
  37. Use information values to select features.
  38. Parameters
  39. ----------
  40. value_threshold: float, default: 1.0
  41. Used if iv_value_thres method is used in feature selection.
  42. host_thresholds: List of float or None, default: None
  43. Set threshold for different host. If None, use same threshold as guest. If provided, the order should map with
  44. the host id setting.
  45. """
  46. def __init__(self, value_threshold=0.0, host_thresholds=None, local_only=False):
  47. super().__init__()
  48. self.value_threshold = value_threshold
  49. self.host_thresholds = host_thresholds
  50. self.local_only = local_only
  51. def check(self):
  52. if not isinstance(self.value_threshold, (float, int)):
  53. raise ValueError("IV selection param's value_threshold should be float or int")
  54. if self.host_thresholds is not None:
  55. if not isinstance(self.host_thresholds, list):
  56. raise ValueError("IV selection param's host_threshold should be list or None")
  57. if not isinstance(self.local_only, bool):
  58. raise ValueError("IV selection param's local_only should be bool")
  59. return True
  60. class IVPercentileSelectionParam(BaseParam):
  61. """
  62. Use information values to select features.
  63. Parameters
  64. ----------
  65. percentile_threshold: float, 0 <= percentile_threshold <= 1.0, default: 1.0
  66. Percentile threshold for iv_percentile method
  67. """
  68. def __init__(self, percentile_threshold=1.0, local_only=False):
  69. super().__init__()
  70. self.percentile_threshold = percentile_threshold
  71. self.local_only = local_only
  72. def check(self):
  73. descr = "IV selection param's"
  74. self.check_decimal_float(self.percentile_threshold, descr)
  75. self.check_boolean(self.local_only, descr)
  76. return True
  77. class IVTopKParam(BaseParam):
  78. """
  79. Use information values to select features.
  80. Parameters
  81. ----------
  82. k: int, should be greater than 0, default: 10
  83. Percentile threshold for iv_percentile method
  84. """
  85. def __init__(self, k=10, local_only=False):
  86. super().__init__()
  87. self.k = k
  88. self.local_only = local_only
  89. def check(self):
  90. descr = "IV selection param's"
  91. self.check_positive_integer(self.k, descr)
  92. self.check_boolean(self.local_only, descr)
  93. return True
  94. class VarianceOfCoeSelectionParam(BaseParam):
  95. """
  96. Use coefficient of variation to select features. When judging, the absolute value will be used.
  97. Parameters
  98. ----------
  99. value_threshold: float, default: 1.0
  100. Used if coefficient_of_variation_value_thres method is used in feature selection. Filter those
  101. columns who has smaller coefficient of variance than the threshold.
  102. """
  103. def __init__(self, value_threshold=1.0):
  104. self.value_threshold = value_threshold
  105. def check(self):
  106. descr = "Coff of Variances param's"
  107. self.check_positive_number(self.value_threshold, descr)
  108. return True
  109. class OutlierColsSelectionParam(BaseParam):
  110. """
  111. Given percentile and threshold. Judge if this quantile point is larger than threshold. Filter those larger ones.
  112. Parameters
  113. ----------
  114. percentile: float, [0., 1.] default: 1.0
  115. The percentile points to compare.
  116. upper_threshold: float, default: 1.0
  117. Percentile threshold for coefficient_of_variation_percentile method
  118. """
  119. def __init__(self, percentile=1.0, upper_threshold=1.0):
  120. self.percentile = percentile
  121. self.upper_threshold = upper_threshold
  122. def check(self):
  123. descr = "Outlier Filter param's"
  124. self.check_decimal_float(self.percentile, descr)
  125. self.check_defined_type(self.upper_threshold, descr, ['float', 'int'])
  126. return True
  127. class CommonFilterParam(BaseParam):
  128. """
  129. All of the following parameters can set with a single value or a list of those values.
  130. When setting one single value, it means using only one metric to filter while
  131. a list represent for using multiple metrics.
  132. Please note that if some of the following values has been set as list, all of them
  133. should have same length. Otherwise, error will be raised. And if there exist a list
  134. type parameter, the metrics should be in list type.
  135. Parameters
  136. ----------
  137. metrics: str or list, default: depends on the specific filter
  138. Indicate what metrics are used in this filter
  139. filter_type: str, default: threshold
  140. Should be one of "threshold", "top_k" or "top_percentile"
  141. take_high: bool, default: True
  142. When filtering, taking highest values or not.
  143. threshold: float or int, default: 1
  144. If filter type is threshold, this is the threshold value.
  145. If it is "top_k", this is the k value.
  146. If it is top_percentile, this is the percentile threshold.
  147. host_thresholds: List of float or List of List of float or None, default: None
  148. Set threshold for different host. If None, use same threshold as guest. If provided, the order should map with
  149. the host id setting.
  150. select_federated: bool, default: True
  151. Whether select federated with other parties or based on local variables
  152. """
  153. def __init__(self, metrics, filter_type='threshold', take_high=True, threshold=1,
  154. host_thresholds=None, select_federated=True):
  155. super().__init__()
  156. self.metrics = metrics
  157. self.filter_type = filter_type
  158. self.take_high = take_high
  159. self.threshold = threshold
  160. self.host_thresholds = host_thresholds
  161. self.select_federated = select_federated
  162. def check(self):
  163. if not isinstance(self.metrics, list):
  164. for value_name in ["filter_type", "take_high",
  165. "threshold", "select_federated"]:
  166. v = getattr(self, value_name)
  167. if isinstance(v, list):
  168. raise ValueError(f"{value_name}: {v} should not be a list when "
  169. f"metrics: {self.metrics} is not a list")
  170. setattr(self, value_name, [v])
  171. setattr(self, "metrics", [self.metrics])
  172. else:
  173. expected_length = len(self.metrics)
  174. for value_name in ["filter_type", "take_high",
  175. "threshold", "select_federated"]:
  176. v = getattr(self, value_name)
  177. if isinstance(v, list):
  178. if len(v) != expected_length:
  179. raise ValueError(f"The parameter {v} should have same length "
  180. f"with metrics")
  181. else:
  182. new_v = [v] * expected_length
  183. setattr(self, value_name, new_v)
  184. for v in self.filter_type:
  185. if v not in ["threshold", "top_k", "top_percentile"]:
  186. raise ValueError('filter_type should be one of '
  187. '"threshold", "top_k", "top_percentile"')
  188. descr = "hetero feature selection param's"
  189. for v in self.take_high:
  190. self.check_boolean(v, descr)
  191. for idx, v in enumerate(self.threshold):
  192. if self.filter_type[idx] == "threshold":
  193. if not isinstance(v, (float, int)):
  194. raise ValueError(descr + f"{v} should be a float or int")
  195. elif self.filter_type[idx] == 'top_k':
  196. self.check_positive_integer(v, descr)
  197. else:
  198. if not (v == 0 or v == 1):
  199. self.check_decimal_float(v, descr)
  200. if self.host_thresholds is not None:
  201. if not isinstance(self.host_thresholds, list):
  202. self.host_thresholds = [self.host_thresholds]
  203. # raise ValueError("selection param's host_threshold should be list or None")
  204. assert isinstance(self.select_federated, list)
  205. for v in self.select_federated:
  206. self.check_boolean(v, descr)
  207. class CorrelationFilterParam(BaseParam):
  208. """
  209. This filter follow this specific rules:
  210. 1. Sort all the columns from high to low based on specific metric, eg. iv.
  211. 2. Traverse each sorted column. If there exists other columns with whom the
  212. absolute values of correlation are larger than threshold, they will be filtered.
  213. Parameters
  214. ----------
  215. sort_metric: str, default: iv
  216. Specify which metric to be used to sort features.
  217. threshold: float or int, default: 0.1
  218. Correlation threshold
  219. select_federated: bool, default: True
  220. Whether select federated with other parties or based on local variables
  221. """
  222. def __init__(self, sort_metric='iv', threshold=0.1, select_federated=True):
  223. super().__init__()
  224. self.sort_metric = sort_metric
  225. self.threshold = threshold
  226. self.select_federated = select_federated
  227. def check(self):
  228. descr = "Correlation Filter param's"
  229. self.sort_metric = self.sort_metric.lower()
  230. support_metrics = ['iv']
  231. if self.sort_metric not in support_metrics:
  232. raise ValueError(f"sort_metric in Correlation Filter should be one of {support_metrics}")
  233. self.check_positive_number(self.threshold, descr)
  234. class PercentageValueParam(BaseParam):
  235. """
  236. Filter the columns that have a value that exceeds a certain percentage.
  237. Parameters
  238. ----------
  239. upper_pct: float, [0.1, 1.], default: 1.0
  240. The upper percentage threshold for filtering, upper_pct should not be less than 0.1.
  241. """
  242. def __init__(self, upper_pct=1.0):
  243. super().__init__()
  244. self.upper_pct = upper_pct
  245. def check(self):
  246. descr = "Percentage Filter param's"
  247. if self.upper_pct not in [0, 1]:
  248. self.check_decimal_float(self.upper_pct, descr)
  249. if self.upper_pct < consts.PERCENTAGE_VALUE_LIMIT:
  250. raise ValueError(descr + f" {self.upper_pct} not supported,"
  251. f" should not be smaller than {consts.PERCENTAGE_VALUE_LIMIT}")
  252. return True
  253. class ManuallyFilterParam(BaseParam):
  254. """
  255. Specified columns that need to be filtered. If exist, it will be filtered directly, otherwise, ignore it.
  256. Both Filter_out or left parameters only works for this specific filter. For instances, if you set some columns left
  257. in this filter but those columns are filtered by other filters, those columns will NOT left in final.
  258. Please note that (left_col_indexes & left_col_names) cannot use with
  259. (filter_out_indexes & filter_out_names) simultaneously.
  260. Parameters
  261. ----------
  262. filter_out_indexes: list of int, default: None
  263. Specify columns' indexes to be filtered out
  264. Note tha columns specified by `filter_out_indexes` and `filter_out_names` will be combined.
  265. filter_out_names : list of string, default: None
  266. Specify columns' names to be filtered out
  267. Note tha columns specified by `filter_out_indexes` and `filter_out_names` will be combined.
  268. left_col_indexes: list of int, default: None
  269. Specify left_col_index
  270. Note tha columns specified by `left_col_indexes` and `left_col_names` will be combined.
  271. left_col_names: list of string, default: None
  272. Specify left col names
  273. Note tha columns specified by `left_col_indexes` and `left_col_names` will be combined.
  274. """
  275. def __init__(self, filter_out_indexes=None, filter_out_names=None, left_col_indexes=None,
  276. left_col_names=None):
  277. super().__init__()
  278. self.filter_out_indexes = filter_out_indexes
  279. self.filter_out_names = filter_out_names
  280. self.left_col_indexes = left_col_indexes
  281. self.left_col_names = left_col_names
  282. def check(self):
  283. descr = "Manually Filter param's"
  284. self.check_defined_type(self.filter_out_indexes, descr, ['list', 'NoneType'])
  285. self.check_defined_type(self.filter_out_names, descr, ['list', 'NoneType'])
  286. self.check_defined_type(self.left_col_indexes, descr, ['list', 'NoneType'])
  287. self.check_defined_type(self.left_col_names, descr, ['list', 'NoneType'])
  288. if (self.filter_out_indexes or self.filter_out_names) is not None and \
  289. (self.left_col_names or self.left_col_indexes) is not None:
  290. raise ValueError("(left_col_indexes & left_col_names) cannot use with"
  291. " (filter_out_indexes & filter_out_names) simultaneously")
  292. return True
  293. class FeatureSelectionParam(BaseParam):
  294. """
  295. Define the feature selection parameters.
  296. Parameters
  297. ----------
  298. select_col_indexes: list or int, default: -1
  299. Specify which columns need to calculated. -1 represent for all columns.
  300. Note tha columns specified by `select_col_indexes` and `select_names` will be combined.
  301. select_names : list of string, default: []
  302. Specify which columns need to calculated. Each element in the list represent for a column name in header.
  303. Note tha columns specified by `select_col_indexes` and `select_names` will be combined.
  304. filter_methods: list, ["manually", "iv_filter", "statistic_filter",
  305. "psi_filter", “hetero_sbt_filter", "homo_sbt_filter",
  306. "hetero_fast_sbt_filter", "percentage_value",
  307. "vif_filter", "correlation_filter"],
  308. default: ["manually"]
  309. The following methods will be deprecated in future version:
  310. "unique_value", "iv_value_thres", "iv_percentile",
  311. "coefficient_of_variation_value_thres", "outlier_cols"
  312. Specify the filter methods used in feature selection. The orders of filter used is depended on this list.
  313. Please be notified that, if a percentile method is used after some certain filter method,
  314. the percentile represent for the ratio of rest features.
  315. e.g. If you have 10 features at the beginning. After first filter method, you have 8 rest. Then, you want
  316. top 80% highest iv feature. Here, we will choose floor(0.8 * 8) = 6 features instead of 8.
  317. unique_param: filter the columns if all values in this feature is the same
  318. iv_value_param: Use information value to filter columns. If this method is set, a float threshold need to be provided.
  319. Filter those columns whose iv is smaller than threshold. Will be deprecated in the future.
  320. iv_percentile_param: Use information value to filter columns. If this method is set, a float ratio threshold
  321. need to be provided. Pick floor(ratio * feature_num) features with higher iv. If multiple features around
  322. the threshold are same, all those columns will be keep. Will be deprecated in the future.
  323. variance_coe_param: Use coefficient of variation to judge whether filtered or not.
  324. Will be deprecated in the future.
  325. outlier_param: Filter columns whose certain percentile value is larger than a threshold.
  326. Will be deprecated in the future.
  327. percentage_value_param: Filter the columns that have a value that exceeds a certain percentage.
  328. iv_param: Setting how to filter base on iv. It support take high mode only. All of "threshold",
  329. "top_k" and "top_percentile" are accepted. Check more details in CommonFilterParam. To
  330. use this filter, hetero-feature-binning module has to be provided.
  331. statistic_param: Setting how to filter base on statistic values. All of "threshold",
  332. "top_k" and "top_percentile" are accepted. Check more details in CommonFilterParam.
  333. To use this filter, data_statistic module has to be provided.
  334. psi_param: Setting how to filter base on psi values. All of "threshold",
  335. "top_k" and "top_percentile" are accepted. Its take_high properties should be False
  336. to choose lower psi features. Check more details in CommonFilterParam.
  337. To use this filter, data_statistic module has to be provided.
  338. use_anonymous: bool, default False
  339. whether to interpret 'select_names' as anonymous names.
  340. need_run: bool, default True
  341. Indicate if this module needed to be run
  342. """
  343. def __init__(self, select_col_indexes=-1, select_names=None, filter_methods=None,
  344. unique_param=UniqueValueParam(),
  345. iv_value_param=IVValueSelectionParam(),
  346. iv_percentile_param=IVPercentileSelectionParam(),
  347. iv_top_k_param=IVTopKParam(),
  348. variance_coe_param=VarianceOfCoeSelectionParam(),
  349. outlier_param=OutlierColsSelectionParam(),
  350. manually_param=ManuallyFilterParam(),
  351. percentage_value_param=PercentageValueParam(),
  352. iv_param=CommonFilterParam(metrics=consts.IV),
  353. statistic_param=CommonFilterParam(metrics=consts.MEAN),
  354. psi_param=CommonFilterParam(metrics=consts.PSI,
  355. take_high=False),
  356. vif_param=CommonFilterParam(metrics=consts.VIF,
  357. threshold=5.0,
  358. take_high=False),
  359. sbt_param=CommonFilterParam(metrics=consts.FEATURE_IMPORTANCE),
  360. correlation_param=CorrelationFilterParam(),
  361. use_anonymous=False,
  362. need_run=True
  363. ):
  364. super(FeatureSelectionParam, self).__init__()
  365. self.correlation_param = correlation_param
  366. self.vif_param = vif_param
  367. self.select_col_indexes = select_col_indexes
  368. if select_names is None:
  369. self.select_names = []
  370. else:
  371. self.select_names = select_names
  372. if filter_methods is None:
  373. self.filter_methods = [consts.MANUALLY_FILTER]
  374. else:
  375. self.filter_methods = filter_methods
  376. # deprecate in the future
  377. self.unique_param = copy.deepcopy(unique_param)
  378. self.iv_value_param = copy.deepcopy(iv_value_param)
  379. self.iv_percentile_param = copy.deepcopy(iv_percentile_param)
  380. self.iv_top_k_param = copy.deepcopy(iv_top_k_param)
  381. self.variance_coe_param = copy.deepcopy(variance_coe_param)
  382. self.outlier_param = copy.deepcopy(outlier_param)
  383. self.percentage_value_param = copy.deepcopy(percentage_value_param)
  384. self.manually_param = copy.deepcopy(manually_param)
  385. self.iv_param = copy.deepcopy(iv_param)
  386. self.statistic_param = copy.deepcopy(statistic_param)
  387. self.psi_param = copy.deepcopy(psi_param)
  388. self.sbt_param = copy.deepcopy(sbt_param)
  389. self.need_run = need_run
  390. self.use_anonymous = use_anonymous
  391. def check(self):
  392. descr = "hetero feature selection param's"
  393. self.check_defined_type(self.filter_methods, descr, ['list'])
  394. for idx, method in enumerate(self.filter_methods):
  395. method = method.lower()
  396. self.check_valid_value(method, descr, [consts.UNIQUE_VALUE, consts.IV_VALUE_THRES, consts.IV_PERCENTILE,
  397. consts.COEFFICIENT_OF_VARIATION_VALUE_THRES, consts.OUTLIER_COLS,
  398. consts.MANUALLY_FILTER, consts.PERCENTAGE_VALUE,
  399. consts.IV_FILTER, consts.STATISTIC_FILTER, consts.IV_TOP_K,
  400. consts.PSI_FILTER, consts.HETERO_SBT_FILTER,
  401. consts.HOMO_SBT_FILTER, consts.HETERO_FAST_SBT_FILTER,
  402. consts.VIF_FILTER, consts.CORRELATION_FILTER])
  403. self.filter_methods[idx] = method
  404. self.check_defined_type(self.select_col_indexes, descr, ['list', 'int'])
  405. self.unique_param.check()
  406. self.iv_value_param.check()
  407. self.iv_percentile_param.check()
  408. self.iv_top_k_param.check()
  409. self.variance_coe_param.check()
  410. self.outlier_param.check()
  411. self.manually_param.check()
  412. self.percentage_value_param.check()
  413. self.iv_param.check()
  414. for th in self.iv_param.take_high:
  415. if not th:
  416. raise ValueError("Iv filter should take higher iv features")
  417. for m in self.iv_param.metrics:
  418. if m != consts.IV:
  419. raise ValueError("For iv filter, metrics should be 'iv'")
  420. self.statistic_param.check()
  421. self.psi_param.check()
  422. for th in self.psi_param.take_high:
  423. if th:
  424. raise ValueError("PSI filter should take lower psi features")
  425. for m in self.psi_param.metrics:
  426. if m != consts.PSI:
  427. raise ValueError("For psi filter, metrics should be 'psi'")
  428. self.sbt_param.check()
  429. for th in self.sbt_param.take_high:
  430. if not th:
  431. raise ValueError("SBT filter should take higher feature_importance features")
  432. for m in self.sbt_param.metrics:
  433. if m != consts.FEATURE_IMPORTANCE:
  434. raise ValueError("For SBT filter, metrics should be 'feature_importance'")
  435. self.vif_param.check()
  436. for m in self.vif_param.metrics:
  437. if m != consts.VIF:
  438. raise ValueError("For VIF filter, metrics should be 'vif'")
  439. self.correlation_param.check()