Mercurial > repos > bgruening > stacking_ensemble_models
comparison association_rules.py @ 3:0a1812986bc3 draft
planemo upload for repository https://github.com/bgruening/galaxytools/tree/master/tools/sklearn commit 9981e25b00de29ed881b2229a173a8c812ded9bb
author | bgruening |
---|---|
date | Wed, 09 Aug 2023 11:10:37 +0000 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
2:38c4f8a98038 | 3:0a1812986bc3 |
---|---|
1 import argparse | |
2 import json | |
3 import warnings | |
4 | |
5 import pandas as pd | |
6 from mlxtend.frequent_patterns import association_rules, fpgrowth | |
7 from mlxtend.preprocessing import TransactionEncoder | |
8 | |
9 | |
10 def main( | |
11 inputs, | |
12 infile, | |
13 outfile, | |
14 min_support=0.5, | |
15 min_confidence=0.5, | |
16 min_lift=1.0, | |
17 min_conviction=1.0, | |
18 max_length=None, | |
19 ): | |
20 """ | |
21 Parameter | |
22 --------- | |
23 input : str | |
24 File path to galaxy tool parameter | |
25 | |
26 infile : str | |
27 File paths of input vector | |
28 | |
29 outfile : str | |
30 File path to output matrix | |
31 | |
32 min_support: float | |
33 Minimum support | |
34 | |
35 min_confidence: float | |
36 Minimum confidence | |
37 | |
38 min_lift: float | |
39 Minimum lift | |
40 | |
41 min_conviction: float | |
42 Minimum conviction | |
43 | |
44 max_length: int | |
45 Maximum length | |
46 | |
47 """ | |
48 warnings.simplefilter("ignore") | |
49 | |
50 with open(inputs, "r") as param_handler: | |
51 params = json.load(param_handler) | |
52 | |
53 input_header = params["header0"] | |
54 header = "infer" if input_header else None | |
55 | |
56 with open(infile) as fp: | |
57 lines = fp.read().splitlines() | |
58 | |
59 if header is not None: | |
60 lines = lines[1:] | |
61 | |
62 dataset = [] | |
63 for line in lines: | |
64 line_items = line.split("\t") | |
65 dataset.append(line_items) | |
66 | |
67 # TransactionEncoder learns the unique labels in the dataset and transforms the | |
68 # input dataset (a Python list of lists) into a one-hot encoded NumPy boolean array | |
69 te = TransactionEncoder() | |
70 te_ary = te.fit_transform(dataset) | |
71 | |
72 # Turn the encoded NumPy array into a DataFrame | |
73 df = pd.DataFrame(te_ary, columns=te.columns_) | |
74 | |
75 # Extract frequent itemsets for association rule mining | |
76 # use_colnames: Use DataFrames' column names in the returned DataFrame instead of column indices | |
77 frequent_itemsets = fpgrowth( | |
78 df, min_support=min_support, use_colnames=True, max_len=max_length | |
79 ) | |
80 | |
81 # Get association rules, with confidence larger than min_confidence | |
82 rules = association_rules( | |
83 frequent_itemsets, metric="confidence", min_threshold=min_confidence | |
84 ) | |
85 | |
86 # Filter association rules, keeping rules with lift and conviction larger than min_liftand and min_conviction | |
87 rules = rules[(rules["lift"] >= min_lift) & (rules["conviction"] >= min_conviction)] | |
88 | |
89 # Convert columns from frozenset to list (more readable) | |
90 rules["antecedents"] = rules["antecedents"].apply(list) | |
91 rules["consequents"] = rules["consequents"].apply(list) | |
92 | |
93 # The next 3 steps are intended to fix the order of the association | |
94 # rules generated, so tests that rely on diff'ing a desired output | |
95 # with an expected output can pass | |
96 | |
97 # 1) Sort entry in every row/column for columns 'antecedents' and 'consequents' | |
98 rules["antecedents"] = rules["antecedents"].apply(lambda row: sorted(row)) | |
99 rules["consequents"] = rules["consequents"].apply(lambda row: sorted(row)) | |
100 | |
101 # 2) Create two temporary string columns to sort on | |
102 rules["ant_str"] = rules["antecedents"].apply(lambda row: " ".join(row)) | |
103 rules["con_str"] = rules["consequents"].apply(lambda row: " ".join(row)) | |
104 | |
105 # 3) Sort results so they are re-producable | |
106 rules.sort_values(by=["ant_str", "con_str"], inplace=True) | |
107 del rules["ant_str"] | |
108 del rules["con_str"] | |
109 rules.reset_index(drop=True, inplace=True) | |
110 | |
111 # Write association rules and metrics to file | |
112 rules.to_csv(outfile, sep="\t", index=False) | |
113 | |
114 | |
115 if __name__ == "__main__": | |
116 aparser = argparse.ArgumentParser() | |
117 aparser.add_argument("-i", "--inputs", dest="inputs", required=True) | |
118 aparser.add_argument("-y", "--infile", dest="infile", required=True) | |
119 aparser.add_argument("-o", "--outfile", dest="outfile", required=True) | |
120 aparser.add_argument("-s", "--support", dest="support", default=0.5) | |
121 aparser.add_argument("-c", "--confidence", dest="confidence", default=0.5) | |
122 aparser.add_argument("-l", "--lift", dest="lift", default=1.0) | |
123 aparser.add_argument("-v", "--conviction", dest="conviction", default=1.0) | |
124 aparser.add_argument("-t", "--length", dest="length", default=5) | |
125 args = aparser.parse_args() | |
126 | |
127 main( | |
128 args.inputs, | |
129 args.infile, | |
130 args.outfile, | |
131 min_support=float(args.support), | |
132 min_confidence=float(args.confidence), | |
133 min_lift=float(args.lift), | |
134 min_conviction=float(args.conviction), | |
135 max_length=int(args.length), | |
136 ) |