risk.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. """
  2. Health Information Privacy Lab
  3. Brad. Malin, Weiyi Xia, Steve L. Nyemba
  4. This framework computes re-identification risk of a dataset assuming the data being shared can be loaded into a dataframe (pandas)
  5. The framework will compute the following risk measures:
  6. - marketer
  7. - prosecutor
  8. - pitman
  9. References :
  10. https://www.scb.se/contentassets/ff271eeeca694f47ae99b942de61df83/applying-pitmans-sampling-formula-to-microdata-disclosure-risk-assessment.pdf
  11. This framework integrates pandas (for now) as an extension and can be used in two modes :
  12. Experimental mode
  13. Here the assumption is that we are not sure of the attributes to be disclosed, the framework will explore a variety of combinations and associate risk measures every random combinations
  14. Evaluation mode
  15. The evaluation mode assumes the set of attributes given are known and thus will evaluate risk for a subset of attributes.
  16. features :
  17. - determine viable fields (quantifiable in terms of uniqueness). This is a way to identify fields that can act as identifiers.
  18. - explore and evaluate risk of a sample dataset against a known population dataset
  19. - explore and evaluate risk on a sample dataset
  20. Usage:
  21. from pandas_risk import *
  22. mydataframe = pd.DataFrame('/myfile.csv')
  23. resp = mydataframe.risk.evaluate(id=<name of patient field>,num_runs=<number of runs>,cols=[])
  24. resp = mydataframe.risk.explore(id=<name of patient field>,num_runs=<number of runs>,cols=[])
  25. @TODO:
  26. - Provide a selected number of fields and risk will be computed for those fields.
  27. - include journalist risk
  28. """
  29. import pandas as pd
  30. import numpy as np
  31. import logging
  32. import json
  33. from datetime import datetime
  34. import sys
  35. from itertools import combinations
  36. @pd.api.extensions.register_dataframe_accessor("risk")
  37. class deid :
  38. """
  39. This class is a deidentification class that will compute risk (marketer, prosecutor) given a pandas dataframe
  40. """
  41. def __init__(self,df):
  42. self._df = df.fillna(' ')
  43. #
  44. # Let's get the distribution of the values so we know what how unique the fields are
  45. #
  46. values = df.apply(lambda col: col.unique().size / df.shape[0])
  47. self._dinfo = dict(zip(df.columns.tolist(),values))
  48. def explore(self,**args):
  49. """
  50. This function will perform experimentation by performing a random policies (combinations of attributes)
  51. This function is intended to explore a variety of policies and evaluate their associated risk.
  52. :pop|sample data-frame with population or sample reference
  53. :field_count number of fields to randomly select
  54. :strict if set the field_count is exact otherwise field_count is range from 2-field_count
  55. :num_runs number of runs (by default 5)
  56. """
  57. pop= args['pop'] if 'pop' in args else None
  58. if 'pop_size' in args :
  59. pop_size = np.float64(args['pop_size'])
  60. else:
  61. pop_size = -1
  62. #
  63. # Policies will be generated with a number of runs
  64. #
  65. RUNS = args['num_runs'] if 'num_runs' in args else 5
  66. sample = args['sample'] if 'sample' in args else pd.DataFrame(self._df)
  67. k = sample.columns.size if 'field_count' not in args else int(args['field_count']) +1
  68. #
  69. # remove fields that are unique, they function as identifiers
  70. #
  71. if 'id' in args :
  72. id = args['id']
  73. columns = list(set(sample.columns.tolist()) - set([id]))
  74. else:
  75. columns = sample.columns.tolist()
  76. # If columns are not specified we can derive them from self._dinfo
  77. # given the distribution all fields that are < 1 will be accounted for
  78. # columns = args['cols'] if 'cols' in args else [key for key in self._dinfo if self._dinfo[key] < 1]
  79. o = pd.DataFrame()
  80. columns = [key for key in self._dinfo if self._dinfo[key] < 1]
  81. _policy_count = 2 if 'policy_count' not in args else int(args['policy_count'])
  82. _policies = []
  83. _index = 0
  84. for size in np.arange(2,len(columns)) :
  85. p = list(combinations(columns,size))
  86. p = (np.array(p)[ np.random.choice( len(p), _policy_count)].tolist())
  87. flag = 'Policy_'+str(_index)
  88. _index += 1
  89. for cols in p :
  90. r = self.evaluate(sample=sample,cols=cols,flag = flag)
  91. p = pd.DataFrame(1*sample.columns.isin(cols)).T
  92. p.columns = sample.columns
  93. o = pd.concat([o,r.join(p)])
  94. # for i in np.arange(RUNS):
  95. # if 'strict' not in args or ('strict' in args and args['strict'] is False):
  96. # n = np.random.randint(2,k)
  97. # else:
  98. # n = args['field_count']
  99. # cols = np.random.choice(columns,n,replace=False).tolist()
  100. # params = {'sample':sample,'cols':cols}
  101. # if pop is not None :
  102. # params['pop'] = pop
  103. # if pop_size > 0 :
  104. # params['pop_size'] = pop_size
  105. # r = self.evaluate(**params)
  106. # #
  107. # # let's put the policy in place
  108. # p = pd.DataFrame(1*sample.columns.isin(cols)).T
  109. # p.columns = sample.columns
  110. # # o = o.append(r.join(p))
  111. # o = pd.concat([o,r.join(p)])
  112. o.index = np.arange(o.shape[0]).astype(np.int64)
  113. return o
  114. def evaluate(self, **args):
  115. """
  116. This function has the ability to evaluate risk associated with either a population or a sample dataset
  117. :sample sample dataset
  118. :pop population dataset
  119. :cols list of columns of interest or policies
  120. :flag user provided flag for the context of the evaluation
  121. """
  122. if 'sample' in args :
  123. sample = pd.DataFrame(args['sample'])
  124. else:
  125. sample = pd.DataFrame(self._df)
  126. if not args or 'cols' not in args:
  127. # cols = sample.columns.tolist()
  128. cols = [key for key in self._dinfo if self._dinfo[key] < 1]
  129. elif args and 'cols' in args:
  130. cols = args['cols']
  131. #
  132. #
  133. flag = 'UNFLAGGED' if 'flag' not in args else args['flag']
  134. #
  135. # @TODO: auto select the columns i.e removing the columns that will have the effect of an identifier
  136. #
  137. # if 'population' in args :
  138. # pop = pd.DataFrame(args['population'])
  139. r = {"flag":flag}
  140. # if sample :
  141. handle_sample = Sample()
  142. xi = sample.groupby(cols,as_index=False).count().values
  143. handle_sample.set('groups',xi)
  144. if 'pop_size' in args :
  145. pop_size = np.float64(args['pop_size'])
  146. else:
  147. pop_size = -1
  148. #
  149. #-- The following conditional line is to address the labels that will be returned
  150. # @TODO: Find a more elegant way of doing this.
  151. #
  152. if 'pop' in args :
  153. label_market = 'sample marketer'
  154. label_prosec = 'sample prosecutor'
  155. label_groupN = 'sample group count'
  156. label_unique = 'sample journalist' #'sample unique ratio'
  157. # r['sample marketer'] = handle_sample.marketer()
  158. # r['sample prosecutor'] = handle_sample.prosecutor()
  159. # r['sample unique ratio'] = handle_sample.unique_ratio()
  160. # r['sample group count'] = xi.size
  161. # r['sample group count'] = len(xi)
  162. else:
  163. label_market = 'marketer'
  164. label_prosec = 'prosecutor'
  165. label_groupN = 'group count'
  166. label_unique = 'journalist' #'unique ratio'
  167. # r['marketer'] = handle_sample.marketer()
  168. # r['prosecutor'] = handle_sample.prosecutor()
  169. # r['unique ratio'] = handle_sample.unique_ratio()
  170. # r['group count'] = xi.size
  171. # r['group count'] = len(xi)
  172. if pop_size > 0 :
  173. handle_sample.set('pop_size',pop_size)
  174. r['pitman risk'] = handle_sample.pitman()
  175. r[label_market] = handle_sample.marketer()
  176. r[label_unique] = handle_sample.unique_ratio()
  177. r[label_prosec] = handle_sample.prosecutor()
  178. r[label_groupN] = len(xi)
  179. if 'pop' in args :
  180. xi = pd.DataFrame({"sample_group_size":sample.groupby(cols,as_index=False).count()}).reset_index()
  181. yi = pd.DataFrame({"population_group_size":args['pop'].groupby(cols,as_index=False).size()}).reset_index()
  182. merged_groups = pd.merge(xi,yi,on=cols,how='inner')
  183. handle_population= Population()
  184. handle_population.set('merged_groups',merged_groups)
  185. r['pop. marketer'] = handle_population.marketer()
  186. r['pitman risk'] = handle_population.pitman()
  187. r['pop. group size'] = np.unique(yi.population_group_size).size
  188. #
  189. # At this point we have both columns for either sample,population or both
  190. #
  191. r['field count'] = len(cols)
  192. return pd.DataFrame([r])
  193. class Risk :
  194. """
  195. This class is an abstraction of how we chose to structure risk computation i.e in 2 sub classes:
  196. - Sample computes risk associated with a sample dataset only
  197. - Population computes risk associated with a population
  198. """
  199. def __init__(self):
  200. self.cache = {}
  201. def set(self,key,value):
  202. if id not in self.cache :
  203. self.cache[id] = {}
  204. self.cache[key] = value
  205. class Sample(Risk):
  206. """
  207. This class will compute risk for the sample dataset: the marketer and prosecutor risk are computed by default.
  208. This class can optionally add pitman risk if the population size is known.
  209. """
  210. def __init__(self):
  211. Risk.__init__(self)
  212. def marketer(self):
  213. """
  214. computing marketer risk for sample dataset
  215. """
  216. groups = self.cache['groups']
  217. # group_count = groups.size
  218. # row_count = groups.sum()
  219. group_count = len(groups)
  220. row_count = np.sum([_g[-1] for _g in groups])
  221. return group_count / np.float64(row_count)
  222. def prosecutor(self):
  223. """
  224. The prosecutor risk consists in determining 1 over the smallest group size
  225. It identifies if there is at least one record that is unique
  226. """
  227. groups = self.cache['groups']
  228. _min = np.min([_g[-1] for _g in groups])
  229. # return 1 / np.float64(groups.min())
  230. return 1/ np.float64(_min)
  231. def unique_ratio(self):
  232. groups = self.cache['groups']
  233. # row_count = groups.sum()
  234. row_count = np.sum([_g[-1] for _g in groups])
  235. # return groups[groups == 1].sum() / np.float64(row_count)
  236. values = [_g[-1] for _g in groups if _g[-1] == 1]
  237. return np.sum(values) / np.float64(row_count)
  238. def pitman(self):
  239. """
  240. This function will approximate pitman de-identification risk based on pitman sampling
  241. """
  242. groups = self.cache['groups']
  243. si = groups[groups == 1].size
  244. # u = groups.size
  245. u = len(groups)
  246. alpha = np.divide(si , np.float64(u) )
  247. row_count = np.sum([_g[-1] for _g in groups])
  248. # f = np.divide(groups.sum(), np.float64(self.cache['pop_size']))
  249. f = np.divide(row_count, np.float64(self.cache['pop_size']))
  250. return np.power(f,1-alpha)
  251. class Population(Sample):
  252. """
  253. This class will compute risk for datasets that have population information or datasets associated with them.
  254. This computation includes pitman risk (it requires minimal information about population)
  255. """
  256. def __init__(self,**args):
  257. Sample.__init__(self)
  258. def set(self,key,value):
  259. Sample.set(self,key,value)
  260. if key == 'merged_groups' :
  261. Sample.set(self,'pop_size',np.float64(value.population_group_size.sum()) )
  262. Sample.set(self,'groups',value.sample_group_size)
  263. """
  264. This class will measure risk and account for the existance of a population
  265. :merged_groups {sample_group_size, population_group_size} is a merged dataset with group sizes of both population and sample
  266. """
  267. def marketer(self):
  268. """
  269. This function requires
  270. """
  271. r = self.cache['merged_groups']
  272. sample_row_count = r.sample_group_size.sum()
  273. #
  274. # @TODO : make sure the above line is size (not sum)
  275. # sample_row_count = r.sample_group_size.size
  276. return r.apply(lambda row: (row.sample_group_size / np.float64(row.population_group_size)) /np.float64(sample_row_count) ,axis=1).sum()