Java差分隐私案例

wen java案例 2

本文目录导读:

Java差分隐私案例

  1. 基础差分隐私实现
  2. 完整示例:统计数据库查询
  3. 高级:组合机制
  4. 实用工具类
  5. 使用建议

我将为您提供几个Java差分隐私的实用案例,涵盖基本概念到实际应用。

基础差分隐私实现

1 拉普拉斯机制

import java.util.Random;
public class LaplaceMechanism {
    private static final Random random = new Random();
    /**
     * 拉普拉斯机制
     * @param trueValue 真实值
     * @param sensitivity 敏感度
     * @param epsilon 隐私预算(越小隐私保护越强)
     * @return 添加噪声后的值
     */
    public static double addLaplaceNoise(double trueValue, double sensitivity, double epsilon) {
        double scale = sensitivity / epsilon;
        double noise = generateLaplaceNoise(scale);
        return trueValue + noise;
    }
    /**
     * 生成拉普拉斯噪声
     */
    private static double generateLaplaceNoise(double scale) {
        // 使用均匀分布生成拉普拉斯噪声
        double u = random.nextDouble() - 0.5;
        return -scale * Math.signum(u) * Math.log(1 - 2 * Math.abs(u));
    }
    public static void main(String[] args) {
        // 示例:统计数据集中的计数(敏感度为1)
        double trueCount = 1000;
        double epsilon = 0.1;  // 较小的epsilon提供更强隐私保护
        double noisyCount = addLaplaceNoise(trueCount, 1.0, epsilon);
        System.out.println("真实值: " + trueCount);
        System.out.println("加噪值: " + noisyCount);
    }
}

2 指数机制

import java.util.*;
public class ExponentialMechanism {
    /**
     * 指数机制:用于非数值型结果
     */
    public static String selectOutput(Map<String, Double> utilityScores, 
                                     double sensitivity, 
                                     double epsilon) {
        // 计算每个选项被选中的概率
        Map<String, Double> probabilities = new HashMap<>();
        double totalWeight = 0;
        for (Map.Entry<String, Double> entry : utilityScores.entrySet()) {
            double weight = Math.exp(epsilon * entry.getValue() / (2 * sensitivity));
            probabilities.put(entry.getKey(), weight);
            totalWeight += weight;
        }
        // 根据概率随机选择
        double randomValue = new Random().nextDouble() * totalWeight;
        double cumulativeProbability = 0;
        for (Map.Entry<String, Double> entry : probabilities.entrySet()) {
            cumulativeProbability += entry.getValue();
            if (randomValue <= cumulativeProbability) {
                return entry.getKey();
            }
        }
        // 兜底返回
        return probabilities.keySet().iterator().next();
    }
    public static void main(String[] args) {
        // 示例:从多个选项中选择最优答案
        Map<String, Double> utilityScores = new HashMap<>();
        utilityScores.put("北京", 90.0);
        utilityScores.put("上海", 85.0);
        utilityScores.put("广州", 60.0);
        utilityScores.put("深圳", 75.0);
        double sensitivity = 1.0;
        double epsilon = 1.0;
        String result = selectOutput(utilityScores, sensitivity, epsilon);
        System.out.println("选择结果: " + result);
    }
}

完整示例:统计数据库查询

import java.util.*;
import java.util.stream.Collectors;
public class DifferentialPrivacyExample {
    // 数据库类
    static class Database {
        private List<Record> records = new ArrayList<>();
        public void addRecord(Record record) {
            records.add(record);
        }
        public int count() {
            return records.size();
        }
        public double averageAge() {
            if (records.isEmpty()) return 0;
            return records.stream().mapToInt(r -> r.age).average().orElse(0);
        }
        public long countByGender(String gender) {
            return records.stream()
                .filter(r -> r.gender.equals(gender))
                .count();
        }
    }
    static class Record {
        String name;
        int age;
        String gender;
        double salary;
        Record(String name, int age, String gender, double salary) {
            this.name = name;
            this.age = age;
            this.gender = gender;
            this.salary = salary;
        }
    }
    // 隐私保护查询服务
    static class PrivacyProtectedService {
        private Database database;
        private double epsilon;
        private LaplaceMechanism laplace;
        PrivacyProtectedService(Database db, double epsilon) {
            this.database = db;
            this.epsilon = epsilon;
            this.laplace = new LaplaceMechanism();
        }
        // 计数查询(敏感度 = 1)
        public int privateCount() {
            int trueCount = database.count();
            double noisyCount = laplace.addLaplaceNoise(trueCount, 1.0, epsilon);
            return (int) Math.max(0, Math.round(noisyCount));
        }
        // 平均值查询(敏感度 = 最大值/样本数)
        public double privateAverageAge() {
            double trueAvg = database.averageAge();
            // 年龄范围0-100,敏感度 = 100/count
            double sensitivity = 100.0 / Math.max(1, database.count());
            double noisyAvg = laplace.addLaplaceNoise(trueAvg, sensitivity, epsilon);
            return Math.max(0, Math.min(100, noisyAvg));
        }
        // 按性别计数
        public long privateCountByGender(String gender) {
            long trueCount = database.countByGender(gender);
            double noisyCount = laplace.addLaplaceNoise(trueCount, 1.0, epsilon);
            return Math.max(0, Math.round(noisyCount));
        }
        // 分位数查询
        public double privatePercentile(int percentile) {
            List<Integer> ages = database.records.stream()
                .map(r -> r.age)
                .sorted()
                .collect(Collectors.toList());
            if (ages.isEmpty()) return 0;
            int index = (int) Math.ceil(percentile / 100.0 * ages.size()) - 1;
            index = Math.max(0, Math.min(index, ages.size() - 1));
            double trueValue = ages.get(index);
            double sensitivity = 100.0 / Math.max(1, ages.size());
            return laplace.addLaplaceNoise(trueValue, sensitivity, epsilon);
        }
    }
    public static void main(String[] args) {
        // 创建示例数据库
        Database db = new Database();
        Random random = new Random();
        String[] genders = {"男", "女"};
        for (int i = 0; i < 1000; i++) {
            String name = "用户" + i;
            int age = 18 + random.nextInt(60);
            String gender = genders[random.nextInt(2)];
            double salary = 5000 + random.nextDouble() * 30000;
            db.addRecord(new Record(name, age, gender, salary));
        }
        // 创建隐私保护服务
        double epsilon = 0.5;  // 隐私预算
        PrivacyProtectedService service = new PrivacyProtectedService(db, epsilon);
        System.out.println("===== 差分隐私查询演示 =====");
        System.out.println("隐私预算 ε = " + epsilon);
        System.out.println();
        // 真实值查询
        System.out.println("真实记录数: " + db.count());
        for (int i = 1; i <= 5; i++) {
            System.out.println("加噪计数 " + i + ": " + service.privateCount());
        }
        System.out.println();
        // 平均年龄查询
        System.out.println("真实平均年龄: " + db.averageAge());
        for (int i = 1; i <= 3; i++) {
            System.out.println("加噪平均年龄 " + i + ": " + service.privateAverageAge());
        }
        System.out.println();
        // 按性别计数
        System.out.println("真实男性人数: " + db.countByGender("男"));
        for (int i = 1; i <= 3; i++) {
            System.out.println("加噪男性计数 " + i + ": " + service.privateCountByGender("男"));
        }
    }
}

高级:组合机制

import java.util.*;
public class AdvancedDifferentialPrivacy {
    // 组合定理示例
    static class CompositionMechanism {
        /**
         * 串行组合:多个查询共享隐私预算
         */
        public static List<Double> sequentialComposition(List<Double> trueValues, 
                                                         double totalEpsilon, 
                                                         double sensitivity) {
            List<Double> results = new ArrayList<>();
            int numQueries = trueValues.size();
            double perQueryEpsilon = totalEpsilon / numQueries;
            LaplaceMechanism laplace = new LaplaceMechanism();
            for (Double value : trueValues) {
                results.add(laplace.addLaplaceNoise(value, sensitivity, perQueryEpsilon));
            }
            return results;
        }
        /**
         * 并行组合:不同数据集可以共享隐私预算
         */
        public static double parallelComposition(List<List<Double>> datasets,
                                                  double totalEpsilon,
                                                  double sensitivity,
                                                  int targetDataset) {
            // 并行组合中每个查询可以使用全部隐私预算
            LaplaceMechanism laplace = new LaplaceMechanism();
            List<Double> targetData = datasets.get(targetDataset);
            if (targetData.isEmpty()) return 0;
            double avg = targetData.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0);
            return laplace.addLaplaceNoise(avg, sensitivity * totalEpsilon, totalEpsilon);
        }
    }
    // 数据聚合器
    static class SmartAggregator {
        private LaplaceMechanism laplace = new LaplaceMechanism();
        /**
         * 智能聚合:自动调整隐私预算
         */
        public double smartAggregate(List<Double> values, 
                                    double maxEpsilon, 
                                    double sensitivity) {
            double variance = calculateVariance(values);
            double mean = values.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0);
            // 根据数据方差动态调整噪声
            double adaptiveEpsilon = maxEpsilon / (1 + Math.sqrt(variance));
            adaptiveEpsilon = Math.min(maxEpsilon, adaptiveEpsilon);
            return laplace.addLaplaceNoise(mean, sensitivity, adaptiveEpsilon);
        }
        private double calculateVariance(List<Double> values) {
            if (values.isEmpty()) return 0;
            double mean = values.stream()
                .mapToDouble(Double::doubleValue)
                .average()
                .orElse(0);
            return values.stream()
                .mapToDouble(v -> Math.pow(v - mean, 2))
                .average()
                .orElse(0);
        }
    }
    public static void main(String[] args) {
        // 演示组合机制
        System.out.println("===== 组合机制演示 =====");
        // 串行组合
        List<Double> trueValues = Arrays.asList(50.0, 60.0, 70.0);
        double totalEpsilon = 0.3;
        List<Double> perturbedValues = CompositionMechanism.sequentialComposition(
            trueValues, totalEpsilon, 1.0);
        System.out.println("串行组合(总隐私预算 " + totalEpsilon + "):");
        for (int i = 0; i < trueValues.size(); i++) {
            System.out.println("真实值 " + trueValues.get(i) + " -> 加噪值 " + perturbedValues.get(i));
        }
        // 智能聚合
        SmartAggregator aggregator = new SmartAggregator();
        List<Double> data = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 100; i++) {
            data.add(100 + random.nextGaussian() * 20);
        }
        double result = aggregator.smartAggregate(data, 0.5, 1.0);
        System.out.println("\n智能聚合结果: " + result);
        System.out.println("真实均值: " + data.stream().mapToDouble(Double::doubleValue).average().orElse(0));
    }
}

实用工具类

public class PrivacyBudgetManager {
    private double remainingEpsilon;
    private double totalEpsilon;
    public PrivacyBudgetManager(double totalEpsilon) {
        this.totalEpsilon = totalEpsilon;
        this.remainingEpsilon = totalEpsilon;
    }
    /**
     * 检查是否有足够隐私预算
     */
    public synchronized boolean canSpend(double epsilon) {
        return remainingEpsilon >= epsilon;
    }
    /**
     * 消耗隐私预算
     */
    public synchronized void spend(double epsilon) {
        if (epsilon > remainingEpsilon) {
            throw new IllegalStateException("隐私预算不足");
        }
        remainingEpsilon -= epsilon;
        System.out.printf("已消耗 %.3f,剩余 %.3f\n", epsilon, remainingEpsilon);
    }
    /**
     * 获取剩余隐私预算
     */
    public synchronized double getRemainingEpsilon() {
        return remainingEpsilon;
    }
    /**
     * 重置隐私预算
     */
    public synchronized void reset() {
        remainingEpsilon = totalEpsilon;
    }
}

使用建议

  1. 选择适当的Epsilon值

    • ε ≤ 0.1:强隐私保护
    • 1 < ε ≤ 1:中等隐私保护
    • ε > 1:弱隐私保护(不推荐)
  2. 敏感度计算

    • 计数查询:敏感度 = 1
    • 求和查询:敏感度 = 最大值 - 最小值
    • 平均值查询:敏感度 = (最大值 - 最小值) / 样本数
  3. 实际应用场景

    • 人口统计数据分析
    • 医疗数据统计
    • 用户行为分析
    • 金融数据分析
  4. 性能优化

    • 使用缓存减少重复计算
    • 批量处理时使用并行组合
    • 合理分配隐私预算

这些案例展示了Java中差分隐私的基本实现和应用,在实际项目中,建议使用成熟的差分隐私库,如Google的Differential Privacy库或IBM的Diffprivlib(Python),但Java实现可以用于学习和理解核心概念。

抱歉,评论功能暂时关闭!