def test_misses_cost_with_pgbs(self):

        # Sensitive closed itemsets whose support needs to be reduced
        sensitive_IS = {frozenset(['1', '2']), frozenset(['4'])}

        # PGBS needs input in this format
        sensitive_IL = pd.DataFrame(
            {'itemset': [list(l) for l in sensitive_IS],
             'threshold': [self.sigma_min, self.sigma_min]})

        original_database = self.basket_sets.copy()
        modified_database = self.basket_sets.copy()

        # No return value, instead it modifies input database in place
        pgbs(modified_database, sensitive_IL)

        # Get all itemsets and supports in D (original_database)
        sigma_model = 1 / len(original_database)
        original_IS = fpgrowth(original_database, min_support=sigma_model, use_colnames=True, verbose=False)

        # Get all itemsets and supports in D' (modified_database)
        mofidied_F_IS = fpgrowth(modified_database, min_support=sigma_model, use_colnames=True, verbose=False)

        # Find set of non-sensitive frequent itemsets in D
        a = remove_sensitive_subsets(original_IS, self.sensitive_IS)

        # Find set of non-sensitive frequent itemsets in D'
        b = remove_sensitive_subsets(mofidied_F_IS[mofidied_F_IS["support"] >= self.sigma_min], self.sensitive_IS)

        mc = misses_cost(a, b)
        self.assertEqual(mc, 0.18181818181818182)
    def test_misses_cost_with_rps(self):

        # Produce a sanitised DB with sensitive IS's support below sigma_min
        sanitized_closed_IS = rps(model=self.original_Closed_IS,
                                  sensitiveItemsets=self.sensitive_IS,
                                  supportThreshold=self.sigma_min)

        # Convert from closed to frequent itemsets
        sanitised_F_IS = itemsets_from_closed_itemsets(closed_itemsets=sanitized_closed_IS,
                                                       possible_itemsets=self.original_IS['itemsets'])

        # Find set of non-sensitive frequent itemsets in D
        a = remove_sensitive_subsets(self.original_Freq_IS, self.sensitive_IS)

        # Find set of non-sensitive frequent itemsets in D'
        b = remove_sensitive_subsets(sanitised_F_IS[sanitised_F_IS["support"] >= self.sigma_min], self.sensitive_IS)

        mc = misses_cost(a, b)
        self.assertEqual(mc, 0.0)
Ejemplo n.º 3
0
def main(datasets, algorithm, i):
    #Create the base of a table
    table_11 = pd.DataFrame(columns=[
        'Model', 'Support threshold', 'Model threshold', 'Sensitive itemsets',
        'Number of FI before sanitization',
        'Number of FI containing an element of S before sanitization',
        'Information loss expected', 'Number of FI after sanitization',
        'Number of FI containing an element of S after RPS', 'Hiding failure',
        'Artifactual patterns', 'Misses cost', 'Side effects factor',
        'Information loss', 'RPS Time'
    ])

    table_10 = pd.DataFrame(columns=[
        'Dataset', 'Model threshold', 'Number of Closed frequent itemsets',
        'Number of frequent itemsets', 'Time closed itemsets'
    ])

    #Loop through datasets
    for dataset in datasets:
        sigma_model = datasets[dataset][0]

        #Load dataset
        data = im.import_dataset(dataset)
        data = data.astype('bool')  #This may be needed for some datasets
        print("\n", dataset, "imported\n")

        #Start total timer
        total_time_start = time.time()

        #Convert to closed itemsets
        current_model, freq_model = get_closed_itemsets(data, sigma_model)

        new_row = {
            'Dataset': dataset,
            'Model threshold': sigma_model,
            'Number of Closed frequent itemsets': len(current_model),
            'Number of frequent itemsets': len(freq_model),
            'Time closed itemsets': time.time() - total_time_start
        }

        print(new_row)
        table_10 = table_10.append(new_row, ignore_index=True)
        table_10.to_csv('table_10.csv')

        #Loop through support thresholds
        for sigma_min in datasets[dataset][1:]:
            print("\n", dataset, "FI:", sigma_min)

            #Find original frequent itemsets at frequency sigma min
            freq_original = freq_model.loc[freq_model["support"] >= sigma_min]

            for k_freq in [10, 30]:
                print("-", dataset, ":", k_freq, "Sensitive itemsets")

                #Copy the model so we can edit it directly
                copied_model = current_model.copy()

                #We pick sensitive itemsets here
                sensitive_IS = get_top_k_sensitive_itemsets(
                    freq_original, k_freq)
                num_FI_containing_S = count_FI_containing_S(
                    freq_original, sensitive_IS)

                if algorithm == "RPS":
                    #Start timer for RPS portion
                    total_time_start = time.time()

                    #Run RPS
                    sanitized_closed_IS = rps(model=copied_model,
                                              sensitiveItemsets=sensitive_IS,
                                              supportThreshold=sigma_min)

                elif algorithm == "MRPS":
                    #Convert to pandas format for MRPS input
                    sensitive_IS_pandas = pd.DataFrame(
                        data=[(sensitive_IS),
                              np.full((len(sensitive_IS)), sigma_min),
                              np.full((len(sensitive_IS)), sigma_min - 0.5 *
                                      (sigma_min - sigma_model))]).T

                    sensitive_IS_pandas.columns = [
                        'itemset', 'upper_threshold', 'lower_threshold'
                    ]

                    #Start timer for RPS portion
                    total_time_start = time.time()

                    #Run RPS random threshold
                    sanitized_closed_IS = rps_two_thresholds(
                        model=copied_model,
                        sensitiveItemsets=sensitive_IS_pandas)

                #Reproduce frequent itemsets
                sanitized_DB = itemsets_from_closed_itemsets(
                    closed_itemsets=sanitized_closed_IS,
                    possible_itemsets=freq_model['itemsets'])

                rps_time = time.time()

                #Calculating metrics
                #Variables needed
                freq_sanitized = sanitized_DB.loc[
                    sanitized_DB["support"] >= sigma_min]

                #Sensitive subsets of frequent itemsets
                freq_sanitized_sensitive = get_sensitive_subsets(
                    freq_sanitized, sensitive_IS)
                freq_original_sensitive = get_sensitive_subsets(
                    freq_original, sensitive_IS)

                #Non sensitive subset of frequent itemsets
                freq_sanitized_nonsensitive = remove_sensitive_subsets(
                    freq_sanitized, sensitive_IS)["itemsets"]
                freq_original_nonsensitive = remove_sensitive_subsets(
                    freq_original, sensitive_IS)["itemsets"]

                #Calculation of metrics
                hiding_f = hiding_failure(freq_original_sensitive["itemsets"],
                                          freq_sanitized_sensitive["itemsets"])
                artifactual_p = artifactual_patterns(
                    set(freq_original["itemsets"]),
                    set(freq_sanitized["itemsets"]))
                misses_c = misses_cost(freq_original_nonsensitive.copy(),
                                       freq_sanitized_nonsensitive.copy())
                side_effect_fac = side_effects_factor(
                    set(freq_original["itemsets"]),
                    set(freq_sanitized["itemsets"]),
                    set(freq_original_sensitive["itemsets"]))

                #Information loss between frequent itemsets in original and sanitized at sigma model
                information_l = information_loss(freq_model.copy(),
                                                 sanitized_DB)

                #Expected information loss if all sensitive frequent itemsets had their support reduced to sigma min
                expected_information_l = expected_information_loss(
                    freq_model.copy(), freq_original_sensitive.copy(),
                    sigma_min)

                #Calculate the end time of this iteration
                end_time = rps_time - total_time_start

                #Threshold sanitized database by threshold_min to get frequent itemsets
                print(f'- RPS time: {end_time}')

                #Plot support graphs
                dual_support_graph_distribution(
                    freq_model, sanitized_DB, sigma_model, dataset + "_" +
                    str(i) + "_" + str(sigma_min) + "_" + str(k_freq))

                #Find number of FI in sanitized database containing sensitive itemsets
                num_FI_containing_S_RPS = count_FI_containing_S(
                    freq_sanitized, sensitive_IS)

                #Add to row of table
                new_row = {
                    'Model': dataset,
                    'Model threshold': sigma_model,
                    'Support threshold': sigma_min,
                    'Sensitive itemsets': k_freq,
                    'Number of FI before sanitization': len(freq_original),
                    'Number of FI containing an element of S before sanitization':
                    num_FI_containing_S,
                    'Information loss expected': expected_information_l,
                    'Number of FI after sanitization': len(freq_sanitized),
                    'Number of FI containing an element of S after RPS':
                    num_FI_containing_S_RPS,
                    'Hiding failure': hiding_f,
                    'Artifactual patterns': artifactual_p,
                    'Misses cost': misses_c,
                    'Side effects factor': side_effect_fac,
                    'Information loss': information_l,
                    'RPS Time': end_time
                }

                #Update after each one just so we are sure we are recording results
                table_11 = table_11.append(new_row, ignore_index=True)
                table_11.to_csv('table_11_' + str(i) + '.csv')
Ejemplo n.º 4
0
def main(datasets):
    #Create the base of a table
    table_11 = pd.DataFrame(columns=['Model',
                                     'Support threshold',
                                     'Model threshold',
                                     'Sensitive itemsets',
                                     'Number of FI before sanitization',
                                     'Information loss expected',
                                     'Number of FI after sanitization',
                                     'Number of FI containing an element of S after RPS',
                                     'Hiding failure',
                                     'Artifactual patterns',
                                     'Misses cost',
                                     'Side effects factor',
                                     'Information loss',
                                     'PGBS time'])

    #Loop through datasets
    for dataset in datasets:
        sigma_model = datasets[dataset][0]

        #Load dataset
        data = im.import_dataset(dataset)
        data = data.astype('bool') #This may be needed for some datasets
        print("\n", dataset, "imported\n")

        #Get frequent itemsets
        freq_model = fpgrowth(data, min_support=sigma_model, use_colnames=True) 

        #Loop through support thresholds
        for sigma_min in datasets[dataset][1:]:
            print("\n", dataset, "FI:", sigma_min)
            
            #Find original frequent itemsets at frequency sigma min
            freq_original = freq_model.loc[freq_model["support"] >= sigma_min]

            for k_freq in [10, 30, 50]:
                print("-", dataset, ":", k_freq, "Sensitive itemsets")

                #Copy the transactions so we can edit it directly
                copied_data = data.copy()
                
                #We pick sensitive itemsets here
                sensitive_IS = get_top_k_sensitive_itemsets(freq_original, k_freq)

                #Start timer for PGBS portion
                total_time_start = time.time()

                #Convert to pandas format for PGBS input
                sensitive_IS_pandas = pd.DataFrame(data=[(sensitive_IS), np.full((len(sensitive_IS)), sigma_min)]).T

                sensitive_IS_pandas.columns = ['itemset', 'threshold']

                #Run PGBS
                print("Running PGBS")
                pgbs(copied_data,sensitive_IS_pandas)
                print("PGBS run")
                pgbs_time = time.time()

                sensitive_IS = convert_to_sets(sensitive_IS)
                
                print("FPGrowth")
                #Reproduce frequent itemsets
                freq_model_sanitized = fpgrowth(copied_data, min_support=sigma_model, use_colnames=True)
                
                #Calculating metrics
                #Variables needed
                freq_sanitized = freq_model_sanitized.loc[freq_model_sanitized["support"] >= sigma_min]

                #Sensitive subsets of frequent itemsets
                freq_sanitized_sensitive = get_sensitive_subsets(freq_sanitized, sensitive_IS)
                freq_original_sensitive = get_sensitive_subsets(freq_original, sensitive_IS)

                #Non sensitive subset of frequent itemsets
                freq_sanitized_nonsensitive = remove_sensitive_subsets(freq_sanitized, sensitive_IS)["itemsets"]
                freq_original_nonsensitive = remove_sensitive_subsets(freq_original, sensitive_IS)["itemsets"]

                #Calculation of metrics
                freq_original_sensitive.to_csv("original.csv")
                freq_sanitized_sensitive.to_csv("sanitized.csv")
                print("len:", len(freq_original_sensitive["itemsets"]), len(freq_sanitized_sensitive["itemsets"]))

                hiding_f = hiding_failure(freq_original_sensitive["itemsets"], freq_sanitized_sensitive["itemsets"])
                artifactual_p = artifactual_patterns(set(freq_original["itemsets"]), set(freq_sanitized["itemsets"]))
                misses_c = misses_cost(freq_original_nonsensitive.copy(), freq_sanitized_nonsensitive.copy())
                side_effect_fac = side_effects_factor(set(freq_original["itemsets"]), set(freq_sanitized["itemsets"]), set(freq_original_sensitive["itemsets"]))

                #Information loss between frequent itemsets in original and sanitized at sigma model
                information_l = information_loss(freq_model.copy(), freq_model_sanitized)

                #Expected information loss if all sensitive frequent itemsets had their support reduced to sigma min
                expected_information_l = expected_information_loss(freq_model.copy(), freq_original_sensitive.copy(), sigma_min)

                #Calculate the end time of this iteration
                end_time = pgbs_time - total_time_start

                #Threshold sanitized database by threshold_min to get frequent itemsets 
                print(f'- PGBS time: {end_time}')

                #Plot support graphs
                dual_support_graph_distribution(freq_model, freq_model_sanitized, sigma_model, dataset+"_PGBS_"+str(sigma_min)+"_"+str(k_freq))

                #Find number of FI in sanitized database containing sensitive itemsets
                num_FI_containing_S_RPS = count_FI_containing_S(freq_sanitized, sensitive_IS)

                #Add to row of table
                new_row = {'Model': dataset,
                           'Model threshold': sigma_model,
                           'Support threshold': sigma_min,
                           'Sensitive itemsets': k_freq,
                           'Number of FI before sanitization': len(freq_original),
                           'Information loss expected': expected_information_l,
                           'Number of FI after sanitization': len(freq_sanitized),
                           'Number of FI containing an element of S after RPS': num_FI_containing_S_RPS,
                           'Hiding failure': hiding_f,
                           'Artifactual patterns': artifactual_p,
                           'Misses cost': misses_c,
                           'Side effects factor': side_effect_fac,
                           'Information loss': information_l,
                           'PGBS time': end_time}

                #Update after each one just so we are sure we are recording results
                table_11 = table_11.append(new_row, ignore_index=True)
                table_11.to_csv('table_pgbs.csv')
Ejemplo n.º 5
0
def main(datasets):
    #Create the base of a table
    table_11 = pd.DataFrame(columns=[
        'Model', 'Support threshold', 'Model threshold', 'Sensitive itemsets',
        'Number of FI before sanitization', 'Information loss expected',
        'Number of FI after sanitization',
        'Number of FI containing an element of S after SWA', 'Hiding failure',
        'Artifactual patterns', 'Misses cost', 'Side effects factor',
        'Information loss', 'SWA time'
    ])

    #Loop through datasets
    for dataset in datasets:
        #Loop through support thresholds #TODO: error running this in the normal way but
        #It is not much of a slowdown for SWA to have this here

        #Load dataset
        sigma_model = datasets[dataset][0]
        db = im.import_dataset(dataset)
        db = db.astype('bool')  #This may be needed for some datasets
        print("\n", dataset, "imported")

        #Get frequent itemsets
        freq_model = fpgrowth(db, min_support=sigma_model, use_colnames=True)

        for sigma_min in datasets[dataset][1:]:
            print("\n", dataset, "FI:", sigma_min)

            #Find original frequent itemsets at frequency sigma min
            freq_original = freq_model.loc[freq_model["support"] >= sigma_min]

            for k_freq in [10, 30, 50]:

                data = im.convert_to_transaction(db)

                print(dataset, ":", k_freq, "Sensitive itemsets")

                #We pick sensitive itemsets here
                sensitive_IS = get_top_k_sensitive_itemsets(
                    freq_original, k_freq)

                #Start timer for SWA portion
                total_time_start = time.time()

                #Convert to pandas format for SWA input
                sensitive_rules = get_disclosures(sensitive_IS, freq_model,
                                                  sigma_min)

                #Run SWA
                SWA(data, sensitive_rules, data.shape[0])
                swa_time = time.time()

                sensitive_IS = convert_to_sets(sensitive_IS)

                data = im.convert_to_matrix(data)

                #Reproduce frequent itemsets
                freq_model_sanitized = fpgrowth(data,
                                                min_support=sigma_model,
                                                use_colnames=True)

                #Calculating metrics
                #Variables needed
                freq_sanitized = freq_model_sanitized.loc[
                    freq_model_sanitized["support"] >= sigma_min]

                #Sensitive subsets of frequent itemsets
                freq_sanitized_sensitive = get_sensitive_subsets(
                    freq_sanitized, sensitive_IS)
                freq_original_sensitive = get_sensitive_subsets(
                    freq_original, sensitive_IS)

                #Non sensitive subset of frequent itemsets
                freq_sanitized_nonsensitive = remove_sensitive_subsets(
                    freq_sanitized, sensitive_IS)["itemsets"]
                freq_original_nonsensitive = remove_sensitive_subsets(
                    freq_original, sensitive_IS)["itemsets"]

                #Calculation of metrics
                freq_original_sensitive.to_csv("original.csv")
                freq_sanitized_sensitive.to_csv("sanitized.csv")
                print("- len:", len(freq_original_sensitive["itemsets"]),
                      len(freq_sanitized_sensitive["itemsets"]))

                hiding_f = hiding_failure(freq_original_sensitive["itemsets"],
                                          freq_sanitized_sensitive["itemsets"])
                artifactual_p = artifactual_patterns(
                    set(freq_original["itemsets"]),
                    set(freq_sanitized["itemsets"]))
                misses_c = misses_cost(freq_original_nonsensitive.copy(),
                                       freq_sanitized_nonsensitive.copy())
                side_effect_fac = side_effects_factor(
                    set(freq_original["itemsets"]),
                    set(freq_sanitized["itemsets"]),
                    set(freq_original_sensitive["itemsets"]))

                #Information loss between frequent itemsets in original and sanitized at sigma model
                information_l = information_loss(freq_model.copy(),
                                                 freq_model_sanitized)

                #Expected information loss if all sensitive frequent itemsets had their support reduced to sigma min
                expected_information_l = expected_information_loss(
                    freq_model.copy(), freq_original_sensitive.copy(),
                    sigma_min)

                #Calculate the end time of this iteration
                end_time = swa_time - total_time_start

                #Threshold sanitized database by threshold_min to get frequent itemsets
                print(f'- SWA time: {end_time}')

                #Plot support graphs
                dual_support_graph_distribution(
                    freq_model, freq_model_sanitized, sigma_model,
                    dataset + "_SWA_" + str(sigma_min) + "_" + str(k_freq))

                #Find number of FI in sanitized database containing sensitive itemsets
                num_FI_containing_S_RPS = count_FI_containing_S(
                    freq_sanitized, sensitive_IS)

                #Add to row of table
                new_row = {
                    'Model': dataset,
                    'Model threshold': sigma_model,
                    'Support threshold': sigma_min,
                    'Sensitive itemsets': k_freq,
                    'Number of FI before sanitization': len(freq_original),
                    'Information loss expected': expected_information_l,
                    'Number of FI after sanitization': len(freq_sanitized),
                    'Number of FI containing an element of S after SWA':
                    num_FI_containing_S_RPS,
                    'Hiding failure': hiding_f,
                    'Artifactual patterns': artifactual_p,
                    'Misses cost': misses_c,
                    'Side effects factor': side_effect_fac,
                    'Information loss': information_l,
                    'SWA time': end_time
                }

                #Update after each one just so we are sure we are recording results
                table_11 = table_11.append(new_row, ignore_index=True)
                table_11.to_csv('table_SWA.csv')