การสร้าง Association Rules
ดังที่ได้เห็นไปแล้ว ฟังก์ชัน permutations จากโมดูล itertools ช่วยให้สร้างชุดกฎทั้งหมดแบบ one-antecedent, one-consequent ได้อย่างรวดเร็ว แน่นอนว่าเรายังไม่รู้ว่ากฎใดมีประโยชน์จริง เราเพียงแค่รู้ว่าแต่ละกฎเป็นวิธีการจับคู่สินค้าสองรายการที่ถูกต้อง
มาฝึกสร้างและนับจำนวนกฎทั้งหมดจากชุดข้อมูลร้านขายของชำกลุ่มย่อยกัน ได้แก่ กาแฟ ชา นม และน้ำตาล
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Market Basket Analysis ด้วย Python
คำแนะนำการฝึกหัด
- เติมคำสั่ง
importให้สมบูรณ์เพื่อนำเข้าฟังก์ชันpermutations - สร้าง association rules ทั้งหมดจากลิสต์
groceries - แสดงผลชุดกฎที่ได้
- แสดงผลจำนวนกฎทั้งหมด
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Import permutations from the itertools module
from itertools import ____
# Define the set of groceries
flattened = [i for t in transactions for i in t]
groceries = list(set(flattened))
# Generate all possible rules from groceries list
rules = list(permutations(____, 2))
# Print the set of rules
print(____)
# Print the number of rules
print(____(rules))