apriori算法java代码
时间: 2023-11-20 22:07:46 浏览: 74
以下是apriori算法的Java代码示例:
```java
public static ArrayList<ArrayList<String>> apriori(ArrayList<ArrayList<String>> transactions, int minSup) {
ArrayList<ArrayList<String>> itemsets = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> L = new ArrayList<ArrayList<String>>();
ArrayList<ArrayList<String>> C = new ArrayList<ArrayList<String>>();
int k = 0;
int transactionsSize = transactions.size();
while (k == 0 || !L.isEmpty()) {
if (k == 0) {
for (ArrayList<String> transaction : transactions) {
for (String item : transaction) {
ArrayList<String> itemset = new ArrayList<String>();
itemset.add(item);
if (!C.contains(itemset)) {
C.add(itemset);
}
}
}
} else {
C = generateC(L);
}
for (ArrayList<String> transaction : transactions) {
for (ArrayList<String> c : C) {
if (transaction.containsAll(c)) {
incrementCount(itemsets, c);
}
}
}
L.clear();
for (ArrayList<String> itemset : itemsets) {
int count = getCount(itemsets, itemset);
if (count >= minSup && !L.contains(itemset)) {
L.add(itemset);
}
}
k++;
}
return itemsets;
}
private static ArrayList<ArrayList<String>> generateC(ArrayList<ArrayList<String>> L) {
ArrayList<ArrayList<String>> C = new ArrayList<ArrayList<String>>();
for (int i = 0; i < L.size(); i++) {
for (int j = i + 1; j < L.size(); j++) {
ArrayList<String> c = new ArrayList<String>();
for (String item : L.get(i)) {
if (!c.contains(item)) {
c.add(item);
}
}
for (String item : L.get(j)) {
if (!c.contains(item)) {
c.add(item);
}
}
Collections.sort(c);
if (!C.contains(c)) {
C.add(c);
}
}
}
return C;
}
private static void incrementCount(ArrayList<ArrayList<String>> itemsets, ArrayList<String> itemset) {
for (int i = 0; i < itemsets.size(); i++) {
if (itemsets.get(i).equals(itemset)) {
int count = Integer.parseInt(itemsets.get(i).get(itemsets.get(i).size() - 1));
itemsets.get(i).set(itemsets.get(i).size() - 1, Integer.toString(count + 1));
return;
}
}
itemset.add("1");
itemsets.add(itemset);
}
private static int getCount(ArrayList<ArrayList<String>> itemsets, ArrayList<String> itemset) {
for (ArrayList<String> i : itemsets) {
if (i.equals(itemset)) {
return Integer.parseInt(i.get(i.size() - 1));
}
}
return 0;
}
```
阅读全文