python实现差分隐私Laplace机制

python实现差分隐私Laplace机制

 

https://blog.csdn.net/qq_38242289/article/details/80798952

 

kyton123 2018-06-25 11:22:43  7005  收藏 12

分类专栏: Differential Privacy

Laplace分布定义:

 

下面先给出Laplace分布实现代码:

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. def laplace_function(x,beta):
  4. result = (1/(2*beta)) * np.e**(-1*(np.abs(x)/beta))
  5. return result
  6. #-55之间等间隔的取10000个数
  7. x = np.linspace(-5,5,10000)
  8. y1 = [laplace_function(x_,0.5) for x_ in x]
  9. y2 = [laplace_function(x_,1) for x_ in x]
  10. y3 = [laplace_function(x_,2) for x_ in x]
  11. plt.plot(x,y1,color='r',label='beta:0.5')
  12. plt.plot(x,y2,color='g',label='beta:1')
  13. plt.plot(x,y3,color='b',label='beta:2')
  14. plt.title("Laplace distribution")
  15. plt.legend()
  16. plt.show()

效果图如下:

 

接下来给出Laplace机制实现:

 

Laplace机制,即在操作函数结果中加入服从Laplace分布的噪声。

Laplace概率密度函数Lap(x|b)=1/2b exp(-|x|/b)正比于exp(-|x|/b)

 

  1. import numpy as np
  2. def noisyCount(sensitivety,epsilon):
  3. beta = sensitivety/epsilon
  4. u1 = np.random.random()
  5. u2 = np.random.random()
  6. if u1 <= 0.5:
  7. n_value = -beta*np.log(1.-u2)
  8. else:
  9. n_value = beta*np.log(u2)
  10. print(n_value)
  11. return n_value
  12. def laplace_mech(data,sensitivety,epsilon):
  13. for i in range(len(data)):
  14. data[i] += noisyCount(sensitivety,epsilon)
  15. return data
  16. if __name__ =='__main__':
  17. x = [1.,1.,0.]
  18. sensitivety = 1
  19. epsilon = 1
  20. data = laplace_mech(x,sensitivety,epsilon)
  21. for j in data:
  22. print(j)
posted on 2021-05-28 15:43  独上兰舟1  阅读(617)  评论(0编辑  收藏  举报