To perform random sampling in Python, especially for use with the Apriori algorithm, you can use libraries like pandas or numpy. Below is a clear breakdown of how to do this, along with code examples and best practices.
🔹 1. Using pandas.DataFrame.sample()
This is the most straightforward method if your data is in a pandas DataFrame, where each row represents a transaction.
✅ Example:
python
import pandas as pd
import numpy as np
# Create a dummy dataset of transactions
np.random.seed(42)
data = {
'transaction_id': range(1, 1001),
'items': [np.random.choice(['A', 'B', 'C', 'D', 'E', 'F'],
size=np.random.randint(1, 6),
replace=False).tolist()
for _ in range(1000)]
}
transactions_df = pd.DataFrame(data)
# Sample 10% of the transactions (i.e., 100 out of 1000)
sampled_df = transactions_df.sample(frac=0.1, random_state=42)
# Or sample a fixed number of transactions (e.g., 200)
# sampled_df = transactions_df.sample(n=200, random_state=42)
print(f"Original dataset size: {len(transactions_df)}")
print(f"Sampled dataset size: {len(sampled_df)}")
📝 Notes:
frac: Fraction of the dataset to sample (e.g., 0.1 for 10%).
n: Number of rows to sample directly.
random_state: Ensures reproducibility.
Each sampled row is a full transaction, preserving item co-occurrence.
🔹 2. Using numpy.random.choice()
Useful when working with NumPy arrays or lists of transactions.
✅ Example:
python
import numpy as np
# Dummy list of transactions
transactions = [
['milk', 'bread', 'butter'],
['milk', 'eggs'],
['bread', 'cheese'],
['milk', 'bread', 'cheese', 'soda'],
# ... many more transactions
]
# Sample 2 out of 4 transactions
sample_indices = np.random.choice(len(transactions), size=2, replace=False)
sampled_transactions = [transactions[i] for i in sample_indices]
print("Sampled Transactions:")
for t in sampled_transactions:
print(t)
📝 Notes:
replace=False: Ensures no duplicate transactions in the sample (default behavior).
size: Number of transactions to sample.
🔹 3. Using random.sample() (Standard Python)
For smaller datasets or when avoiding external libraries.
✅ Example:
python
import random
# Same dummy list of transactions
transactions = [
['milk', 'bread', 'butter'],
['milk', 'eggs'],
['bread', 'cheese'],
['milk', 'bread', 'cheese', 'soda'],
]
# Sample 2 transactions
sampled_transactions = random.sample(transactions, k=2)
print("Sampled Transactions:")
for t in sampled_transactions:
print(t)
📝 Notes:
k: Number of items to sample.
Does not allow duplicates (replace=False).
🔹 4. Sampling with Replacement (Optional)
Useful when simulating bootstrapping or synthetic data generation.
✅ Example:
python
# With replacement (allows duplicates)
sample_indices = np.random.choice(len(transactions), size=2, replace=True)
sampled_transactions = [transactions[i] for i in sample_indices]
🧠 Best Practices for Sampling in Apriori
Preserve Transaction Integrity: Always sample entire transactions, not individual items.
Adjust Support Thresholds: If sampling reduces the dataset size, consider lowering the min_support proportionally.
Check Representativeness: Compare item frequencies in the sample vs. the original dataset.
Reproducibility: Always use random_state or a fixed seed for consistent results.
Iterate and Validate: Use the sample to tune parameters, then validate rules on the full dataset if possible.
📌 Summary
Method
Use Case
Pros
Cons
pandas.sample()
DataFrame-based data
Simple, integrates well with ML pipelines
Requires pandas
numpy.random.choice()
Arrays/lists
Fast, flexible
Manual indexing needed
random.sample()
Small datasets
No dependencies
Slower for large data
By following these methods, you can efficiently sample your dataset for Apriori, ensuring computational efficiency while maintaining meaningful associations between items.