imputer.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404
  1. import copy
  2. import functools
  3. import numpy as np
  4. from federatedml.feature.fate_element_type import NoneType
  5. from federatedml.feature.instance import Instance
  6. from federatedml.statistic import data_overview
  7. from federatedml.statistic.data_overview import get_header
  8. from federatedml.statistic.statics import MultivariateStatisticalSummary
  9. from federatedml.util import LOGGER
  10. from federatedml.util import consts
  11. class Imputer(object):
  12. """
  13. This class provides basic strategies for values replacement. It can be used as missing filled or outlier replace.
  14. You can use the statistics such as mean, median or max of each column to fill the missing value or replace outlier.
  15. """
  16. def __init__(self, missing_value_list=None):
  17. """
  18. Parameters
  19. ----------
  20. missing_value_list: list, the value to be replaced. Default None, if is None, it will be set to list of blank, none, null and na,
  21. which regarded as missing filled. If not, it can be outlier replace, and missing_value_list includes the outlier values
  22. """
  23. if missing_value_list is None:
  24. self.missing_value_list = ['', 'none', 'null', 'na', 'None', np.nan]
  25. else:
  26. self.missing_value_list = missing_value_list
  27. self.abnormal_value_list = copy.deepcopy(self.missing_value_list)
  28. for i, v in enumerate(self.missing_value_list):
  29. if v != v:
  30. self.missing_value_list[i] = np.nan
  31. self.abnormal_value_list[i] = NoneType()
  32. self.abnormal_value_set = set(self.abnormal_value_list)
  33. self.support_replace_method = ['min', 'max', 'mean', 'median', 'designated']
  34. self.support_output_format = {
  35. 'str': str,
  36. 'float': float,
  37. 'int': int,
  38. 'origin': None
  39. }
  40. self.support_replace_area = {
  41. 'min': 'col',
  42. 'max': 'col',
  43. 'mean': 'col',
  44. 'median': 'col',
  45. 'designated': 'col'
  46. }
  47. self.cols_fit_impute_rate = []
  48. self.cols_transform_impute_rate = []
  49. self.cols_replace_method = []
  50. self.skip_cols = []
  51. def get_missing_value_list(self):
  52. return self.missing_value_list
  53. def get_cols_replace_method(self):
  54. return self.cols_replace_method
  55. def get_skip_cols(self):
  56. return self.skip_cols
  57. def get_impute_rate(self, mode="fit"):
  58. if mode == "fit":
  59. return list(self.cols_fit_impute_rate)
  60. elif mode == "transform":
  61. return list(self.cols_transform_impute_rate)
  62. else:
  63. raise ValueError("Unknown mode of {}".format(mode))
  64. @staticmethod
  65. def replace_missing_value_with_cols_transform_value_format(data, transform_list, missing_value_list,
  66. output_format, skip_cols):
  67. _data = copy.deepcopy(data)
  68. replace_cols_index_list = []
  69. if isinstance(_data, Instance):
  70. for i, v in enumerate(_data.features):
  71. if v in missing_value_list and i not in skip_cols:
  72. _data.features[i] = output_format(transform_list[i])
  73. replace_cols_index_list.append(i)
  74. else:
  75. _data[i] = output_format(v)
  76. else:
  77. for i, v in enumerate(_data):
  78. if str(v) in missing_value_list and i not in skip_cols:
  79. _data[i] = output_format(transform_list[i])
  80. replace_cols_index_list.append(i)
  81. else:
  82. _data[i] = output_format(v)
  83. return _data, replace_cols_index_list
  84. @staticmethod
  85. def replace_missing_value_with_cols_transform_value(data, transform_list, missing_value_list, skip_cols):
  86. _data = copy.deepcopy(data)
  87. replace_cols_index_list = []
  88. if isinstance(_data, Instance):
  89. new_features = []
  90. for i, v in enumerate(_data.features):
  91. if v in missing_value_list and i not in skip_cols:
  92. # _data.features[i] = transform_list[i]
  93. new_features.append(transform_list[i])
  94. replace_cols_index_list.append(i)
  95. else:
  96. new_features.append(v)
  97. if replace_cols_index_list:
  98. # new features array will have lowest compatible dtype
  99. _data.features = np.array(new_features)
  100. else:
  101. for i, v in enumerate(_data):
  102. if str(v) in missing_value_list and i not in skip_cols:
  103. _data[i] = str(transform_list[i])
  104. replace_cols_index_list.append(i)
  105. return _data, replace_cols_index_list
  106. @staticmethod
  107. def replace_missing_value_with_replace_value_format(data, replace_value, missing_value_list, output_format):
  108. _data = copy.deepcopy(data)
  109. replace_cols_index_list = []
  110. if isinstance(_data, Instance):
  111. for i, v in enumerate(_data.features):
  112. if v in missing_value_list:
  113. _data.features[i] = replace_value
  114. replace_cols_index_list.append(i)
  115. else:
  116. _data[i] = output_format(_data[i])
  117. else:
  118. for i, v in enumerate(_data):
  119. if str(v) in missing_value_list:
  120. _data[i] = output_format(replace_value)
  121. replace_cols_index_list.append(i)
  122. else:
  123. _data[i] = output_format(_data[i])
  124. return _data, replace_cols_index_list
  125. @staticmethod
  126. def replace_missing_value_with_replace_value(data, replace_value, missing_value_list):
  127. _data = copy.deepcopy(data)
  128. replace_cols_index_list = []
  129. if isinstance(_data, Instance):
  130. new_features = []
  131. for i, v in enumerate(_data.features):
  132. if v in missing_value_list:
  133. # _data.features[i] = replace_value
  134. new_features.append(replace_value)
  135. replace_cols_index_list.append(i)
  136. else:
  137. new_features.append(v)
  138. if replace_cols_index_list:
  139. # make sure new features array has lowest compatible dtype
  140. _data.features = np.array(new_features)
  141. else:
  142. for i, v in enumerate(_data):
  143. if str(v) in missing_value_list:
  144. _data[i] = str(replace_value)
  145. replace_cols_index_list.append(i)
  146. return _data, replace_cols_index_list
  147. @staticmethod
  148. def __get_cols_transform_method(data, replace_method, col_replace_method):
  149. header = get_header(data)
  150. if col_replace_method:
  151. replace_method_per_col = {col_name: col_replace_method.get(col_name, replace_method) for col_name in header}
  152. else:
  153. replace_method_per_col = {col_name: replace_method for col_name in header}
  154. skip_cols = [v for v in header if replace_method_per_col[v] is None]
  155. return replace_method_per_col, skip_cols
  156. def __get_cols_transform_value(self, data, replace_method, replace_value=None):
  157. """
  158. Parameters
  159. ----------
  160. data: input data
  161. replace_method: dictionary of (column name, replace_method_name) pairs
  162. Returns
  163. -------
  164. list of transform value for each column, length equal to feature count of input data
  165. """
  166. summary_obj = MultivariateStatisticalSummary(data, -1, abnormal_list=self.abnormal_value_list)
  167. header = get_header(data)
  168. cols_transform_value = {}
  169. if isinstance(replace_value, list):
  170. if len(replace_value) != len(header):
  171. raise ValueError(
  172. f"replace value {replace_value} length does not match with header {header}, please check.")
  173. for i, feature in enumerate(header):
  174. if replace_method[feature] is None:
  175. transform_value = 0
  176. elif replace_method[feature] == consts.MIN:
  177. transform_value = summary_obj.get_min()[feature]
  178. elif replace_method[feature] == consts.MAX:
  179. transform_value = summary_obj.get_max()[feature]
  180. elif replace_method[feature] == consts.MEAN:
  181. transform_value = summary_obj.get_mean()[feature]
  182. elif replace_method[feature] == consts.MEDIAN:
  183. transform_value = summary_obj.get_median()[feature]
  184. elif replace_method[feature] == consts.DESIGNATED:
  185. if isinstance(replace_value, list):
  186. transform_value = replace_value[i]
  187. else:
  188. transform_value = replace_value
  189. LOGGER.debug(f"replace value for feature {feature} is: {transform_value}")
  190. else:
  191. raise ValueError("Unknown replace method:{}".format(replace_method))
  192. cols_transform_value[feature] = transform_value
  193. LOGGER.debug(f"cols_transform value is: {cols_transform_value}")
  194. cols_transform_value = [cols_transform_value[key] for key in header]
  195. # cols_transform_value = {i: round(cols_transform_value[key], 6) for i, key in enumerate(header)}
  196. LOGGER.debug(f"cols_transform value is: {cols_transform_value}")
  197. return cols_transform_value
  198. @staticmethod
  199. def _transform_nan(instance):
  200. feature_shape = instance.features.shape[0]
  201. new_features = []
  202. for i in range(feature_shape):
  203. if instance.features[i] != instance.features[i]:
  204. new_features.append(NoneType())
  205. else:
  206. new_features.append(instance.features[i])
  207. new_instance = copy.deepcopy(instance)
  208. new_instance.features = np.array(new_features)
  209. return new_instance
  210. def __fit_replace(self, data, replace_method, replace_value=None, output_format=None,
  211. col_replace_method=None):
  212. replace_method_per_col, skip_cols = self.__get_cols_transform_method(data, replace_method, col_replace_method)
  213. schema = data.schema
  214. if isinstance(data.first()[1], Instance):
  215. data = data.mapValues(lambda v: Imputer._transform_nan(v))
  216. data.schema = schema
  217. cols_transform_value = self.__get_cols_transform_value(data, replace_method_per_col,
  218. replace_value=replace_value)
  219. self.skip_cols = skip_cols
  220. skip_cols = [get_header(data).index(v) for v in skip_cols]
  221. if output_format is not None:
  222. f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value_format,
  223. transform_list=cols_transform_value, missing_value_list=self.abnormal_value_set,
  224. output_format=output_format, skip_cols=set(skip_cols))
  225. else:
  226. f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value,
  227. transform_list=cols_transform_value, missing_value_list=self.abnormal_value_set,
  228. skip_cols=set(skip_cols))
  229. transform_data = data.mapValues(f)
  230. self.cols_replace_method = replace_method_per_col
  231. LOGGER.info(
  232. "finish replace missing value with cols transform value, replace method is {}".format(replace_method))
  233. return transform_data, cols_transform_value
  234. def __transform_replace(self, data, transform_value, replace_area, output_format, skip_cols):
  235. skip_cols = [get_header(data).index(v) for v in skip_cols]
  236. schema = data.schema
  237. if isinstance(data.first()[1], Instance):
  238. data = data.mapValues(lambda v: Imputer._transform_nan(v))
  239. data.schema = schema
  240. if replace_area == 'all':
  241. if output_format is not None:
  242. f = functools.partial(Imputer.replace_missing_value_with_replace_value_format,
  243. replace_value=transform_value, missing_value_list=self.abnormal_value_set,
  244. output_format=output_format)
  245. else:
  246. f = functools.partial(Imputer.replace_missing_value_with_replace_value,
  247. replace_value=transform_value, missing_value_list=self.abnormal_value_set)
  248. elif replace_area == 'col':
  249. if output_format is not None:
  250. f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value_format,
  251. transform_list=transform_value, missing_value_list=self.abnormal_value_set,
  252. output_format=output_format,
  253. skip_cols=set(skip_cols))
  254. else:
  255. f = functools.partial(Imputer.replace_missing_value_with_cols_transform_value,
  256. transform_list=transform_value, missing_value_list=self.abnormal_value_set,
  257. skip_cols=set(skip_cols))
  258. else:
  259. raise ValueError("Unknown replace area {} in Imputer".format(replace_area))
  260. return data.mapValues(f)
  261. @staticmethod
  262. def __get_impute_number(some_data):
  263. impute_num_list = None
  264. data_size = None
  265. for line in some_data:
  266. processed_data = line[1][0]
  267. index_list = line[1][1]
  268. if not data_size:
  269. if isinstance(processed_data, Instance):
  270. data_size = data_overview.get_instance_shape(processed_data)
  271. else:
  272. data_size = len(processed_data)
  273. # data_size + 1, the last element of impute_num_list used to count the number of "some_data"
  274. impute_num_list = [0 for _ in range(data_size + 1)]
  275. impute_num_list[data_size] += 1
  276. for index in index_list:
  277. impute_num_list[index] += 1
  278. return np.array(impute_num_list)
  279. def __get_impute_rate_from_replace_data(self, data):
  280. impute_number_statics = data.applyPartitions(self.__get_impute_number).reduce(lambda x, y: x + y)
  281. cols_impute_rate = impute_number_statics[:-1] / impute_number_statics[-1]
  282. return cols_impute_rate
  283. def fit(self, data, replace_method=None, replace_value=None, output_format=consts.ORIGIN,
  284. col_replace_method=None):
  285. """
  286. Apply imputer for input data
  287. Parameters
  288. ----------
  289. data: Table, each data's value should be list
  290. replace_method: str, the strategy of imputer, like min, max, mean or designated and so on. Default None
  291. replace_value: str, if replace_method is designated, you should assign the replace_value which will be used to replace the value in imputer_value_list
  292. output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data
  293. col_replace_method: dict of (col_name, replace_method), any col_name not included will take replace_method
  294. Returns
  295. ----------
  296. fit_data:data_instance, data after imputer
  297. cols_transform_value: list, the replace value in each column
  298. """
  299. if output_format not in self.support_output_format:
  300. raise ValueError("Unsupport output_format:{}".format(output_format))
  301. output_format = self.support_output_format[output_format]
  302. if isinstance(replace_method, str):
  303. replace_method = replace_method.lower()
  304. if replace_method not in self.support_replace_method:
  305. raise ValueError("Unknown replace method:{}".format(replace_method))
  306. elif replace_method is None and col_replace_method is None:
  307. if isinstance(data.first()[1], Instance):
  308. replace_value = 0
  309. else:
  310. replace_value = '0'
  311. elif replace_method is None and col_replace_method is not None:
  312. LOGGER.debug(f"perform computation on selected cols only: {col_replace_method}")
  313. else:
  314. raise ValueError("parameter replace_method should be str or None only")
  315. if isinstance(col_replace_method, dict):
  316. for col_name, method in col_replace_method.items():
  317. method = method.lower()
  318. if method not in self.support_replace_method:
  319. raise ValueError("Unknown replace method:{}".format(method))
  320. col_replace_method[col_name] = method
  321. process_data, cols_transform_value = self.__fit_replace(data, replace_method, replace_value, output_format,
  322. col_replace_method=col_replace_method)
  323. self.cols_fit_impute_rate = self.__get_impute_rate_from_replace_data(process_data)
  324. process_data = process_data.mapValues(lambda v: v[0])
  325. process_data.schema = data.schema
  326. return process_data, cols_transform_value
  327. def transform(self, data, transform_value, output_format=consts.ORIGIN, skip_cols=None):
  328. """
  329. Transform input data using Imputer with fit results
  330. Parameters
  331. ----------
  332. data: Table, each data's value should be list
  333. transform_value:
  334. output_format: str, the output data format. The output data can be 'str', 'int', 'float'. Default origin, the original format as input data
  335. Returns
  336. ----------
  337. transform_data:data_instance, data after transform
  338. """
  339. if output_format not in self.support_output_format:
  340. raise ValueError("Unsupport output_format:{}".format(output_format))
  341. output_format = self.support_output_format[output_format]
  342. skip_cols = [] if skip_cols is None else skip_cols
  343. # Now all of replace_method is "col", remain replace_area temporarily
  344. # replace_area = self.support_replace_area[replace_method]
  345. replace_area = "col"
  346. process_data = self.__transform_replace(data, transform_value, replace_area, output_format, skip_cols)
  347. self.cols_transform_impute_rate = self.__get_impute_rate_from_replace_data(process_data)
  348. process_data = process_data.mapValues(lambda v: v[0])
  349. process_data.schema = data.schema
  350. return process_data