Commit ·
367219f
1
Parent(s): 163aedf
new files
Browse files- Apriori Algo.py +2 -75
- config.json +1 -1
- model.py +85 -0
- requirements.txt +2 -0
Apriori Algo.py
CHANGED
|
@@ -1,78 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
from itertools import combinations
|
| 3 |
-
from collections import defaultdict
|
| 4 |
import json
|
| 5 |
-
import os
|
| 6 |
-
|
| 7 |
-
class AprioriModel:
|
| 8 |
-
def __init__(self, min_support=0.01):
|
| 9 |
-
self.min_support = min_support
|
| 10 |
-
self.transactions = []
|
| 11 |
-
|
| 12 |
-
def load_data(self, folder_path):
|
| 13 |
-
"""Load CSV files from a folder and combine them into a single DataFrame."""
|
| 14 |
-
combined_df = pd.DataFrame()
|
| 15 |
-
|
| 16 |
-
for file in os.listdir(folder_path):
|
| 17 |
-
if file.endswith('.csv'):
|
| 18 |
-
file_path = os.path.join(folder_path, file)
|
| 19 |
-
df = pd.read_csv(file_path)
|
| 20 |
-
combined_df = pd.concat([combined_df, df], ignore_index=True)
|
| 21 |
-
|
| 22 |
-
return combined_df
|
| 23 |
-
|
| 24 |
-
def preprocess_data(self, data):
|
| 25 |
-
"""Prepare basket data and transaction sets from raw data."""
|
| 26 |
-
basket = data.groupby(['Transaction ID', 'Product'])['Quantity'].sum().unstack().fillna(0)
|
| 27 |
-
basket = basket.applymap(lambda x: 1 if x > 0 else 0)
|
| 28 |
-
|
| 29 |
-
for _, row in basket.iterrows():
|
| 30 |
-
self.transactions.append(set(row[row == 1].index))
|
| 31 |
-
|
| 32 |
-
return basket
|
| 33 |
-
|
| 34 |
-
def calculate_pair_support(self):
|
| 35 |
-
"""Calculate support for all pairs in the transactions."""
|
| 36 |
-
pair_count = defaultdict(int)
|
| 37 |
-
|
| 38 |
-
for transaction in self.transactions:
|
| 39 |
-
for pair in combinations(transaction, 2):
|
| 40 |
-
pair_count[frozenset(pair)] += 1
|
| 41 |
-
|
| 42 |
-
return {
|
| 43 |
-
pair: count for pair, count in pair_count.items()
|
| 44 |
-
if count / len(self.transactions) >= self.min_support
|
| 45 |
-
}
|
| 46 |
-
|
| 47 |
-
def generate_rules(self, frequent_pairs):
|
| 48 |
-
"""Generate association rules based on frequent pairs."""
|
| 49 |
-
rules = []
|
| 50 |
-
|
| 51 |
-
for pair, support_count in frequent_pairs.items():
|
| 52 |
-
for item in pair:
|
| 53 |
-
antecedent = frozenset([item])
|
| 54 |
-
consequent = pair - antecedent
|
| 55 |
-
|
| 56 |
-
antecedent_support = sum(1 for t in self.transactions if antecedent.issubset(t)) / len(self.transactions)
|
| 57 |
-
confidence = (support_count / len(self.transactions)) / antecedent_support
|
| 58 |
-
consequent_support = sum(1 for t in self.transactions if consequent.issubset(t)) / len(self.transactions)
|
| 59 |
-
lift = confidence / consequent_support
|
| 60 |
-
|
| 61 |
-
rules.append({
|
| 62 |
-
"Driver": list(antecedent)[0],
|
| 63 |
-
"Attach": list(consequent)[0],
|
| 64 |
-
"Support": support_count / len(self.transactions),
|
| 65 |
-
"Confidence": confidence,
|
| 66 |
-
"Lift": lift
|
| 67 |
-
})
|
| 68 |
-
|
| 69 |
-
return rules
|
| 70 |
-
|
| 71 |
-
def save_rules(self, rules, output_path):
|
| 72 |
-
"""Save generated rules to a CSV file."""
|
| 73 |
-
rules_df = pd.DataFrame(rules)
|
| 74 |
-
rules_df.to_csv(output_path, index=False)
|
| 75 |
-
print("Rules saved successfully to", output_path)
|
| 76 |
|
| 77 |
if __name__ == "__main__":
|
| 78 |
# Load configuration
|
|
@@ -90,4 +17,4 @@ if __name__ == "__main__":
|
|
| 90 |
|
| 91 |
frequent_pairs = model.calculate_pair_support()
|
| 92 |
rules = model.generate_rules(frequent_pairs)
|
| 93 |
-
model.save_rules(rules, output_path)
|
|
|
|
| 1 |
+
from apriori_model.model import AprioriModel
|
|
|
|
|
|
|
| 2 |
import json
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
if __name__ == "__main__":
|
| 5 |
# Load configuration
|
|
|
|
| 17 |
|
| 18 |
frequent_pairs = model.calculate_pair_support()
|
| 19 |
rules = model.generate_rules(frequent_pairs)
|
| 20 |
+
model.save_rules(rules, output_path)
|
config.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"folder_path": "D:
|
| 3 |
"min_support": 0.01,
|
| 4 |
"output_path": "promotion_optimizer_rules.csv"
|
| 5 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"folder_path": "D://Training//Flat files",
|
| 3 |
"min_support": 0.01,
|
| 4 |
"output_path": "promotion_optimizer_rules.csv"
|
| 5 |
}
|
model.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
from itertools import combinations
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
import json
|
| 5 |
+
import os
|
| 6 |
+
|
| 7 |
+
class AprioriModel:
|
| 8 |
+
def __init__(self, min_support=0.01):
|
| 9 |
+
self.min_support = min_support
|
| 10 |
+
self.transactions = []
|
| 11 |
+
|
| 12 |
+
def load_data(self, folder_path):
|
| 13 |
+
"""Load CSV files from a folder and combine them into a single DataFrame."""
|
| 14 |
+
combined_df = pd.DataFrame()
|
| 15 |
+
|
| 16 |
+
for file in os.listdir(folder_path):
|
| 17 |
+
if file.endswith('.csv'):
|
| 18 |
+
file_path = os.path.join(folder_path, file)
|
| 19 |
+
df = pd.read_csv(file_path)
|
| 20 |
+
combined_df = pd.concat([combined_df, df], ignore_index=True)
|
| 21 |
+
|
| 22 |
+
return combined_df
|
| 23 |
+
|
| 24 |
+
def preprocess_data(self, data):
|
| 25 |
+
"""Prepare basket data and transaction sets from raw data."""
|
| 26 |
+
basket = data.groupby(['Transaction ID', 'Product'])['Quantity'].sum().unstack().fillna(0)
|
| 27 |
+
basket = basket.applymap(lambda x: 1 if x > 0 else 0)
|
| 28 |
+
|
| 29 |
+
for _, row in basket.iterrows():
|
| 30 |
+
self.transactions.append(set(row[row == 1].index))
|
| 31 |
+
|
| 32 |
+
return basket
|
| 33 |
+
|
| 34 |
+
def calculate_pair_support(self):
|
| 35 |
+
"""Calculate support for all pairs in the transactions."""
|
| 36 |
+
pair_count = defaultdict(int)
|
| 37 |
+
|
| 38 |
+
for transaction in self.transactions:
|
| 39 |
+
for pair in combinations(transaction, 2):
|
| 40 |
+
pair_count[frozenset(pair)] += 1
|
| 41 |
+
|
| 42 |
+
return {
|
| 43 |
+
pair: count for pair, count in pair_count.items()
|
| 44 |
+
if count / len(self.transactions) >= self.min_support
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
def generate_rules(self, frequent_pairs):
|
| 48 |
+
"""Generate association rules based on frequent pairs."""
|
| 49 |
+
rules = []
|
| 50 |
+
|
| 51 |
+
for pair, support_count in frequent_pairs.items():
|
| 52 |
+
for item in pair:
|
| 53 |
+
antecedent = frozenset([item])
|
| 54 |
+
consequent = pair - antecedent
|
| 55 |
+
|
| 56 |
+
antecedent_support = sum(1 for t in self.transactions if antecedent.issubset(t)) / len(self.transactions)
|
| 57 |
+
confidence = (support_count / len(self.transactions)) / antecedent_support
|
| 58 |
+
consequent_support = sum(1 for t in self.transactions if consequent.issubset(t)) / len(self.transactions)
|
| 59 |
+
lift = confidence / consequent_support
|
| 60 |
+
|
| 61 |
+
rules.append({
|
| 62 |
+
"Driver": list(antecedent)[0],
|
| 63 |
+
"Attach": list(consequent)[0],
|
| 64 |
+
"Support": support_count / len(self.transactions),
|
| 65 |
+
"Confidence": confidence,
|
| 66 |
+
"Lift": lift
|
| 67 |
+
})
|
| 68 |
+
|
| 69 |
+
return rules
|
| 70 |
+
|
| 71 |
+
def save_rules(self, rules, output_path):
|
| 72 |
+
"""Save generated rules to a CSV file."""
|
| 73 |
+
rules_df = pd.DataFrame(rules)
|
| 74 |
+
rules_df.to_csv(output_path, index=False)
|
| 75 |
+
print("Rules saved successfully to", output_path)
|
| 76 |
+
|
| 77 |
+
# This function is optional for Hugging Face Inference API (if using API)
|
| 78 |
+
def predict(data):
|
| 79 |
+
# Example of how to process input for inference
|
| 80 |
+
model = AprioriModel(min_support=0.01)
|
| 81 |
+
processed_data = model.load_data(data['folder_path'])
|
| 82 |
+
model.preprocess_data(processed_data)
|
| 83 |
+
frequent_pairs = model.calculate_pair_support()
|
| 84 |
+
rules = model.generate_rules(frequent_pairs)
|
| 85 |
+
return rules
|
requirements.txt
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
|
|
|
| 1 |
+
pandas
|
| 2 |
+
huggingface_hub
|