Chương 01 — Lộ trình Chương trình, Khung Toán học Machine Learning, Python Khoa học Dữ liệu Hiện đại & Phân tích Giỏ hàng (Market Basket Analysis)
Hợp nhất Statistical Decision Theory, kiến trúc bộ nhớ CPython/NumPy/Arrow, FP-Growth + Fisher Log-Space + BH-FDR + HUIM và cầu nối Prod2Vec / Generative Bundle.
Unit ID:
T1-P1-U01
Track & Part: Track 1 (DSAI) — Part 1: Mathematical Foundations, Statistical Inference & Causal Decision Science (part-01-math-stats-and-causal)
Truy xuất Giáo trình Gốc (R26): Lesson 1 (Introduction to the course: Course roadmap; Introduction to ML types & real-world applications; Introduction to Python for Data Science; Lab: Market Basket Analysis)
Bài thực hành Song hành (Lab 01):labs/lab-01-market-basket-analysis/(mba_lab)
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành trọn vẹn học phần T1-P1-U01 (Chương 01 và Lab 01), học viên có đủ năng lực để:
- Hình thức hóa & Định khung Bài toán (Mathematical Rigor): Ánh xạ bất kỳ hệ thống học máy nào (phân loại, xếp hạng, Self-Supervised Learning, Reinforcement Learning, Causal Uplift, Generative Modeling) vào bộ năm \((\mathcal{X}, \mathcal{Y}, P, \mathcal{H}, L)\), suy diễn bộ dự báo tối ưu Bayes dạng đóng (bao gồm ngưỡng quyết định bất đối xứng \(\tau^*\)), và phân rã rủi ro dư thừa thành \(\mathcal{E}_{\text{app}} + \mathcal{E}_{\text{est}} + \mathcal{E}_{\text{opt}}\) dưới ràng buộc của định lý No-Free-Lunch (NFL).
- Phân tích Bố cục Bộ nhớ & Phần cứng (Systems Rigor): Tính toán chính xác mức tiêu thụ RAM và hiệu suất dòng cache (
64 Bcache line) giữa CPythonlist[float], NumPyPyArrayObjectvà Apache ArrowStringView/REE; kiểm định zero-copy view so với copy quastridesvànp.shares_memory; và chẩn đoán thực thi bị khóa bởi GIL so với thực thi song song giải phóng GIL trong BLAS/SIMD. - Thực thi & Chứng minh Thuật toán Khai phá Mẫu: Thực hiện truy vết thuật toán Apriori và FP-Growth 2 lần quét (2-scan) trên cơ sở dữ liệu giao dịch; chứng minh tính đóng hướng xuống (downward closure) của Apriori và tính bị chặn \(\operatorname{Zhang}(A \to B) \in [-1, 1]\) của thước đo Zhang; phân tách chính xác sản phẩm bổ trợ (complements, \(\text{Zhang} > 0\)) khỏi sản phẩm thay thế (substitutes, \(\text{Zhang} < 0\)).
- Loại bỏ Mẫu Nhiễu Thống kê & Bẫy Biên Lợi nhuận: Ngăn chặn bùng nổ sai lầm loại I (Type-I error) và hiện tượng tràn dưới số thực dưới chuẩn (
p < 1e-308underflow) bằng phương pháp chia tập theo thời gian (temporal split-sample holdout), kiểm định chính xác Fisher một phía tính trong không gian logarit (math.lgamma+ hệ thức truy hồi \(O(1)\) +LogSumExp), hiệu chỉnh tỷ lệ khám phá saiBH-FDR(\(q\)-values), cận trênTWUtrong khai phá hữu ích cao (HUIM), và lọc biên lợi nhuận để triệt tiêu "Bẫy Phổ biến Chuối" (Banana Popularity Trap). - Kết nối Thống kê Rời rạc với Kiến trúc Neural & Generative 2026: Chứng minh đẳng thức đại số \(\mathbf{w}_i^\top \mathbf{c}_j = \ln\operatorname{lift}(i, j) - \ln k_{\text{neg}}\) và phân tích đánh đổi kiến trúc qua 5 thế hệ hệ thống gợi ý:
SSPD/HUIM,Prod2Vec, Session GNN (SR-GNN,GCE-GNN),Two-Tower + HNSW, và các mô hình truy xuất sinh/khuếch tán dùng Semantic ID (TIGER,OneRec-V2,DPE-Rec).
Tình huống Mở đầu: Vì sao Một Module "Mua Kèm" Giỏ hàng Phổ thông sụp đổ trong Production?#
Hãy hình dung một kỹ sư dữ liệu vừa tiếp nhận bài toán xây dựng widget "Thường được mua cùng nhau" (Frequently Bought Together — FBT) tại trang thanh toán của một siêu thị trực tuyến có 50,000 mã hàng (SKUs) và 10 triệu giỏ hàng lịch sử. Nếu tiếp cận theo thói quen "viết nhanh một script Python":
- Thảm họa Bộ nhớ & Tốc độ (
Python Systems Trap): Kỹ sư tải dữ liệu vào các danh sáchlist[float]/list[str]của CPython và duyệt đồng xuất hiện bằng vòng lặpforlồng nhau hoặcdf.iterrows(). Chỉ riêng10 triệusố thựcfloat64đóng hộp tronglist[float]đã tiêu tốn \(\approx 330\text{ MB}\) RAM rời rạc trên heap thay vì \(80\text{ MB}\) liên tục của NumPy, phá hủy bộ nhớ đệm L1/L2 của CPU và khóa cứng toàn bộ tiến trình trên một lõi duy nhất do Global Interpreter Lock (GIL). - Thảm họa Tổ hợp (
Combinatorial Trap): Chạy thuật toán Apriori cổ điển ở ngưỡng hỗ trợ thấp khiến bộ sinh ứng viên \(C_2\) phải cấp phát \(\binom{50{,}000}{2} \approx 1.25 \times 10^9\) cặp trong RAM và quét đi quét lại toàn bộ tệp dữ liệu qua I/O đĩa. - Thảm họa Thống kê & Kinh doanh (
Banana Trap&Substitute Contamination): Xếp hạng luật theoSupportvàConfidencethô khiến mọi giỏ hàng—từ người mua máy pha cà phê espresso đến người mua laptop—đều bị gợi ý Chuối (Banana) hoặc Túi nilon (Plastic Bag) vì tần suất nền lên tới 25%–35% nhưng biên lợi nhuận chỉ $0.15–$0.35. Tệ hơn nữa, việc thiếu kiểm định đa giả thuyết (Multiple Testing) biến các cặp nhiễu ngẫu nhiên ở đuôi dài thành các cặp cóLifthàng trăm nghìn, trong khi một thước đo không phân biệt được hướng và dấu âm lại gợi ý Sữa tươi Nhãn B ngay khi khách vừa bỏ Sữa tươi Nhãn A vào giỏ—hoặc gợi ý TV $1,200 cho khách chỉ đang mua cáp HDMI $12.
Chương 01 đặt nền móng cho toàn bộ giáo trình FSDS-SOTA-2026 bằng cách chứng minh rằng giải quyết triệt để bài toán trên đòi hỏi hợp nhất ba trụ cột không thể tách rời: (i) Lý thuyết Quyết định Thống kê (Statistical Decision Theory) để định khung đúng hàm mục tiêu; (ii) Kiến trúc Bộ nhớ & Thực thi Cấp thấp (Low-Level Memory & Arrow/NumPy Hardware Layout) để tính toán ở băng thông phần cứng thực; và (iii) Suy diễn Thống kê Chặt chẽ + Kinh tế học Giỏ hàng (Fisher trong không gian log, BH-FDR, Zhang, HUIM, CATE) làm cầu nối tự nhiên sang các kiến trúc Neural và Generative Retrieval năm 2026.
Bảng Ký hiệu Toán học Thống nhất (Unified Notation Reference)#
| Ký hiệu | Miền giá trị / Kiểu | Định nghĩa chuẩn hóa xuyên suốt Chương 01 & Lab 01 | Ký hiệu mã nguồn (mba_lab) |
|---|---|---|---|
| \(\mathcal{X}, \mathcal{Y}, \hat{\mathcal{Y}}\) | Không gian đo được | Không gian đầu vào/bối cảnh, nhãn/kết quả thực, và không gian dự báo/quyết định | — |
| \(P, \mathcal{D}_n, n\) | Độ đo xác suất, tập hợp, \(\mathbb{N}\) | Phân phối sinh dữ liệu chưa biết; mẫu huấn luyện i.i.d. \(\{(x_i, y_i)\}_{i=1}^n\) kích thước \(n\) | n_elements (benchmark) |
| \(\mathcal{H}, f, L(y, \hat{y})\) | Lớp hàm, ánh xạ, \(\mathbb{R}_{\ge 0}\) | Không gian giả thuyết; bộ dự báo \(f: \mathcal{X} \to \hat{\mathcal{Y}}\); hàm mất mát điểm | — |
| \(R(f), \hat{R}_n(f), R^*\) | \(\mathbb{R}_{\ge 0}\) | Rủi ro kỳ vọng \(\mathbb{E}[L(Y, f(X))]\); rủi ro thực nghiệm \(\frac{1}{n}\sum L\); rủi ro Bayes \(R(f^*)\) | — |
| \(\mathcal{E}_{\text{app}}, \mathcal{E}_{\text{est}}, \mathcal{E}_{\text{opt}}\) | \(\mathbb{R}\) | Sai số xấp xỉ, sai số ước lượng, và sai số tối ưu hóa hợp thành \(R(\tilde{f}_n) - R^*\) | — |
| \(\eta(x), C_{\text{FP}}, C_{\text{FN}}, \tau^*\) | \([0,1], \mathbb{R}_{>0}\) | Hậu nghiệm \(P(Y=1 \mid X=x)\); chi phí FP/FN; ngưỡng tối ưu \(\frac{C_{\text{FP}}}{C_{\text{FP}}+C_{\text{FN}}}\) | — |
| \(d_k, s_k, b\) | \(\mathbb{N}, \mathbb{Z}, \mathbb{N}\) | Chiều dài trục \(k\), bước nhảy byte (byte stride) trục \(k\), kích thước phần tử (itemsize) |
shape, strides, itemsize |
| \(\mathcal{I}, M, \prec\) | Tập hữu hạn, \(\mathbb{N}\), thứ tự | Tập danh mục SKU \(\{i_1, \dots, i_M\}\) kích thước \(M = \lvert\mathcal{I}\rvert\) với thứ tự toàn phần chuẩn | vocab |
| \(\mathcal{D}, N, T_t\) | Túi tập hợp, \(\mathbb{N}\), tập con | Cơ sở dữ liệu giao dịch \(\{T_1, \dots, T_N\}\) gồm \(N\) giỏ hàng; giỏ thứ \(t\): \(T_t \subseteq \mathcal{I}\) | transactions, n_transactions |
| \(\mathbf{B} \in \{0,1\}^{N \times M}\) | Ma trận nhị phân | Ma trận liên thuộc giỏ–mặt hàng (\(B_{t,j} = \mathbb{I}[i_j \in T_t]\)) | basket_matrix_uint8 |
| \(A \to B\) | Cặp tập rời nhau | Luật kết hợp với \(A, B \subseteq \mathcal{I}\), \(A \neq \emptyset, B \neq \emptyset, A \cap B = \emptyset\) | antecedent, consequent |
| \(\sigma(X), \sigma_{\min}, \theta_{\text{supp}}\) | \(\mathbb{N}_{\ge 0}, \mathbb{N}, (0,1]\) | Số đếm hỗ trợ tuyệt đối \(\lvert\{t : X \subseteq T_t\}\rvert\); ngưỡng đếm \(\lceil \theta_{\text{supp}} N \rceil\); tỷ lệ hỗ trợ | support_count, min_support_count |
| \(p_A, p_B, p_{AB}\) | \([0, 1]\) | Hỗ trợ tương đối \(\operatorname{supp}(A) = \sigma(A)/N\), \(\operatorname{supp}(B)\), \(\operatorname{supp}(A \cup B)\) | support |
| \(m_{\text{hyp}}, \alpha, H_m\) | \(\mathbb{N}, (0,1), \mathbb{R}_{>0}\) | Tổng số giả thuyết kiểm định (vd. \(\binom{M}{2}\)); mức kiểm soát FWER/FDR; số điều hòa \(\sum_{i=1}^m \frac{1}{i}\) | total_hypotheses, alpha |
| \(k, \ell(x), p_{\text{right}}, q_i\) | \(\mathbb{N}_{\ge 0}, \mathbb{R}_{\le 0}, [0,1]\) | Đồng xuất hiện \(\sigma(A \cup B)\); \(\ln \Pr(X=x)\); trị số \(p\) Fisher một phía; \(q\)-value BH-FDR |
support_both_count, log_p_value, p_value, q_value |
| \(\operatorname{qty}(i, T_t), \pi_i, \operatorname{TU}, \operatorname{TWU}\) | \(\mathbb{N}, \mathbb{R}\) | Số lượng SKU \(i\) trong \(T_t\); biên lợi nhuận đơn vị; tổng hữu ích giỏ; tổng \(\operatorname{TU}\) chứa \(X\) | quantity, unit_margin, line_profit, twu |
| \(\mathbf{w}_i, \mathbf{c}_j, k_{\text{neg}}\) | \(\mathbb{R}^d, \mathbb{N}\) | Vector embedding mặt hàng & ngữ cảnh SGNS; số mẫu âm (\(\mathbf{w}_i^\top \mathbf{c}_j = \ln\operatorname{lift} - \ln k_{\text{neg}}\)) | — |
Trụ cột 1 — Nền tảng Toán học & Kiến trúc Hệ thống từ Nguyên lý Gốc (First-Principles Mathematical & Theoretical Rigor)#
1.1 Lộ trình Chương trình FSDS-SOTA-2026 & Ma trận Truy xuất Nguồn (Course Roadmap & Traceability)#
Các chương trình đào tạo truyền thống thường tách rời Khoa học Dữ liệu (huấn luyện mô hình trên tệp CSV sạch trong notebook) khỏi Kỹ thuật Hệ thống AI (vận hành web backend/DevOps chung chung). Trên thực tế, các hệ thống AI năm 2026 thất bại ngay tại giao điểm giữa hai thế giới:
- Mô hình hóa thiếu tư duy hệ thống tạo ra rò rỉ thời gian (temporal leakage), xác suất không hiệu chuẩn (uncalibrated probabilities), lệch pha giữa AUC ngoại tuyến với lợi nhuận P&L, hoặc bộ nhớ KV-cache vượt ngưỡng SLA độ trễ.
- Hạ tầng thiếu hiểu biết mô hình hóa tạo ra sai lệch đặc trưng huấn luyện–phục vụ (training–serving skew), suy giảm chất lượng âm thầm khi nhãn đến muộn (late labels), và cấu trúc song song GPU sai quy mô làm sụp đổ độ trễ
TTFT/TPOT.
Chương trình Full-Stack Data Science & AI Engineering (FSDS-SOTA-2026) hợp nhất cả hai nhánh thành hai Track bổ trợ chặt chẽ gồm 12 Parts, 56 Chapters, 37 Labs, và 35 Bài viết Chuyên sâu (Deep-Dive Articles #1–#35) (theo phạm vi chuẩn hóa, Data Analytics và Building AI Web Apps được tách khỏi chương trình lõi):
-
Track 1: Data Science & AI (
DSAI) (01-track-1-dsai-sota-syllabus.md) —7Parts,30Chapters (+2Capstone Specs),17Labs, Articles#1–#14(phủ 100% 32 bài học gốc + Mini Coursework + Research Paper Capstone):- Part 1 (
part-01-math-stats-and-causal): Toán học cho ML, Suy diễn Thống kê, Conformal Prediction, Vòng đời ML & Suy diễn Nhân quả / Uplift (Article#3). - Part 2 (
part-02-classical-ml-tabular-and-domains): Hồi quy, Đánh giá Chống rò rỉ (Article#1), Hiệu chuẩn & Quyết định theo Chi phí (Article#2), Kỹ thuật Đặc trưng, SVM, GBDTs & Tabular FMs (TabPFN v2),HNSWANN, Phân cụm, Dự báo Chuỗi thời gian theo Chi phí (Article#4) + 4 Labs công nghiệp & Mini Coursework. - Part 3 (
part-03-deep-learning-and-modern-cv): PyTorch 2.x (torch.compile,bf16/fp8), Autoencoders/Nén mô hình, Thị giác máy tính hiện đại (ViT,DINOv2,YOLO11,RT-DETR,SAM 2) & IoT Predictive Maintenance. - Part 4 (
part-04-nlp-llm-post-training-and-safety): NLP/IE, Kiến trúc LLM 2026 (RoPE,SwiGLU,GQA,MLA,MoE,FlashAttention),DSPy,LoRA/QLoRA, Hậu huấn luyện Suy luận (RLVR/GRPO), và An toàn AI (Articles#9, #10, #11). - Part 5 (
part-05-rag-agents-and-evals): Production Hybrid/Graph RAG, Hệ thống Tác tửMCPtrong Sandbox, và Đánh giá LLM theo Chế độ Lỗi (Article#5). - Part 6 (
part-06-gpu-cuda-and-triton): Kiến trúc Phần cứng GPU, Phân tích Roofline, Lập trình CUDA & Viết Triton Kernel từ đầu (Online Softmax,RMSNorm,FlashAttention). - Part 7 (
part-07-frontier-world-models-robotics): Mô hình Thế giới Tiềm ẩn (JEPA,DreamerV3, Latent Action — Articles#6–#8), Robot học/VLAs (Flow Matching,Sim-to-Real— Articles#12–#14) và Luận văn Nghiên cứu (RIVF / A* / Q1).
- Part 1 (
-
Track 2: Engineering for Data & AI (
EDAI) (02-track-2-edai-sota-syllabus.md) —5Parts,26Chapters (+2Capstone Specs),20Labs, Articles#15–#35(phủ 100% 33 bài học gốc + các thực hành kỹ thuậtAIDE 1/AIDE 3):- Part 1 (
part-01-software-systems-foundations): Linux, Python sản xuất (uv), CSDL PostgreSQL, FastAPI & Load Testing, TDD/Kiểm chứng (pytest/Hypothesis), Containers (Docker/Podman). - Part 2 (
part-02-data-engineering-and-lakehouse): Kafka KRaft & Debezium CDC, Open Lakehouse (Iceberg/Delta/DuckDB/Polars), SparkAQE, Flink Watermarks/RocksDB, ClickHouse/Pinot &FeastPoint-in-Time Parity (Article#15), Airflow & DataHub. - Part 3 (
part-03-distributed-k8s-cloud-and-gateway): Hệ thống Phân tán (CAP/PACELC/Raft), Kubernetes, Kubeflow & Huấn luyện Phân tán, GCP FinOps, AI Gateway (Token Rate Limit,Semantic Cache), OpenTofu/Ansible & Istio. - Part 4 (
part-04-ml-and-llm-serving-systems): Hệ thống Phục vụ ML & LLM Hiệu năng Cao — 18 Bài viết Chuyên sâu (#18–#35) về Serving Paths, Continuous Batching, Chunked Prefill,PagedAttention/RadixAttention, Disaggregated Prefill–Decode, Speculative Decoding,FP8/INT4Quantization,TP/PP/DP/EP, Cache-Aware Routing, Profiling & CUDA Graphs. - Part 5 (
part-05-mlops-cicd-and-observability): CI/CD/CT & Triển khai An toàn (Article#16), Giám sát Chất lượng khi Nhãn Đến Muộn (Article#17), Full-stack Telemetry (OpenTelemetry,Evidently,Langfuse), SRE Error Budgets & Production Engineering Capstone.
- Part 1 (
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P1-U01)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, Dòng R26) |
Nâng cấp Chuẩn SOTA 2026 | Mục trong Chương 01 | Kiểm chứng trong Lab 01 (mba_lab) |
|---|---|---|---|
| Course roadmap: Overview of topics and skills you'll gain | Đồ thị phụ thuộc 12 Parts hai nhánh (DSAI + EDAI), tích hợp 35 Bài viết Chuyên sâu & vai trò nghề nghiệp |
Trụ cột 1 (§1.1) + Sơ đồ Mermaid 1 | README.md định vị bài thực hành trong lộ trình |
| Introduction to machine learning: types & real-world applications | Khung Lý thuyết Quyết định Thống nhất 6 hệ hình (ERM, Bayes Risk, Phân rã \(\mathcal{E}_{\text{app}} + \mathcal{E}_{\text{est}} + \mathcal{E}_{\text{opt}}\), NFL) + Thác Chỉ số Production (Netflix, Uber, Booking.com, Stripe, Airbnb) |
Trụ cột 1 (§1.2) + Trụ cột 3 (§3.2) | synthetic_retail.py (cấu trúc lợi nhuận/thay thế) & rules_and_significance.py (expected_incremental_margin) |
| Introduction to Python for Data Science | CPython PyFloatObject/PyListObject vs. PyArrayObject strides/views/stride=0/SIMD/Roofline/GIL + Arrow (StringView/ListView/REE/PyCapsule), Polars 2.0 vs. DuckDB 1.5 vs. Pandas 3.0, Python 3.13–3.15t (abi3t), uv & PEP 751, và Anti-Patterns |
Trụ cột 1 (§1.3) + Trụ cột 2 (§2.1) + Trụ cột 3 (§3.4) + Sơ đồ Mermaid 2 | memory_benchmark.py (benchmark_vector_scale_and_sum, benchmark_cooccurrence_engines, audit_numpy_views_and_strides) |
| Lab: Market basket analysis | Dàn mục Itemset Lattice, Apriori vs. FP-Growth 2-quét, 8 thước đo (chứng minh \(\text{Zhang} \in [-1,1]\) + Kulc/IR) + SSPD (Webb SSI) + Fisher chính xác (\(\ln p\)) & BH-FDR / Holm + Holdout Split + HUIM (TWU/HUI-Miner/EFIM) + Cầu nối Neural/Generative (Prod2Vec \(\equiv\) shifted \(\ln\text{Lift}\) \(\to\) DPE-Rec) |
Trụ cột 1 (§1.4) + Trụ cột 2 (§2.2–§2.4) + Trụ cột 3 (§3.1, §3.3) + Trụ cột 4 + Sơ đồ Mermaid 3 | Gói mba_lab đầy đủ (fpgrowth.py, rules_and_significance.py, synthetic_retail.py, scripts/run_lab_demo.py, 16 kiểm thử pytest) |
1.2 Khung Toán học Thống nhất cho Các Hệ hình Machine Learning (Unified Decision-Theoretic ML Framing)#
Thay vì liệt kê Machine Learning như một danh sách rời rạc các thuật toán ("Học có giám sát dùng để phân loại, Học không giám sát dùng để phân cụm"), cách tiếp cận chuẩn thống kê xem mọi hệ hình AI cổ điển lẫn tiên phong 2026 đều là bài toán tối ưu hóa một hàm giả thuyết hoặc chính sách \(f \in \mathcal{H}\) dưới quá trình sinh dữ liệu (hoặc động lực học môi trường) \(P\) và hàm mất mát (hoặc hàm hữu ích âm) \(L\):
- Không gian Đầu vào / Bối cảnh (\(\mathcal{X}\)): Không gian đo được chứa đặc trưng, trạng thái, câu lệnh (prompts), hoặc bối cảnh (ví dụ \(\mathcal{X} \subseteq \mathbb{R}^d\), chuỗi token \(\mathcal{V}^*\), hoặc không gian trạng thái \(\mathcal{S}\)).
- Không gian Đích / Hành động / Biến ẩn (\(\mathcal{Y}\)): Không gian đầu ra, nhãn thực, hành động \(\mathcal{A}\), biểu diễn ẩn \(\mathcal{Z}\), hoặc kết quả phản thực tế (potential outcomes) \((Y(0), Y(1))\).
- Không gian Quyết định / Dự báo (\(\hat{\mathcal{Y}}\)): Không gian giá trị mà mô hình xuất ra (nhãn, phân phối xác suất \(\Delta^{K-1}\), chính sách hành động \(\pi(x)\)).
- Quá trình Sinh Dữ liệu (\(P\)): Độ đo xác suất chưa biết (hoặc nhân chuyển trạng thái Markov) chi phối các quan sát và phản hồi.
- Không gian Giả thuyết / Chính sách (\(\mathcal{H}\)) & Hàm Mất mát (\(L\)): Họ hàm khả đo \(f: \mathcal{X} \to \hat{\mathcal{Y}}\) bị ràng buộc cấu trúc cùng hàm phạt điểm \(L: \mathcal{Y} \times \hat{\mathcal{Y}} \to \mathbb{R}\) (hoặc hàm giá trị trên quỹ đạo).
Bảng Ánh xạ Thống nhất 6 Hệ hình Machine Learning#
Hệ hình (Paradigm) |
Không gian Đầu vào (\(\mathcal{X}\)) | Không gian Đích / Quyết định (\(\mathcal{Y}, \hat{\mathcal{Y}}\)) | Quá trình Sinh Dữ liệu (\(P\)) | Không gian Giả thuyết (\(\mathcal{H}\)) | Hàm Mất mát / Mục tiêu Chuẩn (\(L\)) |
|---|---|---|---|---|---|
| Supervised Learning (Phân loại, Hồi quy, Xếp hạng) | Vector đặc trưng \(x \in \mathcal{X}\) | Nhãn \(\{1,\dots,K\}\), số thực \(\mathbb{R}\), hoặc hoán vị \(\Pi_m\) | Độ đo đồng thời i.i.d. \(P(X, Y)\) | Bộ dự báo \(f_\theta: \mathcal{X} \to \hat{\mathcal{Y}}\) (hoặc \(\Delta^{K-1}\)) | Cross-entropy \(-\log f_\theta(x)_y\); MSE \((y - f_\theta(x))^2\); Pairwise/Listwise ranking loss |
| Unsupervised Learning (Phân cụm, Giảm chiều, Ước lượng mật độ) | Quan sát không nhãn \(x \in \mathcal{X}\) | Chỉ số cụm \(\{1,\dots,K\}\), mã chiều thấp \(z \in \mathbb{R}^k\) (\(k \ll d\)) | Độ đo biên \(P(X)\) | Bộ mã hóa/giải mã \((E, D)\), tâm cụm \(\{\mu_k\}\), hoặc mật độ \(p_\theta\) | Tái tạo \(\lVert x - D(E(x))\rVert_2^2\); Quán tính \(K\)-means \(\min_k \lVert x - \mu_k\rVert_2^2\); \(-\log p_\theta(x)\) |
| Self-Supervised Learning (SSL) (Masked, Contrastive, JEPA) | Góc nhìn che khuất/tăng cường \(x_{\text{ctx}}\) hoặc \((x, x^+)\) | Phần bị che \(x_{\text{tgt}}\) hoặc đích ẩn \(z_{\text{tgt}} = \text{sg}(E_{\bar{\theta}}(x_{\text{tgt}}))\) | Biên \(P(X)\) + nhân nhiễu/biến đổi \(T(\tilde{x} \mid x)\) | Bộ mã hóa \(E_\theta: \mathcal{X} \to \mathbb{R}^k\) + bộ dự báo \(g_\phi\) | InfoNCE \(-\log \frac{\exp(\text{sim}(z, z^+)/\tau)}{\sum_j \exp(\text{sim}(z, z_j^-)/\tau)}\); Dự báo tiềm ẩn \(\lVert g_\phi(E_\theta(x_{\text{ctx}})) - z_{\text{tgt}}\rVert_2^2\) |
| Reinforcement Learning (RL) (Điều khiển MDP & RLHF/RLVR) | Trạng thái môi trường \(s_t \in \mathcal{S}\) | Hành động \(a_t \in \mathcal{A}\) (hoặc chuỗi token) | MDP \((\mathcal{S}, \mathcal{A}, P(s_{t+1}\mid s_t, a_t), R, \gamma)\) | Chính sách ngẫu nhiên \(\pi_\theta(a \mid s) \in \Delta(\mathcal{A})\) | Tổng phần thưởng chiết khấu âm \(-J(\pi_\theta) = -\mathbb{E}_{\tau \sim \pi_\theta}\!\left[\sum_{t=0}^\infty \gamma^t R(s_t, a_t)\right]\) |
| Causal / Decision ML (Uplift, Chính sách Can thiệp) | Biến hiệp phương sai \(X \in \mathcal{X}\), can thiệp \(T \in \{0,1\}\) | Kết quả phản thực tế \((Y(0), Y(1))\), quy tắc quyết định \(\pi(x) \in \{0,1\}\) | Mô hình Nhân quả Cấu trúc \(\mathcal{M}\) sinh luật \(P(Y \mid do(T=t), X)\) | Bộ ước lượng CATE \(\hat{\tau}(x)\) & quy tắc \(\pi: \mathcal{X} \to \{0,1\}\) | Giá trị chính sách âm \(-\mathbb{E}[Y(\pi(X)) - c \cdot \pi(X)]\); R-loss / AIPW hai lần bền vững cho \(\tau(x) = \mathbb{E}[Y(1)-Y(0)\mid X=x]\) |
| Generative Modeling (Autoregressive, VAE, Diffusion/Flow) | Điều kiện \(c \in \mathcal{C}\) (hoặc \(\emptyset\)) & nhiễu \(\epsilon \sim p_0\) | Mẫu tổng hợp \(x \in \mathcal{X}\) | Luật điều kiện/biên đích \(P(X \mid C)\) | Mật độ tham số \(p_\theta(x \mid c)\) hoặc trường vận tốc \(v_\theta(x_t, t)\) | Forward KL \(\operatorname{KL}(P \parallel P_\theta)\) (MLE); ELBO âm; Flow Matching \(\mathbb{E}_{t,x_0,x_1}[\lVert v_\theta(x_t, t) - (x_1 - x_0)\rVert_2^2]\) |
Tối thiểu hóa Rủi ro Thực nghiệm (ERM), SRM & Bộ Dự báo Tối ưu Bayes (Bayes-Optimal Predictors)#
Cho \((X, Y) \sim P\) và hàm mất mát khả đo \(L: \mathcal{Y} \times \hat{\mathcal{Y}} \to \mathbb{R}_{\ge 0}\):
- Rủi ro Kỳ vọng / Rủi ro Tổng thể (Expected / Population Risk):
\[R(f) := \mathbb{E}_{(X, Y) \sim P}\big[L(Y, f(X))\big] = \int_{\mathcal{X} \times \mathcal{Y}} L\big(y, f(x)\big)\,dP(x, y).\]
- Tối thiểu hóa Rủi ro Thực nghiệm (
Empirical Risk Minimization — ERM): Vì \(P\) không quan sát được trực tiếp, ta dùng mẫu i.i.d. hữu hạn \(\mathcal{D}_n = \{(x_i, y_i)\}_{i=1}^n \sim P^n\) để tối ưu trung bình mẫu trong họ hàm \(\mathcal{H}\):\[\hat{R}_n(f) := \frac{1}{n}\sum_{i=1}^n L\big(y_i, f(x_i)\big), \qquad \hat{f}_n \in \arg\min_{f \in \mathcal{H}} \hat{R}_n(f).\] - Tối thiểu hóa Rủi ro Cấu trúc (
Structural Risk Minimization — SRM): Để kiểm soát độ phức tạp của \(\mathcal{H}\), SRM cộng thêm hàm phạt \(\Omega: \mathcal{H} \to \mathbb{R}_{\ge 0}\) điều chỉnh bởi siêu tham số \(\lambda \ge 0\):\[\hat{f}_{n, \lambda} \in \arg\min_{f \in \mathcal{H}} \Big\{ \hat{R}_n(f) + \lambda \Omega(f) \Big\}.\] - Bộ Dự báo Tối ưu Bayes (\(f^*\)) và Rủi ro Bayes (\(R^*\)): Nếu cho phép tìm kiếm trên tất cả các hàm khả đo \(\mathcal{F}_{\text{all}}\) (không bị giới hạn bởi \(\mathcal{H}\)), cực tiểu hóa rủi ro điều kiện theo từng điểm \(x\) cho ta nghiệm lý thuyết tốt nhất có thể \(f^*\) và sàn nhiễu bất khả quy (irreducible noise floor) \(R^*\):
\[f^*(x) \in \arg\min_{\hat{y} \in \hat{\mathcal{Y}}} \mathbb{E}_{Y \mid X=x}\big[L(Y, \hat{y}) \mid X = x\big], \qquad R^* := \inf_{f \in \mathcal{F}_{\text{all}}} R(f) = R(f^*).\]
5 Nghiệm Dạng Đóng Của Bộ Dự báo Tối ưu Bayes:
- Mất mát Bình phương Sai số (
Squared Error/ \(L_2\)): \(L(y, \hat{y}) = (y - \hat{y})^2\).
Lấy đạo hàm rủi ro điều kiện \(\phi(\hat{y}) = \mathbb{E}[(Y - \hat{y})^2 \mid X=x]\) theo \(\hat{y}\) và đặt bằng \(0\):\[\frac{\partial \phi}{\partial \hat{y}} = -2\big(\mathbb{E}[Y \mid X=x] - \hat{y}\big) = 0 \implies f^*(x) = \mathbb{E}[Y \mid X = x], \qquad R^* = \mathbb{E}_X\big[\operatorname{Var}(Y \mid X)\big].\] - Mất mát Trị tuyệt đối (
Absolute Error/ \(L_1\)): \(L(y, \hat{y}) = |y - \hat{y}|\).
Điều kiện dưới vi phân bằng \(0\) tại \(\hat{y}\) đòi hỏi khối lượng xác suất hai phía cân bằng: \(P(Y \ge \hat{y} \mid X=x) \ge \frac{1}{2}\) và \(P(Y \le \hat{y} \mid X=x) \ge \frac{1}{2}\), do đó:\[f^*(x) = \operatorname{Median}(Y \mid X = x).\] - Mất mát Phân loại 0–1 (
Zero-One Loss): \(L(y, \hat{y}) = \mathbb{I}[y \neq \hat{y}]\) với \(y \in \{1, \dots, K\}\).
Vì \(\mathbb{E}[\mathbb{I}[Y \neq \hat{y}] \mid X=x] = 1 - P(Y = \hat{y} \mid X=x)\), tối thiểu hóa rủi ro tương đương cực đại hóa xác suất hậu nghiệm:\[f^*(x) = \arg\max_{c \in \{1,\dots,K\}} P(Y = c \mid X = x), \qquad R^* = 1 - \mathbb{E}_X\!\left[\max_{c \in \{1,\dots,K\}} P(Y = c \mid X)\right].\] - Mất mát Nhị phân Chi phí Bất đối xứng (
Asymmetric Cost-Sensitive Binary Loss):
Đặt chi phí báo động giả \(L(0, 1) = C_{\text{FP}} > 0\), chi phí bỏ sót \(L(1, 0) = C_{\text{FN}} > 0\), và \(L(0,0) = L(1,1) = 0\). Ký hiệu hậu nghiệm \(\eta(x) := P(Y=1 \mid X=x)\). Khi dự báo \(\hat{y}=1\), rủi ro điều kiện là \(C_{\text{FP}}(1 - \eta(x))\); khi dự báo \(\hat{y}=0\), rủi ro điều kiện là \(C_{\text{FN}}\eta(x)\). Quyết định \(\hat{y}=1\) là tối ưu Bayes khi và chỉ khi:\[C_{\text{FP}}(1 - \eta(x)) \le C_{\text{FN}}\eta(x) \iff C_{\text{FP}} \le (C_{\text{FP}} + C_{\text{FN}})\eta(x) \iff \eta(x) \ge \tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}.\]Hệ quả thực tế: Ngưỡng mặc định0.5chỉ đúng khi \(C_{\text{FP}} = C_{\text{FN}}\). Trong phát hiện gian lận (Stripe) hoặc tiếp thị giữ chân, chính tỷ số chi phí \(C_{\text{FP}} / (C_{\text{FP}} + C_{\text{FN}})\)—chứ không phải điểm F1 trên tập validation—quyết định ngưỡng cắt \(\tau^*\), đòi hỏi xác suất dự báo \(\hat{\eta}(x)\) phải được hiệu chuẩn (calibrated). - Mất mát Logarit (
Log-Loss / Cross-Entropy): \(L(y, q) = -\log q(y)\) với phân phối dự báo \(q(\cdot \mid x) \in \Delta^{K-1}\).
Phân tách kỳ vọng điều kiện bằng cách cộng và trừ \(\log P(Y \mid X=x)\):\[\mathbb{E}_{Y \mid X=x}\big[-\log q(Y \mid x)\big] = \underbrace{\mathbb{E}_{Y \mid X=x}\big[-\log P(Y \mid X=x)\big]}_{H(Y \mid X=x)} + \underbrace{\mathbb{E}_{Y \mid X=x}\!\left[\log \frac{P(Y \mid X=x)}{q(Y \mid x)}\right]}_{\operatorname{KL}\big(P(Y \mid X=x) \,\parallel\, q(\cdot \mid x)\big)}.\]Theo Bất đẳng thức Gibbs (\(\operatorname{KL} \ge 0\), dấu bằng xảy ra khi và chỉ khi \(q(\cdot \mid x) = P(\cdot \mid X=x)\) hầu khắp nơi), ta thu được \(q^*(y \mid x) = P(Y = y \mid X = x)\) và \(R^* = H(Y \mid X)\) (entropy Shannon có điều kiện).
Phân rã Rủi ro Dư thừa (Excess Risk Decomposition) & Phương sai–Độ lệch Điểm (Bias–Variance)#
Gọi \(f_{\mathcal{H}}^* \in \arg\min_{f \in \mathcal{H}} R(f)\) là hàm tốt nhất trong lớp giả thuyết \(\mathcal{H}\), \(\hat{f}_n \in \arg\min_{f \in \mathcal{H}} \hat{R}_n(f)\) là nghiệm ERM chính xác, và \(\tilde{f}_n \in \mathcal{H}\) là hàm thực tế thu được từ bộ tối ưu hóa hữu hạn bước (như SGD/AdamW dừng sớm). Rủi ro dư thừa (Excess Risk) \(R(\tilde{f}_n) - R^*\) phân rã cộng tính chính xác thành ba thành phần:
- Sai số Xấp xỉ \(\mathcal{E}_{\text{app}}(\mathcal{H}) \ge 0\): Sàn lỗi tất định do lớp \(\mathcal{H}\) có thể không chứa \(f^*\). Mở rộng \(\mathcal{H}\) (thêm tham số, kiến trúc giàu sức biểu diễn hơn) làm giảm đơn điệu \(\mathcal{E}_{\text{app}}\).
- Sai số Ước lượng \(\mathcal{E}_{\text{est}}(\mathcal{H}, n)\): Phương sai thống kê sinh ra vì tối thiểu hóa \(\hat{R}_n\) trên mẫu hữu hạn \(n\) thay vì \(R\) trên \(P\). Nhờ bất đẳng thức ERM cơ bản \(\hat{R}_n(\hat{f}_n) \le \hat{R}_n(f_{\mathcal{H}}^*)\), ta chứng minh được chặn hội tụ đồng đều (uniform convergence bound):
\[\mathcal{E}_{\text{est}}(\mathcal{H}, n) = \big(R(\hat{f}_n) - \hat{R}_n(\hat{f}_n)\big) + \underbrace{\big(\hat{R}_n(\hat{f}_n) - \hat{R}_n(f_{\mathcal{H}}^*)\big)}_{\le 0} + \big(\hat{R}_n(f_{\mathcal{H}}^*) - R(f_{\mathcal{H}}^*)\big) \le 2 \sup_{f \in \mathcal{H}} \big|R(f) - \hat{R}_n(f)\big|.\]Với hàm mất mát bị chặn \(L \in [0, B_L]\), lý thuyết Vapnik–Chervonenkis / Rademacher chặn đại lượng supremum này ở tốc độ \(O\!\big(\sqrt{\text{VC}(\mathcal{H})\log(n)/n}\big)\) hoặc \(O(\mathfrak{R}_n(\mathcal{H}))\): mở rộng \(\mathcal{H}\) làm phình \(\mathcal{E}_{\text{est}}\) trừ khi \(n\) tăng tương ứng hoặc điều chuẩn thu hẹp dung lượng hiệu dụng của \(\mathcal{H}\).
- Sai số Tối ưu hóa \(\mathcal{E}_{\text{opt}}\): Khoảng cách giữa nghiệm thuật toán \(\tilde{f}_n\) và nghiệm ERM toàn cục \(\hat{f}_n\). (Lưu ý tinh tế trong chế độ mạng nơ-ron quá tham số hóa / phi lồi: cơ chế điều chuẩn ngầm của SGD dừng sớm có thể khiến \(\mathcal{E}_{\text{opt}} < 0\) theo nghĩa rủi ro tổng quát hóa \(R(\tilde{f}_n) < R(\hat{f}_n)\) khi \(\hat{f}_n\) nội suy nhiễu mẫu).
Tại một điểm truy vấn cố định \(x\) dưới mất mát bình phương với \(Y = f^*(x) + \varepsilon\), \(\mathbb{E}[\varepsilon \mid x]=0\), \(\operatorname{Var}(\varepsilon \mid x)=\sigma^2(x)\), sai số dự báo kỳ vọng phân rã thành phương trình Bias–Variance–Noise kinh điển:
Thiên kiến Quy nạp (Inductive Bias) & Định lý No-Free-Lunch của Wolpert (1996)#
Thiên kiến Quy nạp (Inductive Bias) là toàn bộ tập giả định tiên nghiệm—tường minh hoặc ngầm định—cho phép một thuật toán khái quát hóa từ tập quan sát hữu hạn \(\mathcal{D}_n\) sang miền chưa thấy \(\mathcal{X} \setminus \{x_1, \dots, x_n\}\):
- Restriction Bias: Lựa chọn họ \(\mathcal{H}\) (siêu phẳng tuyến tính, cây quyết định chia vuông góc trục, hàm Lipschitz).
- Preference / Regularization Bias: Xếp thứ tự ưu tiên trong \(\mathcal{H}\) qua \(\Omega(f)\) hoặc tiên nghiệm Bayes \(P(f)\) (\(L_2\) mượt, \(L_1\) thưa, lề cực đại).
- Architectural / Symmetry Bias: Tính bất biến hoặc đồng biến cấu trúc (bất biến tịnh tiến trong CNN, đồng biến hoán vị trong Self-Attention / GNN).
- Implicit Optimization Bias: Quỹ đạo tối ưu của Gradient Descent / AdamW ưu tiên nghiệm chuẩn cực tiểu hoặc cực tiểu phẳng giữa vô số nghiệm nội suy có cùng \(\hat{R}_n = 0\).
Định lý (Wolpert's No-Free-Lunch Theorem; Wolpert, 1996):
Cho miền đầu vào hữu hạn \(\mathcal{X}\), tập nhãn hữu hạn \(\mathcal{Y}\) (\(\lvert\mathcal{Y}\rvert \ge 2\)), tập hàm đích tất định \(f \in \mathcal{Y}^{\mathcal{X}}\), và hai bộ học bất kỳ \(A_1, A_2\) ánh xạ mẫu huấn luyện \(\mathcal{D}_n = \{(x_i, f(x_i))\}_{i=1}^n\) (\(n < \lvert\mathcal{X}\rvert\)) thành giả thuyết \(h\). Định nghĩa lỗi ngoài tập huấn luyện (Off-Training-Set — OTS error) chỉ đánh giá trên \(x \notin \mathcal{D}_n\):
Nếu phân phối tiên nghiệm trên các hàm đích là đồng đều \(P(f) = \lvert\mathcal{Y}\rvert^{-\lvert\mathcal{X}\rvert}\) (tức mọi giá trị \(f(x)\) ngoài \(\mathcal{D}_n\) độc lập có điều kiện và phân bố đều khi đã biết \(\mathcal{D}_n\)), thì với mọi cặp thuật toán \(A_1, A_2\), mọi cỡ mẫu \(n < \lvert\mathcal{X}\rvert\), và mọi cơ chế lấy mẫu \(\mathcal{D}_n\):
Với phân loại nhị phân (\(\lvert\mathcal{Y}\rvert = 2\)), sai số OTS kỳ vọng trung bình trên mọi hàm đích của bất kỳ thuật toán nào—từ mạng Transformer sâu đến "anti-cross-validation" chọn mô hình tệ nhất trên CV—đều bằng đúng \(1/2\). Ở phiên bản mẫu hữu hạn phi phân phối (Shalev-Shwartz & Ben-David, 2014), với mọi bộ học \(A\) huấn luyện trên \(n < \lvert\mathcal{X}\rvert / 2\) mẫu, luôn tồn tại một phân phối khả hiện (\(R^* = 0\)) sao cho với xác suất \(\ge 1/7\), \(R(A(\mathcal{D}_n)) \ge 1/8\).
Hệ quả Kỹ thuật Cốt lõi: Không tồn tại thuật toán "vô địch toàn năng" trên mọi phân phối. ML thực tế hoạt động được hoàn toàn nhờ phân phối dữ liệu tự nhiên \(P\) mang cấu trúc không đồng đều (chiều nội tại thấp, độ trơn cục bộ, tương tác đặc trưng phân tầng, bất biến nhân quả). Thiết kế mô hình chuẩn xác nghĩa là khớp thiên kiến quy nạp của \(\mathcal{H}\) với hình học của miền dữ liệu \(P\) (ví dụ: GBDT cho dữ liệu bảng phi tuyến cắt trục vs. Transformer cho chuỗi ngữ cảnh dài).
1.3 Kiến trúc Bộ nhớ CPython vs. NumPy PyArrayObject & Hiệu năng Phần cứng (Memory Layout, Strides, SIMD, Roofline & GIL)#
Chi phí Đóng hộp (Boxing Overhead) của CPython so với Bộ đệm Liên tục NumPy#
Trong CPython tiêu chuẩn (kiến trúc 64-bit), mọi giá trị đều là một cấu trúc C cấp phát trên heap có phần đầu PyObject_HEAD (16 B: Py_ssize_t ob_refcnt chiếm 8 B + PyTypeObject *ob_type chiếm 8 B):
PyFloatObject(float): GồmPyObject_HEAD(16 B) +double ob_fval(8 Bpayload chuẩn IEEE-754 binary64) =24 B(sys.getsizeof(1.0) == 24). Chỉ để lưu 8 byte số thực, CPython chịu phình dữ liệu \(3\times\) trước cả con trỏ danh sách.PyListObject(list[float]): Vìlistcó thể chứa chu trình tham chiếu (Py_TPFLAGS_HAVE_GC), CPython đặt thêmPyGC_Head(16 B:_gc_next,_gc_prev) ngay trướcPyVarObject(24 B:PyObject_HEAD+ob_size) cộng vớiPyObject **ob_item(8 B) vàPy_ssize_t allocated(8 B), tạo nên phần đầu56 B(sys.getsizeof([]) == 56). Mỗi phần tử gắn vàolist[float]tiêu tốn thêm 1 con trỏ8 Btrong mảngob_item(mảng này tự cấp phát dư \(\sim 12.5\%\) theo công thứcnew_size + (new_size >> 3) + 6với \(n \ge 9\)), trỏ tới mộtPyFloatObject(24 B) nằm rải rác tại một địa chỉ ảo bất kỳ trên heap.numpy.ndarray(PyArrayObject): Chỉ sử dụng 1 header duy nhất (PyArrayObject, khoảng112 Bcho mảng 1D) chứa con trỏ thôchar *data, số chiềuint nd,npy_intp *dimensions,npy_intp *strides, con trỏ chủ sở hữuPyObject *base, bộ mô tả kiểuPyArray_Descr *descr, và cờ trạng tháiflags(C_CONTIGUOUS,F_CONTIGUOUS,WRITEABLE,ALIGNED). Toàn bộ dữ liệu số thực nằm liên tiếp trong một vùng đệm C thuần túy không đóng hộp (unboxed): đúng8 Bcho mỗifloat64.
Bảng So sánh Bộ nhớ & Phân cấp Cache cho \(N = 10^7\) giá trị float64 (CPython 64-bit)#
| Tiêu chí Kiến trúc | list[float] (Boxed CPython) |
numpy.ndarray (dtype=np.float64) |
|---|---|---|
| Byte mỗi phần tử (trừ header chứa) | \(24\text{ B (PyFloatObject)} + 8\text{ B (ptr)} \approx 32\text{ B}\) (\(\sim 33\text{ B}\) tính cả 12.5% dư ob_item) |
\(8\text{ B}\) (đúng tải IEEE-754; \(0\text{ B}\) siêu dữ liệu mỗi phần tử) |
| Tổng RAM cho \(N = 10^7\) số thực | \(\approx 330\text{ MB}\) (cộng phân mảnh pymalloc/heap) |
\(\approx 80\text{ MB}\) (nhỏ hơn \(> 4.1\times\)) |
Khai thác dòng Cache 64 B (x86-64) |
Nạp 64 B từ ob_item chỉ được 8 con trỏ, mỗi con trỏ lại nhảy ngẫu nhiên trên heap để giải tham chiếu 24 B (tỷ lệ trượt L1/L2/L3 cực cao; vô hiệu hóa bộ nạp trước phần cứng) |
8 giá trị float64 liên tiếp trên mỗi dòng cache 64 B; bộ nạp trước tuần tự (hardware stride prefetcher) hoạt động ở băng thông tối đa |
| Chi phí vòng lặp mỗi phần tử | Giải mã bytecode + đọc ob_item[i] + nhảy tới PyFloatObject + kiểm tra kiểu động + cấp phát heap PyFloatObject mới & cập nhật ob_refcnt |
Vòng lặp C/SIMD chặt trên con trỏ double* (data) với 0 lần đóng hộp PyObject |
Số học Bước nhảy (Stride Arithmetic), C-Order vs. F-Order, và Zero-Copy View vs. Copy#
Với mảng \(n\)-chiều có hình dạng shape \((d_0, d_1, \dots, d_{n-1})\) và bước nhảy byte (byte strides) \((s_0, s_1, \dots, s_{n-1}) \in \mathbb{Z}^n\), địa chỉ byte chính xác của phần tử \(A[i_0, i_1, \dots, i_{n-1}]\) là:
Đặt \(b = \text{arr.itemsize}\) (ví dụ \(b = 8\text{ B}\) cho float64):
- C-order (Row-Major, mặc định của NumPy): Trục cuối biến thiên nhanh nhất trong RAM:
\[s_{n-1} = b, \qquad s_k = b \prod_{j=k+1}^{n-1} d_j \quad (0 \le k < n-1).\]Ví dụ:
shape=(3, 4),float64(\(b=8\)) \(\implies\)strides=(32, 8). - Fortran-order (Column-Major, chuẩn BLAS/LAPACK): Trục đầu biến thiên nhanh nhất:
\[s_0 = b, \qquad s_k = b \prod_{j=0}^{k-1} d_j \quad (0 < k \le n-1).\]Ví dụ:
shape=(3, 4),float64(\(b=8\)) \(\implies\)strides=(8, 24).
Một View (\(O(1)\) thời gian, \(O(1)\) RAM) chỉ tạo một PyArrayObject header mới trỏ base về mảng gốc (kiểm tra bằng v.base is not None hoặc np.shares_memory(a, v)):
Thao tác trên ndarray |
Biến đổi lên (data, shape, strides) |
View hay Copy? |
|---|---|---|
Cắt lát cơ bản a[start:stop:step] trục \(k\) |
\(\text{data}' = \text{data} + \text{start}\cdot s_k\); \(d_k' = \lceil(\text{stop}-\text{start})/\text{step}\rceil\); \(s_k' = \text{step}\cdot s_k\) (đảo ngược a[::-1] tạo bước nhảy âm \(s_k' = -s_k\)) |
Luôn là View |
Chuyển vị a.T / swapaxes(i, j) |
Hoán đổi các bộ shape và strides; vd. C-order (3,4), (32,8) \(\to\) F-order (4,3), (8,32) |
Luôn là View |
Đổi hình dạng a.reshape(new_shape) |
Trả về View khi và chỉ khi tồn tại bộ stride hằng số tương thích (luôn đúng với mảng C/F liên tục; buộc Copy nếu không liên tục, vd. a.T.reshape(-1)) |
View nếu tương thích stride; ngược lại Copy |
Chỉ mục Fancy / Boolean a[[0, 2]], a[a > 0] |
Tập vị trí không tuyến tính không thể biểu diễn bằng vector bước nhảy tuyến tính \((s_0, \dots, s_{n-1})\) | Luôn là Copy |
Hiểm họa Rò rỉ Bộ nhớ trong Production (v.base Memory Pin): Khi cắt một lát nhỏ v = big_arr[:10], trường v.base vẫn giữ tham chiếu mạnh tới toàn bộ mảng big_arr nặng nhiều GB trong RAM cho tới khi v được giải phóng. Luôn gọi tường minh v = big_arr[:10].copy() trước khi loại bỏ tập dữ liệu gốc.
Broadcasting (stride = 0), SIMD Vectorization & Mô hình Roofline#
Quy tắc Broadcasting 3 bước giữa hai mảng \(S_A = (a_0, \dots, a_{p-1})\) và \(S_B = (b_0, \dots, b_{q-1})\) với \(r = \max(p, q)\):
- Căn phải (Đệm
1bên trái): Thêm các chiều kích thước1vào đầu mảng ngắn hơn để cả hai đạt hạng \(r\). - Tương thích từng trục: Trên mỗi trục \(k \in \{0, \dots, r-1\}\), kích thước tương thích khi và chỉ khi \(a_k = b_k\) hoặc \(a_k = 1\) hoặc \(b_k = 1\) (nếu vi phạm sẽ báo lỗi
ValueError). - Mở rộng Ảo Zero-Copy (
stride = 0): Chiều đầu ra là \(d_k = \max(a_k, b_k)\). Mở rộng một trục từ \(1 \to d_k\) đặt bước nhảy tại trục đó bằng \(s_k = 0\) byte, tức \(\operatorname{addr}(\dots, i_k, \dots) = \text{data} + \dots + i_k \cdot 0 + \dots\). Giá trị được đọc lại ngay từ thanh ghi hoặc L1 cache với 0 byte nhân bản trung gian. (Ví dụ:Xshape(3, 1)cộngYshape(1, 4)cho góc nhìn broadcast(3, 4)có stride lần lượt là(8, 0)và(0, 8).)
Khi vùng đệm liên tục và bước nhảy vòng trong bằng đơn vị (\(s_{\text{inner}} = b\)), nhân C/SIMD của NumPy đóng gói dữ liệu vào các thanh ghi vector rộng: AVX2 (256-bit YMM: 4 float64 hoặc 8 float32 mỗi lệnh) và AVX-512 (512-bit ZMM: 8 float64 hoặc 16 float32 mỗi lệnh). Ngược lại, bước nhảy khác đơn vị (như cộng theo axis=0 trên mảng C-order lớn hoặc a[::7]) làm hỏng nạp liên tục, buộc CPU tải rời rạc.
Trực giác Mô hình Roofline (Arithmetic Intensity — \(\text{AI}\)):
Phân tích Roofline so sánh cường độ số học \(\text{AI} = \frac{\text{FLOP}}{\text{Byte truyền từ DRAM}}\) của nhân tính toán với điểm gãy phần cứng (tỷ số giữa năng lực \(\text{FLOP/s}\) đỉnh và băng thông DRAM \(\text{GB/s}\)):
- Tác vụ theo phần tử (Element-wise scaling & sum): Tính \(\sum_{i=0}^{n-1} (1.75 x_i + 0.25 w_i)\) thực hiện \(3\) phép tính dấu phẩy động (
2nhân +1cộng, hoặc2với FMA +1cộng tích lũy) trên mỗi cặpfloat64đọc vào (16 Bđọc từxvàw) \(\implies \text{AI} \approx 3 / 16 \approx 0.19\text{ FLOP/Byte}\) (hoặc \(\approx 0.125\text{ FLOP/Byte}\) khi ghi kết quả ra mảng trung gian24 B). Với \(\text{AI} \ll 1\), tác vụ bị giới hạn chặt bởi băng thông bộ nhớ (memory-bandwidth-bound): nhanh gấp nhiều chục lần Python thuần nhờ loại bỏ boxing & tận dụng SIMD/prefetcher, nhưng chạm trần tốc độ truyền RAM. - Nhân ma trận BLAS cho đồng xuất hiện giỏ hàng (\(\mathbf{C} = \mathbf{B}^\top \mathbf{B}\)): Với \(\mathbf{B} \in \mathbb{R}^{N \times M}\), phép nhân ma trận thực hiện \(2 N M^2\) phép toán FLOP nhưng chỉ đọc/ghi lượng dữ liệu bậc \(\Theta(NM + M^2)\) byte. Khi \(N\) và \(M\) đủ lớn, chia ô (register & L1/L2 cache tiling) trong OpenBLAS/MKL tái sử dụng mỗi byte nạp từ DRAM qua hàng trăm phép tính, đẩy \(\text{AI} = \Theta\big(\frac{NM}{N+M}\big)\) tiến sát vùng giới hạn tính toán (
compute-bound) gần đỉnh Roofline của CPU!
Cơ chế Khóa Trình thông dịch Toàn cục (CPython GIL)#
Trong CPython tiêu chuẩn (3.12 mặc định), Global Interpreter Lock (GIL) là khóa mutex toàn tiến trình bảo vệ ob_refcnt và trạng thái bộ cấp phát heap. Nếu dùng threading.Thread để chạy vòng lặp tính toán Python thuần, đa luồng không hề tăng tốc (thậm chí chậm hơn đơn luồng do tranh chấp khóa và chuyển ngữ cảnh OS) vì mỗi phép tính tạo PyFloatObject đều phải giữ GIL. Trái lại, các nhân C/Rust/Fortran của NumPy, BLAS, PyTorch và Polars ngay sau khi kiểm tra hợp lệ header sẽ giải phóng GIL bằng macro Py_BEGIN_ALLOW_THREADS / NPY_BEGIN_ALLOW_THREADS để thao tác thuần túy trên con trỏ char *data. Nhờ đó, OpenBLAS/MKL hay Rayon thực thi song song đa nhân thực sự trong cùng một tiến trình Python mà không tốn chi phí tuần tự hóa IPC của multiprocessing.
1.4 Lý thuyết Khai phá Tập phổ biến & Đại số Các Thước đo Luật kết hợp (Pattern Mining, FP-Growth & Interestingness)#
Không gian Tổ hợp Dàn Tập hợp (Itemset Lattice Combinatorics)#
Xét tập danh mục hữu hạn \(\mathcal{I} = \{i_1, i_2, \dots, i_M\}\) gồm \(M = \lvert\mathcal{I}\rvert\) mặt hàng (SKUs) sắp theo thứ tự toàn phần chuẩn \(\prec\). Cơ sở dữ liệu giao dịch \(\mathcal{D} = \{T_1, \dots, T_N\}\) gồm \(N = \lvert\mathcal{D}\rvert\) giỏ hàng \(T_t \subseteq \mathcal{I}\), tương đương ma trận liên thuộc nhị phân thưa \(\mathbf{B} \in \{0, 1\}^{N \times M}\) với \(B_{t,j} = \mathbb{I}[i_j \in T_t]\).
- Không gian Tập mặt hàng (
Itemset Lattice): Tạo thành dàn Boolean \((2^{\mathcal{I}}, \subseteq)\) có kích thước \(2^M\) (\(2^M - 1\) tập khác rỗng). - Không gian Luật kết hợp (
Association Rules): Một luật có dạng \(A \to B\) với \(A, B \subseteq \mathcal{I}\), \(A \neq \emptyset\), \(B \neq \emptyset\), \(A \cap B = \emptyset\). Phân hoạch \(\mathcal{I}\) thành 3 tập rời nhau \((A, B, \mathcal{I} \setminus (A \cup B))\) cho \(3^M\) khả năng; trừ đi hai trường hợp \(A = \emptyset\) (\(2^M\)) và \(B = \emptyset\) (\(2^M\)), rồi cộng lại trường hợp giao \((\emptyset, \emptyset)\) bị trừ hai lần cho tổng số luật không tầm thường chính xác:
Với danh mục chỉ \(M = 1{,}000\) SKUs, \(2^{1000} \approx 1.07 \times 10^{301}\) tập hợp và \(3^{1000} \approx 1.32 \times 10^{477}\) luật—khiến vét cạn hoàn toàn bất khả thi về mặt vật lý.
Thuật toán Apriori (Agrawal & Srikant, 1994)#
Với tập \(X \subseteq \mathcal{I}\), định nghĩa số đếm hỗ trợ (support count) \(\sigma(X) := \lvert\{t \in \{1, \dots, N\} : X \subseteq T_t\}\rvert\) và hỗ trợ tương đối \(\operatorname{supp}(X) := \sigma(X) / N \in [0, 1]\).
Định lý (Anti-Monotonicity / Downward Closure — Tính đóng hướng xuống):
Với mọi \(A, B \subseteq \mathcal{I}\), nếu \(A \subseteq B\) thì \(\sigma(B) \le \sigma(A)\) và \(\operatorname{supp}(B) \le \operatorname{supp}(A)\).
Chứng minh: Đặt \(\mathcal{T}(X) := \{t \in \{1, \dots, N\} : X \subseteq T_t\}\). Với mọi giao dịch \(t \in \mathcal{T}(B)\), theo tính bắc cầu của phép chứa tập hợp ta có \(A \subseteq B \subseteq T_t \implies A \subseteq T_t \implies t \in \mathcal{T}(A)\). Do đó \(\mathcal{T}(B) \subseteq \mathcal{T}(A)\), suy ra \(\sigma(B) = \lvert\mathcal{T}(B)\rvert \le \lvert\mathcal{T}(A)\rvert = \sigma(A)\). Chia hai vế cho \(N > 0\) cho \(\operatorname{supp}(B) \le \operatorname{supp}(A)\). \(\blacksquare\)
Hệ quả cắt tỉa (Phản đảo): Nếu \(\operatorname{supp}(A) < \theta_{\text{supp}}\) (hay \(\sigma(A) < \sigma_{\min} = \lceil \theta_{\text{supp}} N \rceil\)) thì mọi tập cha \(B \supseteq A\) đều không phổ biến và có thể bị loại bỏ ngay lập tức.
Cơ chế Sinh Ứng viên theo Tầng (\(C_k\) từ \(L_{k-1}\)): Giả sử phần tử trong tập luôn được sắp theo thứ tự chuẩn \(x_1 \prec x_2 \prec \dots \prec x_k\):
- Lượt 1: Quét \(\mathcal{D}\) tìm \(L_1 = \{\{i\} : \sigma(\{i\}) \ge \sigma_{\min}\}\).
- Bước Nối (
Join Step\(L_{k-1} \bowtie L_{k-1}\)): Ghép cặp \(p, q \in L_{k-1}\) nếu chúng trùng nhau đúng \((k-2)\) phần tử tiền tố đầu và \(p_{k-1} \prec q_{k-1}\), sinh ứng viên \(c = (p_1, \dots, p_{k-2}, p_{k-1}, q_{k-1})\) (tránh sinh trùng lặp). - Bước Cắt tỉa (
Prune Step): Kiểm tra \(k-2\) tập con cỡ \((k-1)\) còn lại của \(c\); nếu bất kỳ tập con nào \(\notin L_{k-1}\), loại bỏ \(c\) trước khi đụng tới \(\mathcal{D}\). - Bước Đếm hỗ trợ: Quét lại toàn bộ \(\mathcal{D}\), dò cây băm (hash tree) chứa \(C_k\) để cập nhật số đếm và giữ \(L_k = \{c \in C_k : \sigma(c) \ge \sigma_{\min}\}\).
Ba Chế độ Thất bại của Apriori trên Dữ liệu Bán lẻ Dày / Hỗ trợ thấp:
- Quét Toàn bộ Đĩa Lặp lại (\(K_{\max} + 1\) lần): Khai phá mẫu dài \(K_{\max}\) đòi hỏi \(K_{\max}\) đến \(K_{\max} + 1\) lần đọc toàn bộ \(\mathcal{D}\), gây nghẽn I/O nghiêm trọng ở quy mô TB.
- Nút cổ chai Bậc hai tại \(C_2\): Nếu \(M_f = \lvert L_1\rvert = 10{,}000\) mặt hàng sống sót qua Lượt 1, Apriori buộc phải vật chất hóa và băm \(\lvert C_2\rvert = \binom{10{,}000}{2} = 49{,}995{,}000\) cặp ứng viên trong RAM dù \(>99\%\) có đồng xuất hiện gần bằng
0. - Bùng nổ Tổ hợp trên Mẫu Dày Dài: Nếu tồn tại một mẫu phổ biến dài \(l = 30\), Apriori bắt buộc phải sinh và đếm đủ \(\sum_{k=1}^{30} \binom{30}{k} = 2^{30} - 1 \approx 1.07 \times 10^9\) tập con qua 30 tầng.
Thuật toán FP-Growth (Han, Pei, & Yin, SIGMOD 2000)#
FP-Growth triệt tiêu hoàn toàn bước sinh ứng viên \(C_k\) và cố định số lần quét đĩa còn đúng 2 lần nhờ nén cây tiền tố (FP-Tree) và chia để trị (divide-and-conquer):
- Cấu trúc Dữ liệu Cốt lõi:
- Bảng Tiêu đề (
Header Table\(H\)): Lưu các mặt hàng phổ biến sắp xếp theo tần suất toàn cục giảm dần (f_list, phá hòa tất định theo thứ tự từ điển), số đếm toàn cục, và con trỏ đầu danh sách liên kếtnode_link. Việc đặt item phổ biến nhất lên sát gốc tối đa hóa sự chia sẻ nhánh tiền tố. - Cây Tiền tố (
FP-Tree): Gốcnull, mỗi nút lưu(item, count, parent, children, node_link), trong đónode_linkxâu chuỗi mọi nút cùng nhãnitemnằm trên các nhánh khác nhau về \(H\).
- Bảng Tiêu đề (
- Quét 1 & Quét 2 (Xây dựng Cây):
- Quét 1: Đếm mọi phần tử, giữ lại \(\sigma(i) \ge \sigma_{\min}\), lập
f_listgiảm dần. - Quét 2: Với mỗi giỏ \(T_t \in \mathcal{D}\), lọc các item phổ biến, sắp theo thứ tự
f_listthành \([p \mid P]\), rồi chèn đệ quy vàoroot(tăngcount += 1nếu nhánh đã tồn tại, hoặc tạo nút mớicount = 1và nối vào chuỗinode_linktrong \(H\)).
- Quét 1: Đếm mọi phần tử, giữ lại \(\sigma(i) \ge \sigma_{\min}\), lập
- Khai phá Đệ quy Từ dưới lên (
FP_growth(Tree, alpha)):- Đường tắt Đơn nhánh (
Single-Path Shortcut): NếuTreechỉ gồm một chuỗi thẳng không phân nhánh \(P\), phát sinh trực tiếp mọi tổ hợp khác rỗng \(\beta \subseteq P\) dưới dạng \(\beta \cup \alpha\) với số đếm \(\min_{v \in \beta} v.\text{count}\). - Chia để trị Đa nhánh (
Multi-Path): Duyệt từng mục \(a_i\) trong \(H\) theo thứ tự tăng dần (từ dưới lên):- Phát sinh tập phổ biến \(\beta = a_i \cup \alpha\) với số đếm bằng tổng
v.countdọc theo chuỗinode_linkcủa \(a_i\). - Trích xuất Cơ sở Mẫu Điều kiện (
Conditional Pattern Base\(B_\beta\)): Với mỗi nút \(v\) trênnode_linkcủa \(a_i\), đi ngược con trỏparentlên tới (không gồm)rootđể thu đường dẫn tiền tố, gán trọng số chính xác bằngv.count(tuyệt đối không dùng số đếm của nút tổ tiên!). - Dựng Cây Điều kiện (\(\text{Tree}_\beta\)): Cộng dồn tần suất trên các đường dẫn có trọng số trong \(B_\beta\), loại phần tử có tổng điều kiện \(< \sigma_{\min}\), sắp xếp giảm dần theo tần suất cục bộ và chèn vào \(\text{Tree}_\beta\); nếu khác rỗng thì gọi đệ quy
FP_growth(Tree_beta, beta).
- Phát sinh tập phổ biến \(\beta = a_i \cup \alpha\) với số đếm bằng tổng
- Đường tắt Đơn nhánh (
Ví dụ Truy vết Tay Toàn phần (\(N = 6\) Giao dịch, \(\sigma_{\min} = 2\), tức \(\theta_{\text{supp}} = 1/3\))#
Xét danh mục \(\mathcal{I} = \{a, b, c, d, e, f\}\) và cơ sở dữ liệu \(\mathcal{D}\) gồm 6 giỏ hàng:
tid |
Giỏ hàng thô \(T_t\) | Giỏ sau lọc & sắp theo f_list |
|---|---|---|
| \(T_1\) | \(\{a, b, c, e\}\) | \([b, a, c, e]\) |
| \(T_2\) | \(\{a, b, d\}\) | \([b, a, d]\) |
| \(T_3\) | \(\{b, c, e\}\) | \([b, c, e]\) |
| \(T_4\) | \(\{a, b, c, f\}\) | \([b, a, c]\) (loại \(f\)) |
| \(T_5\) | \(\{a, c, e\}\) | \([a, c, e]\) |
| \(T_6\) | \(\{b, d\}\) | \([b, d]\) |
- Kết quả Quét 1: \(\sigma(b)=5\), \(\sigma(a)=4\), \(\sigma(c)=4\), \(\sigma(e)=3\), \(\sigma(d)=2\), \(\sigma(f)=1 < 2\) (bị loại). Thứ tự
f_listchuẩn (giảm dần tần suất, phá hòa chữ cái): \([b:5,\; a:4,\; c:4,\; e:3,\; d:2]\). - Cấu trúc Cây FP-Tree Toàn cục sau Quét 2:
root (null)- \(\to\)
b:5- \(\to\)
a:3(từ \(T_1, T_2, T_4\)) \(\to\)c:2(từ \(T_1, T_4\)) \(\to\)e:1(từ \(T_1\)); nhánh rẽ tạia:3\(\to\)d:1(từ \(T_2\)) - \(\to\)
c:1(từ \(T_3\)) \(\to\)e:1(từ \(T_3\)) - \(\to\)
d:1(từ \(T_6\))
- \(\to\)
- \(\to\)
a:1(từ \(T_5\)) \(\to\)c:1\(\to\)e:1
- \(\to\)
- Truy vết Đệ quy Từ dưới lên (
d\(\to\)e\(\to\)c\(\to\)a\(\to\)b):
| Mục hậu tố \(a_i\) | Tập phát sinh gốc | Cơ sở Mẫu Điều kiện (gán trọng số \(v.\text{count}\)) | Tổng điều kiện (\(\ge 2\) giữ lại) | Cây Điều kiện (\(\text{Tree}_\beta\)) & Tập phổ biến thu được |
|---|---|---|---|---|
d (\(\sigma=2\)) |
{d}: 2 |
{(b, a): 1, (b): 1} |
b: 2, ~~a: 1~~ |
Đường đơn null -> b:2 \(\implies\) {b, d}: 2 |
e (\(\sigma=3\)) |
{e}: 3 |
{(b, a, c): 1, (b, c): 1, (a, c): 1} |
c: 3, b: 2, a: 2 |
Đa nhánh null -> c:3 -> {b:2 -> a:1, a:1}. Đệ quy trên [a, b, c]: a (\(1+1=2\)): {a, e}: 2, nền {(c,b):1, (c):1} \(\to\) c:2 \(\implies\) {c, a, e}: 2; b (\(2\)): {b, e}: 2, nền {(c):2} \(\to\) c:2 \(\implies\) {c, b, e}: 2; c (\(3\)): {c, e}: 3, nền \(\emptyset\) |
c (\(\sigma=4\)) |
{c}: 4 |
{(b, a): 2, (b): 1, (a): 1} |
b: 3, a: 3 |
Đa nhánh null -> {b:3 -> a:2, a:1}. Đệ quy trên [a, b]: a (\(2+1=3\)): {a, c}: 3, nền {(b):2} \(\to\) b:2 \(\implies\) {b, a, c}: 2; b (\(3\)): {b, c}: 3, nền \(\emptyset\) |
a (\(\sigma=4\)) |
{a}: 4 |
{(b): 3} (nhánh \(T_5\) tiền tố rỗng) |
b: 3 |
Đường đơn null -> b:3 \(\implies\) {b, a}: 3 |
b (\(\sigma=5\)) |
{b}: 5 |
\(\emptyset\) | — | Kết thúc |
Kiểm chứng Toàn vẹn: Tổng cộng thu được đúng 15 tập phổ biến (5 tập cỡ 1, 7 tập cỡ 2, 3 tập cỡ 3) khớp 100% với vét cạn/Apriori mà sinh ra đúng 0 ứng viên.
So sánh Độ phức tạp: Apriori vs. FP-Growth#
Gọi \(N = \lvert\mathcal{D}\rvert\), \(M_f = \lvert L_1\rvert\), \(\bar{\ell}\) là số mục phổ biến trung bình mỗi giỏ, \(K_{\max}\) là độ dài tập phổ biến tối đa, và \(\lvert F\rvert = \sum_{k=1}^{K_{\max}} \lvert L_k\rvert\) là tổng số tập phổ biến đầu ra:
| Phương diện | Apriori (Agrawal & Srikant, 1994) | FP-Growth (Han, Pei, & Yin, 2000) |
|---|---|---|
| Số lần quét toàn bộ dữ liệu | \(K_{\max} + 1\) (hoặc \(K_{\max}\)) lần quét đĩa | Đúng \(2\) lần quét đĩa |
| Sinh tập ứng viên | Tạo \(\sum_{k=2}^{K_{\max}+1} \lvert C_k\rvert\) ứng viên tường minh (\(O(M_f^2)\) tại \(k=2\); tới \(O(2^{K_{\max}})\) với mẫu dài) | \(0\) ứng viên được sinh |
| Độ phức tạp Thời gian | \(O\!\left(\sum_{k=2}^{K_{\max}} \lvert L_{k-1}\rvert^2 k + N \sum_{k=1}^{K_{\max}} \binom{\bar{\ell}}{k}\right)\) | Dựng cây: \(O(N \bar{\ell} \log M_f)\). Khai phá nhạy đầu ra, nhanh hơn nhiều bậc độ lớn trên mẫu dày nhờ nén tiền tố & đường tắt đơn nhánh; trường hợp xấu nhất vẫn là \(O(2^{M_f})\) (bài toán đếm #P-hard). |
| Độ phức tạp Không gian | \(O\!\left(\max_k (\lvert C_k\rvert + \lvert L_k\rvert)\right)\); dễ tràn RAM tại \(C_2\) hoặc đỉnh \(C_k\) ngay cả khi \(\lvert F\rvert\) nhỏ | \(O(N \bar{\ell})\) xấu nhất, thực tế nhỏ hơn nhiều nhờ chia sẻ tiền tố + ngăn xếp đệ quy sâu \(\le M_f\). Nếu \(\mathcal{D}\) cực lớn và siêu thưa, cây đơn khối có thể tràn RAM (khắc phục bằng FP-Growth phân mảnh hoặc Eclat danh sách dọc). |
Tám Thước đo Đánh giá Luật Kết hợp (8 Objective Interestingness Measures)#
Với luật \(A \to B\) (\(A, B \neq \emptyset, A \cap B = \emptyset\)), ký hiệu \(p_A = \operatorname{supp}(A)\), \(p_B = \operatorname{supp}(B)\), \(p_{AB} = \operatorname{supp}(A \cup B)\). Bất đẳng thức Fréchet–Hoeffding luôn ràng buộc:
Một thước đo \(M(A, B)\) có tính bất biến giao dịch rỗng (Null-Invariant) nếu giá trị của nó không đổi khi cộng thêm tùy ý số lượng giao dịch không chứa cả \(A\) lẫn \(B\) (làm tăng \(N\) trong khi \(\sigma(A), \sigma(B), \sigma(AB)\) giữ nguyên) (Tan, Kumar, & Srivastava, 2004; Wu, Chen, & Han, 2010).
| Thước đo | Công thức Toán học Chính xác | Miền giá trị | Giá trị Độc lập | Đối xứng? (\(A \leftrightarrow B\)) | Null-Invariant? | Bẫy Biên & Điểm Mù Thực tế |
|---|---|---|---|---|---|---|
| Support | \(\operatorname{supp}(A \cup B) = \frac{\sigma(A \cup B)}{N} = p_{AB}\) | \([0, \min(p_A, p_B)] \subseteq [0,1]\) | \(p_A p_B\) | Có | Không (\(\propto 1/N\)) | Ngưỡng cao bỏ sót cặp ngách sinh lời cao (rare-item dilemma); ngưỡng thấp gây bùng nổ tổ hợp. |
| Confidence (Agrawal et al., 1993) | \(\operatorname{conf}(A \to B) = \hat{P}(B \mid A) = \frac{p_{AB}}{p_A} = \frac{\sigma(A \cup B)}{\sigma(A)}\) | \([0, 1]\) | \(p_B\) | Không | Có | Không xác định (\(0/0\)) nếu \(\sigma(A)=0\). Bẫy tần suất nền: Nếu \(B\) phổ biến (\(p_B=0.85\)), \(\operatorname{conf}=0.70\) trông cao dù tương quan thực chất âm (\(p_{AB} < p_A p_B\)). |
| Lift (Brin et al., 1997) | \(\operatorname{lift}(A \to B) = \frac{\operatorname{conf}(A \to B)}{p_B} = \frac{p_{AB}}{p_A p_B}\) | \(\big[0, \min(\frac{1}{p_A}, \frac{1}{p_B})\big] \subseteq [0, \infty)\) | \(1\) | Có | Không (\(\propto N\)) | Không xác định nếu \(p_A=0\) hoặc \(p_B=0\). Ảo giác đuôi dài: 1 cặp hiếm xuất hiện cùng nhau trong \(10^6\) giỏ tạo \(\text{lift}=10^6\). Nén toàn bộ tương quan âm vào \([0, 1)\). |
| Leverage (Piatetsky-Shapiro, 1991) | \(\operatorname{lev}(A \to B) = p_{AB} - p_A p_B\) | \([-0.25, 0.25]\) | \(0\) | Có | Không (\(\approx \propto 1/N\)) | Đạt \(\pm 0.25\) tại \(p_A=p_B=0.5\). Sụp đổ về \(0\) với mặt hàng hiếm, che khuất hoàn toàn các cặp thay thế hoặc phụ thuộc ngách. |
| Conviction (Brin et al., 1997) | \(\operatorname{conv}(A \to B) = \frac{1 - p_B}{1 - \operatorname{conf}(A \to B)} = \frac{p_A(1 - p_B)}{p_A - p_{AB}}\) | \([1 - p_B, \infty] \subseteq [0, \infty]\) | \(1\) | Không | Không (qua \(1-p_B\)) | Bằng \(+\infty\) khi \(\operatorname{conf}=1, p_B < 1\) (luật không ngoại lệ); bất định (\(0/0\)) nếu \(p_B=1, \operatorname{conf}=1\). |
| Zhang's Metric (Zhang, 2000; Tan et al., 2004) | \(\operatorname{Zhang}(A \to B) = \frac{p_{AB} - p_A p_B}{\max\big(p_{AB}(1 - p_A),\; p_A(p_B - p_{AB})\big)}\) | \([-1, 1]\) | \(0\) | Không (dấu đối xứng; độ lớn bất đối xứng khi \(p_A \neq p_B\)) | Không | Bất định nếu \(p_A \in \{0,1\}\) hoặc \(p_B = 0\). Đạt \(+1\) iff \(P(B \mid \neg A)=0\); đạt \(-1\) iff \(P(B \mid A)=0\) (triệt tiêu hoàn toàn). |
| Kulczynski (Wu, Chen, & Han, 2010) | \(\operatorname{Kulc}(A, B) = \frac{1}{2}\left(\frac{\sigma(A \cup B)}{\sigma(A)} + \frac{\sigma(A \cup B)}{\sigma(B)}\right)\) | \([0, 1]\) | \(\frac{p_A + p_B}{2}\) | Có | Có | Bất định nếu \(\sigma(A)=0\) hoặc \(\sigma(B)=0\). Đứng một mình không phát hiện được độ lệch giữa hàng chủ đạo và hàng phụ kiện; phải ghép với \(IR\). |
| Imbalance Ratio (\(IR\)) (Wu, Chen, & Han, 2010) | \(\operatorname{IR}(A, B) = \frac{\lvert\sigma(A) - \sigma(B)\rvert}{\sigma(A) + \sigma(B) - \sigma(A \cup B)} = \frac{\lvert p_A - p_B\rvert}{p_A + p_B - p_{AB}}\) | \([0, 1]\) | \(\frac{\lvert p_A - p_B\rvert}{p_A + p_B - p_A p_B}\) | Có | Có | \(IR=0\) iff \(\sigma(A)=\sigma(B)\) (cân bằng); \(IR \to 1\) khi tỷ số phổ biến lệch cực đoan (vd. phụ kiện \(\leftrightarrow\) hàng phổ thông). |
Định lý & Chứng minh Đầy đủ: Tính Bị chặn và Phân tách Chế độ của Thước đo Zhang#
Định lý (Boundedness & Regime Separation of Zhang's Metric):
Giả sử \(p_A \in (0, 1)\) và \(p_B \in (0, 1]\). Đặt \(\alpha := \hat{P}(B \mid A) = \frac{p_{AB}}{p_A} \in [0, 1]\) và \(\beta := \hat{P}(B \mid \neg A) = \frac{p_B - p_{AB}}{1 - p_A} \in [0, 1]\). Khi đó:
- \(\operatorname{Zhang}(A \to B) = \dfrac{\alpha - \beta}{\max(\alpha, \beta)}\) với mọi trường hợp \(\max(\alpha, \beta) > 0\).
- \(\operatorname{Zhang}(A \to B) \in [-1, 1]\).
- \(\operatorname{Zhang}(A \to B)\) phân tách rành mạch liên kết dương (bổ trợ), độc lập thống kê (\(0\)), và liên kết âm / loại trừ lẫn nhau (thay thế).
Chứng minh:
Bước 1 (Đồng nhất thức Xác suất Có điều kiện): Khai triển hiệu \(\alpha - \beta\):
Tương tự, đưa thừa số dương \(p_A(1 - p_A) > 0\) ra khỏi \(\max(\alpha, \beta)\):
Chia tử số cho mẫu số sẽ triệt tiêu thừa số dương \(p_A(1 - p_A)\):
Bước 2 (Kiểm chứng Khoảng \([-1, 1]\) trên Ba Chế độ): Vì \(p_B > 0\) bảo đảm \(\max(\alpha, \beta) > 0\):
- Liên kết Dương / Sản phẩm Bổ trợ (\(\alpha > \beta \iff p_{AB} > p_A p_B\)): Khi đó \(\max(\alpha, \beta) = \alpha > 0\), nên:
\[\operatorname{Zhang}(A \to B) = \frac{\alpha - \beta}{\alpha} = 1 - \frac{\beta}{\alpha} \in (0, 1],\]do \(0 \le \beta < \alpha \implies 0 \le \beta / \alpha < 1\). Đạt \(+1\) khi và chỉ khi \(\beta = \hat{P}(B \mid \neg A) = 0\) (tức \(B\) chưa từng xuất hiện nếu vắng mặt \(A\)).
- Độc lập Thống kê (\(\alpha = \beta \iff p_{AB} = p_A p_B\)): Tử số bằng \(0\) còn mẫu số dương, nên \(\operatorname{Zhang}(A \to B) = 0\).
- Liên kết Âm / Sản phẩm Thay thế (\(\alpha < \beta \iff p_{AB} < p_A p_B\)): Khi đó \(\max(\alpha, \beta) = \beta > 0\), nên:
\[\operatorname{Zhang}(A \to B) = \frac{\alpha - \beta}{\beta} = \frac{\alpha}{\beta} - 1 \in [-1, 0),\]do \(0 \le \alpha < \beta \implies 0 \le \alpha / \beta < 1\). Đạt \(-1\) khi và chỉ khi \(\alpha = \hat{P}(B \mid A) = 0\) (tức \(p_{AB} = 0\) trong khi \(p_B > 0\): \(A\) và \(B\) loại trừ lẫn nhau hoàn toàn). \(\blacksquare\)
Kiểm chứng Số trên Cơ sở Dữ liệu Mẫu (\(N = 6\)):
- Luật dương \(\{d\} \to \{b\}\) (\(p_d = 1/3\), \(p_b = 5/6\), \(p_{bd} = 1/3\)):
\(\operatorname{supp} = 0.333\); \(\operatorname{conf}(d \to b) = 1.000\); \(\operatorname{lift} = 1.200\); \(\operatorname{lev} = \frac{1}{3} - \frac{5}{18} = \frac{1}{18} \approx 0.056\); \(\operatorname{conv} = +\infty\); \(\operatorname{Zhang}(d \to b) = \frac{1/18}{\max(2/9, 1/6)} = \mathbf{0.250}\); \(\operatorname{Kulc} = \frac{1}{2}(1.0 + 0.4) = \mathbf{0.700}\); \(\operatorname{IR} = \frac{\lvert 2 - 5\rvert}{2 + 5 - 2} = \mathbf{0.600}\) (bộc lộ độ lệch phổ biến giữa phụ kiện \(d\) và mặt hàng chủ đạo \(b\)). - Cặp thay thế loại trừ lẫn nhau \(\{d\}\) và \(\{e\}\) (\(p_d = 1/3\), \(p_e = 1/2\), \(p_{de} = 0\)):
\(\operatorname{supp} = 0\); \(\operatorname{conf} = 0\); \(\operatorname{lift} = 0\); \(\operatorname{lev} = -1/6 \approx -0.167\); \(\operatorname{conv} = 0.500\); \(\operatorname{Zhang}(d \to e) = \frac{-1/6}{\max(0,\; (1/3)(1/2))} = \mathbf{-1.000}\).
Trên dữ liệu bán lẻ thưa thực tế, Leverage sụp đổ về \(-p_A p_B = -0.0004\) khi hai thương hiệu viên nén espresso cạnh tranh có \(p_A = p_B = 0.02\) và \(p_{AB} = 0\) (lẫn vào nhiễu), trong khi \(\operatorname{Zhang} = -1.0\) lập tức phát tín hiệu thay thế tuyệt đối! Đồng thời, việc kết hợp bộ đôi null-invariant Kulc + IR (Wu, Chen, & Han, 2010) giúp loại bỏ ảnh hưởng của hàng triệu giao dịch rỗng mà vẫn phân biệt được cặp đồng mua cân xứng (Kulc cao, IR thấp) với cặp lệch (Kulc cao, IR cao).
Trụ cột 2 — Kiến trúc Hệ thống 2026, Suy diễn Thống kê & Cầu nối Neural/Generative (Production Architecture, 2026 Data Engines & Advanced Pattern Mining)#
2.1 Kiến trúc Bộ nhớ Cột Apache Arrow & Công cụ Xử lý Dữ liệu 2026 (Arrow, Polars 2.0, DuckDB 1.5, Pandas 3.0, Python 3.14t–3.15t, uv)#
Định dạng Bộ nhớ Cột Apache Arrow (Format v1.4+ / PyArrow v19–v26)#
Trong khi NumPy tối ưu hóa mảng số đồng nhất thuần túy, dữ liệu giao dịch bán lẻ thực tế chứa hỗn hợp chuỗi ký tự độ dài biến thiên (SKU, mô tả), giá trị khuyết (null), và danh sách lồng nhau (giỏ hàng). Apache Arrow định nghĩa chuẩn bộ nhớ cột độc lập ngôn ngữ, căn chỉnh 8 B hoặc 64 B để chạy SIMD và trao đổi dữ liệu zero-copy xuyên ranh giới Python–Rust–C++–GPU:
- Bitmap Hợp lệ (
Validity / Null Bitmap— Buffer 0):
Đóng gói 1 bit mỗi phần tử theo thứ tự LSB: bit(i % 8)của bytefloor(i / 8)bằng1nếu phần tử \(i\) hợp lệ và0nếu lànullcấu trúc (được lược bỏ thànhnullptrvới0 Bchi phí khinull_count == 0).
Tách biệt ngữ nghĩa sống còn (nullvs. IEEE-754NaN): Arrow tách hẳn trạng thái khuyết dữ liệu (bit hợp lệ0) khỏi giá trị toán học bất định (NaNmang bit hợp lệ1trong mảngfloat64). Nhờ vậy, một cộtint64chứatransaction_idhayquantitycó giá trịNULLvẫn giữ nguyên kiểu nguyên64-bitthay vì bị ép kiểu âm thầm lênfloat64(gây mất độ chính xác số học trên \(2^{53}\)!). - Bộ đệm Kiểu cố định (
Fixed-Width Primitive Buffers— Buffer 1):
Lưu liên tụcint8–int64,uint8–uint64,float16/32/64,decimal128/256để chạy trực tiếp trên thanh ghi AVX2/AVX-512/NEON. -
Chuỗi & Danh sách Thế hệ 2024–2026 (
StringView,BinaryView,ListView):
Kiểuutf8truyền thống dùng mảng offsetint32[N+1]trỏ vào một bộ đệm byte ghép nối khổng lồ—mọi phép lọc/nối chuỗi đều gây cache miss trên heap và cắt lát mảng buộc phải viết lại toàn bộ offset. Lấy cảm hứng từ kiến trúc Velox/Umbra (German-style strings),StringView(Utf8View) (ổn định toàn diện trên PyArrow compute kernels đến v25.0.0 tháng 7/2026, chuẩn mặc định trongpolars-arrowvà DuckDB) thay thế bằng mảng cố định các cấu trúc16 Bview cộng với các bộ đệm dữ liệu đa biến (variadic Buffers \(2, 3, \dots\)):- Chuỗi ngắn (\(\text{len} \le 12\text{ B}\) — Inlined): Byte
0–3lưu độ dàiint32; byte4–15nhúng trực tiếp chuỗi UTF-8 (đệm số 0). Các mã SKU ngắn, mã tiền tệ, nhãn danh mục được so sánh ngay trong thanh ghi mà không bao giờ giải tham chiếu heap! - Chuỗi dài (\(\text{len} > 12\text{ B}\) — Out-of-Line with Prefix): Byte
0–3lưu độ dàiint32; byte4–7lưu 4 byte tiền tố nội tuyến (cho phép SIMD loại bỏ nhanh các chuỗi không khớp khi lọc/nối mà không chạm vùng đệm dữ liệu); byte8–11lưuint32chỉ số bộ đệmbuf_idx; byte12–15lưuint32độ dờioffset. ListView&LargeListView: Tách rời hai mảngoffsetsvàsizes, cho phép cắt lát, đảo thứ tự, và tái sử dụng các danh sách con giỏ hàng mà không cần sao chép vùng nhớ.
- Chuỗi ngắn (\(\text{len} \le 12\text{ B}\) — Inlined): Byte
Apache Arrow StringView (16-Byte View Entry) vs. Legacy Utf8
==============================================================
Legacy Utf8:
[Validity Bitmap] + [Offsets: int32[N+1]] ---> [Contiguous Heap Bytes] (cache miss on compare)
StringView (Len <= 12 bytes -- Inlined):
| 0..3: len (int32) | 4..15: inline UTF-8 bytes (0-padded) | <-- Zero heap dereference
StringView (Len > 12 bytes -- Out-of-Line with 4B Prefix):
| 0..3: len | 4..7: 4B prefix | 8..11: buf_idx | 12..15: offset | ---> [Variadic Data Buf_k]
- Mã hóa Nén Gốc (
Dictionary Encoding&Run-End Encoding — REE):
Dictionary Encoding lưu mảng chỉ số nguyên dày trỏ vào từ điển giá trị duy nhất (tối ưu cho cột độ phân giải thấp như mã cửa hàng, ngành hàng). Run-End Encoding (REE, mã C+r) lưu cặp mảng conrun_ends(chỉ số kết thúc lũy tích mỗi chuỗi đồng nhất) vàvalues, hỗ trợ truy cập ngẫu nhiên \(O(\log R)\) bằng tìm kiếm nhị phân trên \(R\) đoạn lặp và nén cực mạnh các nhật ký giao dịch đã sắp theo ngày/cửa hàng. - Zero-Copy IPC & Giao thức
Arrow PyCapsule:
Arrow IPC (Feather v2/mmap) ánh xạ trực tiếp từ đĩa vào RAM ở độ phức tạp \(O(1)\). Ở tầng Python, Arrow PyCapsule Interface chuẩn hóa trao đổi zero-copy mà không ép các thư viện phải phụ thuộc vàopyarrowlúc biên dịch hay truyền con trỏ thôuintptr_tdễ rò rỉ bộ nhớ khi gặp ngoại lệ. Mọi đối tượng tương thích chỉ cần triển khai các phương thức chuẩn trả vềPyCapsulegắn hàm hủy C an toàn:__arrow_c_schema__,__arrow_c_array__(requested_schema=None),__arrow_c_stream__(requested_schema=None)(cùng biến thể GPU__arrow_c_device_*__), cho phép thương lượng lược đồ (Utf8\(\leftrightarrow\)StringView) ngay tại biên xuất giữa Polars, DuckDB và PyTorch DataLoader.
Nội bộ Công cụ Truy vấn & Ma trận So sánh 2026 (Polars 2.0, DuckDB 1.4 LTS / 1.5, Pandas 3.0)#
- Polars 2.0 (phát hành 06/10/2026): Xây dựng bằng Rust trên
polars-arrow, biên dịch biểu thức khai báo (LazyFrame) thành DAG vật lý qua Bộ tối ưu Truy vấn (lf.explain()): Đẩy lọc xuống tầng quét (Predicate Pushdown vào thống kê min/max/bloom của Parquet), Cắt cột ngược (Projection Pushdown), Giới hạn lát (Slice Pushdown), Loại bỏ nhánh con chung lồng nhau (Nested Common Subplan Elimination — CSE), và rút gọn biểu thức. Kết hợp Morsel-Driven Parallelism (Leis et al., SIGMOD 2014), Polars giải phóng GIL ngay khi gọi.collect(), đẩy các khối nhỏ vừa khít L1/L2 cache (morsels) qua nhân hợp nhất (fused vectorized loops) trên toàn bộ lõi CPU. Đặc biệt từ Polars 2.0, công cụ streaming tràn đĩa (out-of-core spill-to-disk) trở thành backend mặc định cho bảng băm gom nhóm, nối và sắp xếp vượt quá dung lượng RAM. (Lưu ý tất định: Thực thi song song theo morsel không bảo toàn thứ tự dòng đầu vào saujoin,group_by,unpivottrừ khi bậtmaintain_order=Truehoặc gọi.sort()tường minh). - DuckDB 1.4 LTS (09/2025) / 1.5 (03/2026): Cơ sở dữ liệu phân tích nhúng trong tiến trình (Raasveldt & Mühleisen, SIGMOD 2019) xử lý theo vector cố định
STANDARD_VECTOR_SIZE = 2048dòng, tối ưu chi phí theo đồ thị đường ống (pipeline breakers) và hỗ trợ định dạng lakehouseDuckLake,VARIANT, mã hóa gốc (1.4 LTS), cùng luồng Arrow zero-copy qua__arrow_c_stream__. - Pandas 2.x \(\to\) Pandas 3.0 (phát hành 21/01/2026): Bước nhảy kiến trúc quan trọng với ba thay đổi phá vỡ thói quen cũ: (1) Copy-on-Write (CoW) bắt buộc toàn cục (không thể tắt, loại bỏ hoàn toàn
SettingWithCopyWarningvà vô hiệu hóa gán dây chuyềndf[col][mask] = valqua cơ chế sao chép lười khi ghi); (2) Kiểustrmặc định dựa trên PyArrow thay thế mảngobjectcho dữ liệu chữ (nhưng giữ sentinelnp.nancho giá trị thiếu để tương thích ngữ nghĩa Pandas); (3) Độ phân giải thời gian không bắt buộc[ns]([us]/[s]/[ms], tránh tràn mốc năm2262) và biểu thứcpd.col(). Tuy vậy, Pandas vẫn là công cụ eager thiếu bộ lập kế hoạch DAG toàn cục (CSE/pushdown) và chủ yếu chạy đơn luồng ở các tác vụ gắn kết Python.
| Phương diện | Pandas 3.0 (01/2026) | Polars 2.0 (10/2026) | DuckDB 1.4 LTS / 1.5 (2025–2026) |
|---|---|---|---|
| Mô hình Thực thi | Eager (thao tác khối cột/dòng tuần tự) | Lazy DAG + Eager; Streaming mặc định | SQL Quan hệ Cost-Based Optimizer + Vector hóa |
| Bố cục Bộ nhớ | BlockManager + NumPy / PyArrow str |
polars-arrow gốc (Utf8View, pl.Map) |
Lưu trữ cột nén + vector 2048 phần tử |
| Đa luồng / GIL | Chủ yếu đơn luồng (hạn chế ở nhân NumPy/Arrow) | Morsel-driven Rust thread pool (đa lõi, không GIL) | Morsel-driven C++ thread pool (đa lõi, không GIL) |
Vượt RAM (Out-of-Core) |
Hạn chế / chia khúc thủ công | Tràn đĩa gốc (spill-to-disk) mặc định (Polars 2.0) |
Buffer Manager gốc + tràn đĩa tạm |
| Giao tiếp Zero-Copy | Cột str PyArrow / xuất Arrow |
__arrow_c_stream__ / PyCapsule |
__arrow_c_stream__ / PyCapsule |
Vai trò chuẩn trong T1-P1 |
EDA cỡ nhỏ/trung bình, tương thích mã cũ | Chuẩn bị giỏ hàng, ETL, kỹ thuật đặc trưng tốc độ cao | Nối đa bảng phức tạp, SQL cửa sổ, truy vấn Parquet/DuckLake |
Tiến hóa CPython 3.13–3.15 (Free-Threading & abi3t) và Hệ sinh thái uv / PEP 751#
- Python
3.13(10/2024): Mở đường với PEP 703 (bản thử nghiệm3.13t--disable-gildùng khóa từng đối tượng, đếm tham chiếu thiên vị chủ sở hữu biased reference counting, PEP 683 immortal objects, và bộ cấp phátmimallocan toàn đa luồng) cùng PEP 744 (Copy-and-Patch JIT thử nghiệm không cần LLVM). - Python
3.14(07/10/2025): PEP 779 chính thức đưa3.14tlên trạng thái hỗ trợ chính thức (officially supported), kích hoạt trình thông dịch thích nghi PEP 659 và hạ chi phí đơn luồng xuống chỉ ~5%. Bổ sung trình thông dịch gọi đuôi (tail-calling interpreter tăng tốc 3–5%), trình cài JIT opt-in (PYTHON_JIT=1), PEP 734 (concurrent.interpreters), PEP 750 (t-stringschống tiêm nhiễm SQL/HTML), và PEP 784 (compression.zstd). - Python
3.15(09/10/2026 — PEP 790): Ra mắt ABI Ổn định Không GIL (abi3t— PEPs 803 / 793 / 820) cho phép tác giả thư viện C/Rust (NumPy, PyArrow, Polars, PyTorch) phân phối một tệp wheel nhị phân duy nhất chạy được trên cả bản có GIL lẫn bảnt; JIT đạt ~7–8% tăng tốc trung bình nhân trên Linux x86-64 (~11–12% trên macOS AArch64); cùng PEP 810 (import lười tường minh giảm độ trễ khởi động CLI/ML) và PEP 799 (Tachyonsampling profiler). - Điểm tinh tế Kỹ thuật: Vì Polars, DuckDB và BLAS vốn đã giải phóng GIL trong Rust/C++, bản
3.14t/3.15tphát huy giá trị độc nhất khi điều phối đa luồng bằng Python thuần trên RAM dùng chung—chẳng hạn chạy song song hàng triệu phép kiểm định Fisher thuần Python, gọi UDF phức tạp, hoặc truy vấn Feature Store bất đồng bộ mà không phải nhân bản RAM hay tuần tự hóa IPC quamultiprocessing. - Công cụ
uv& Chuẩn Lockfile PEP 751 (pylock.toml): Viết bằng Rust (Astral),uvthay thếpip,virtualenv,pip-tools,pyenv, vàpoetrybằng bộ giải phụ thuộc PubGrub, bộ đệm toàn cục dùng hardlinks / CoW reflinks (tạo môi trường nhanh hơn 10–100\(\times\) và gần như 0 byte trùng lặp đĩa), tệp khóa đa nền tảnguv.lockkiểm tra SHA-256 (uv sync --locked), monorepo[tool.uv.workspace], bộ dựnguv_build, cài đặt cảuv python install 3.14t/3.15t, và xuất tương thích chuẩn PEP 751 (pylock.toml, thông qua 03/2025) (uv export --format pylock.toml).
Nguyên tắc Song hành Môi trường (Dual Runtime Scope): Giáo trình giảng dạy chuẩn SOTA 2026 (Python 3.12+/3.14t–3.15t, uv, Arrow StringView, Polars 2.0, DuckDB 1.5, Pandas 3.0). Tuy nhiên, để Lab 01 (mba_lab) chạy bền vững trên mọi máy chủ đánh giá tối giản (bao gồm các host Python 3.10+ chưa có uv hoặc polars, hoặc nơi cài sẵn scipy/sklearn cũ xung đột ABI _ARRAY_API với numpy 2.x), Lab 01 khai báo requires-python = ">=3.10", chỉ phụ thuộc vào numpy và pandas, không bao giờ import scipy/scikit-learn/mlxtend, tự cài đặt Fisher log-space bằng math.lgamma thuần Python, và giữ polars dưới dạng tùy chọn mở rộng (try: import polars ... except ImportError).
2.2 Khai phá Mẫu Có ý nghĩa Thống kê (SSPD) & Kiểm soát Đa kiểm định (Multiple Testing & Split-Sample Validation)#
Ba Nguyên nhân Ngưỡng Support/Confidence/Lift Sụp đổ trên Danh mục Đuôi dài#
Trên danh mục thương mại điện tử có phân phối Zipfian (\(M = \lvert\mathcal{I}\rvert \in [10^4, 10^7]\)), lọc luật theo ngưỡng kinh nghiệm thô tạo ra làn sóng sai lầm loại I (Type-I errors — phát hiện giả):
- Bùng nổ Đa kiểm định Tổ hợp (
Multiple Testing Explosion):
Tìm kiếm cặp cỡ 2 kiểm định \(m_2 = \binom{M}{2} = O(M^2)\) giả thuyết; bộ 3 kiểm định \(O(M^3)\). Với \(M = 50{,}000\) SKUs, \(m_2 \approx 1.25 \times 10^9\) cặp! Ngay cả ở ngưỡng p-value chưa hiệu chỉnh rất khắt khe \(\alpha = 0.001\), nhiễu ngẫu nhiên hoàn toàn dưới giả thuyết không (\(H_0\): độc lập) vẫn tạo ra \(1{,}250{,}000\) cặp báo động giả. - Ảo giác
LiftĐuôi dài (Long-Tail Lift Illusion):
Nếu hai mặt hàng cực hiếm đều chỉ xuất hiện \(\sigma(A) = 2\) và \(\sigma(B) = 3\) lần trong \(N = 1{,}000{,}000\) giỏ hàng, và tình cờ có đúng \(1\) người mua cả hai (\(\sigma(A \cup B) = 1\)), thì:\[\operatorname{lift}(A, B) = \frac{10^6 \times 1}{2 \times 3} = 166{,}666.7, \qquad \operatorname{conf}(A \to B) = 0.50.\]VìLiftkhông chuẩn hóa theo phương sai cỡ mẫu, các cặp nhiễu siêu hiếm lập tức chiếm trọn đỉnh bảng xếp hạng dù không hề có ý nghĩa thống kê (\(p > 0.05\)). - Bẫy Hệ quả Phổ biến (
Popular-Consequent Confidence Trap):
Với mặt hàng chủ đạo \(p_B = 0.60\), hầu hết mọi mặt hàng \(A\) bất kỳ đều có \(\operatorname{conf}(A \to B) \approx 0.60\), che lấp hoàn toàn việc \(\operatorname{lift} \le 1\).
Khai phá Mẫu Vững chắc Thống kê (SSPD), Tập Tự đủ (SSI) & Kiểm định Tách mẫu Thời gian (Split-Sample Holdout)#
Geoffrey I. Webb (2007, 2010) và Hämäläinen & Webb (2019) xây dựng lý thuyết Statistically Sound Pattern Discovery (SSPD) nhằm tách phụ thuộc hành vi thực sự khỏi nhiễu mẫu và dư thừa tổ hợp:
- Tập Tự đủ (
Self-Sufficient Itemsets — SSI, Webb 2010): Một tập \(Z\) có thể trông có ý nghĩa thống kê chỉ vì ghép một cặp phụ thuộc thực \(X \subset Z\) với một món "ăn theo" độc lập \(y\) (ví dụ \(\{\text{Máy Espresso}, \text{Hạt Cà phê}, \text{Nước suối}\}\)). Tập \(Z\) là tự đủ khi thỏa mãn đồng thời:- Tính sinh lợi / Phi dư thừa (
Productivity / Non-Redundancy): Với mọi phân hoạch nhị phân \((X, Y)\) thỏa \(X \cup Y = Z\), \(X \cap Y = \emptyset\), \(X, Y \neq \emptyset\), xác suất \(P(Z)\) vượt trội \(P(X)P(Y)\) một cách có ý nghĩa thống kê (hay bỏ bất kỳ điều kiện nào \(a \in X\) đều làm giảm đáng kể \(P(y \mid X)\)). - Không bị Giải thích bởi Tập cha (
Non-Explanation by Supersets): Đồng xuất hiện của \(Z\) không phải là hệ quả giả tạo của một tập cha cấu trúc nào khác (chặn nghịch lý Simpson hoặc nhóm thay thế). Thuật toánOPUS Miner(Webb & Vreeken, 2014) dùng nhánh-và-cận (branch-and-bound) khai phá trực tiếp Top-\(k\) SSI mà không cần liệt kê vét cạn như Apriori.
- Tính sinh lợi / Phi dư thừa (
- Xác thực Tách mẫu theo Thời gian (
Temporal Split-Sample Holdout Validation— Webb, 2007): Nếu vừa dùng tập \(\mathcal{D}\) để tìm kiếm qua không gian mũ \(2^M\) các tập phổ biến, vừa kiểm định p-value trên chính \(\mathcal{D}\), ta phạm lỗi thiên kiến hậu chọn lọc (post-selection overfitting bias) vì \(m_{\text{hyp}}\) thực chất là toàn bộ không gian đã tìm kiếm. Bằng cách chia nghiêm ngặt theo thời gian:- Khai phá các tập ứng viên bằng FP-Growth chỉ trên tập
train(\(t \le T_{\text{split}}\)); - Lọc ứng viên theo
min_confidencevà đóng băng danh sách luật chỉ trên tậptraintrước khi chuyển sang kiểm chứng, rồi kiểm định ý nghĩa thống kê chỉ trên tậpholdoutchưa từng thấy (\(t > T_{\text{split}}\)) để số giả thuyết \(m\) của BH-FDR/Holm không bị co rút sau khi đã nhìn vàoholdout, số giả thuyết kiểm định \(m_{\text{hyp}}\) được giới hạn chính xác bằng số ứng viên sống sót (hoặc dùng chặn bảo thủ \(\binom{M}{2}\) toàn danh mục) mà không bị nhiễm rò rỉ dữ liệu!
- Khai phá các tập ứng viên bằng FP-Growth chỉ trên tập
Kiểm định Chính xác Fisher Một phía & Tính toán Ổn định Số học Trong Không gian Log#
Với cặp/tập bất kỳ \((A, B)\) trên tập đánh giá gồm \(N\) giỏ hàng, lập bảng tiếp liên \(2 \times 2\):
| Giỏ chứa \(B\) | Giỏ không chứa \(B\) | Tổng hàng | |
|---|---|---|---|
| Giỏ chứa \(A\) | \(k = \sigma(A \cup B)\) | \(\sigma(A) - k\) | \(\sigma(A)\) |
| Giỏ không chứa \(A\) | \(\sigma(B) - k\) | \(N - \sigma(A) - \sigma(B) + k\) | \(N - \sigma(A)\) |
| Tổng cột | \(\sigma(B)\) | \(N - \sigma(B)\) | \(N\) |
Cố định các biên \(\sigma(A), \sigma(B), N\), dưới giả thuyết không \(H_0\) (\(A\) và \(B\) xuất hiện độc lập), số giao dịch đồng xuất hiện ngẫu nhiên \(X\) tuân theo phân phối Siêu bội (Hypergeometric Distribution):
Kiểm định bổ trợ dương (\(H_1\): tỷ số chênh \(> 1\)) sử dụng trị số \(p\) chính xác Fisher một phía đuôi phải (one-sided right-tail Fisher exact p-value):
Khác với phép xấp xỉ tiệm cận Pearson \(\chi^2\) hoặc \(G\)-test (vốn sai lệch nghiêm trọng khi tần suất kỳ vọng \(E_{11} = \sigma(A)\sigma(B)/N < 5\) — xảy ra liên tục ở đuôi dài bán lẻ), Fisher luôn chính xác tuyệt đối ở mọi cỡ mẫu.
Ba Bước Tính Toán Không Gian Log Chống Tràn Số (Overflow \(171!\) & Subnormal Underflow \(< 10^{-308}\)):
Tính giai thừa trực tiếp tràn float64 ngay tại \(171! \approx 1.24 \times 10^{309}\), còn tích xác suất tuyến tính dưới ngưỡng \(10^{-308}\) sẽ bị làm tròn về đúng 0.0 (khiến các cặp rất mạnh như máy in + mực in mất thứ tự xếp hạng khi hiệu chỉnh \(q\)-value!). Giải pháp chuẩn xác gồm:
- Neo điểm \(\ell(k)\) qua hàm Log-Gamma (
math.lgamma):\[\ln \binom{n}{r} = \ln\Gamma(n + 1) - \ln\Gamma(r + 1) - \ln\Gamma(n - r + 1), \qquad \ell(k) = \ln\binom{\sigma(A)}{k} + \ln\binom{N - \sigma(A)}{\sigma(B) - k} - \ln\binom{N}{\sigma(B)}.\] - Hệ thức Truy hồi Siêu bội \(O(1)\) mỗi bước: Không gọi lại
lgammatrong vòng lặp; chuyển từ \(x\) sang \(x+1\) bằng biểu thức log hiệu số đại số chính xác:\[\ell(x + 1) = \ell(x) + \ln(\sigma(A) - x) + \ln(\sigma(B) - x) - \ln(x + 1) - \ln(N - \sigma(A) - \sigma(B) + x + 1).\] - Cộng dồn
LogSumExp(LSE) & Lưu trữ \(\ln p_{\text{right}}\):\[\ln p_{\text{right}} = \ell_{\max} + \ln \sum_{x=k}^{x_{\max}} \exp\big(\ell(x) - \ell_{\max}\big), \qquad -\log_{10} p_{\text{right}} = -\frac{\ln p_{\text{right}}}{\ln 10}.\]Nhờ lưu \(\ln p_{\text{right}}\) (ví dụ-11500.0cho \(p \approx 10^{-5000}\)), thứ tự sắp xếp và bước hiệu chỉnh đa kiểm định bảo toàn độ chính xác tuyệt đối ngay cả khimath.exp(log_p_value)trả về0.0trên biểu diễn thập phânfloat64.
Ma trận Kiểm soát Đa kiểm định (Bonferroni, Holm-Bonferroni, BH-FDR, BY-FDR)#
Khi thực hiện \(m = m_{\text{hyp}}\) kiểm định tạo ra \(V\) báo động giả trong tổng số \(R\) giả thuyết bị bác bỏ:
| Phương pháp | Tiêu chuẩn Kiểm soát | Thuật toán Hiệu chỉnh | Đảm bảo Lý thuyết & Độ mạnh Thống kê (Power) |
|---|---|---|---|
| Bonferroni (1936) | \(\text{FWER} = \Pr(V \ge 1) \le \alpha\) | Bác bỏ nếu \(p_i \le \frac{\alpha}{m}\); \(p_{\text{adj}, i} = \min(1, m \cdot p_i)\) | An toàn dưới phụ thuộc bất kỳ, nhưng giết chết hầu hết phát hiện khi \(m \to 10^8\). |
| Holm–Bonferroni (1979) | \(\text{FWER} = \Pr(V \ge 1) \le \alpha\) | Sắp \(p_{(1)} \le \dots \le p_{(m)}\). Bước xuống (step-down): dừng tại \(j\) đầu tiên vi phạm \(p_{(j)} \le \frac{\alpha}{m - j + 1}\). \(p_{\text{adj},(j)} = \max_{i \le j}\min(1, (m-i+1)p_{(i)})\) | Mạnh hơn chặt Bonferroni mà không thêm giả định; vẫn quá khắt khe cho danh mục lớn. |
Benjamini–Hochberg (BH-FDR) (1995) |
\(\text{FDR} = \mathbb{E}\!\left[\frac{V}{\max(R, 1)}\right] \le \alpha\) | Sắp \(p_{(1)} \le \dots \le p_{(m)}\). Bước lên (step-up): tìm \(k^* = \max\{i : p_{(i)} \le \frac{i}{m}\alpha\}\), bác bỏ \(H_{(1)}, \dots, H_{(k^*)}\) | Kiểm soát FDR dưới độc lập & điều kiện phụ thuộc dương PRDS. |
Benjamini–Yekutieli (BY-FDR) (2001) |
\(\text{FDR} \le \alpha\) dưới phụ thuộc bất kỳ | Thay \(m\) trong BH bằng \(m \cdot H_m\), với \(H_m = \sum_{i=1}^{m} \frac{1}{i} \approx \ln m + \gamma\) | An toàn tuyệt đối ngay cả khi các cặp giỏ hàng có tương quan âm phức tạp. |
Tính \(q\)-value (BH-FDR) trong Không gian Log ở Độ phức tạp \(O(m \log m)\):
Sắp tăng dần theo \(\ln p_{(1)} \le \ln p_{(2)} \le \dots \le \ln p_{(m)}\), sau đó duyệt ngược để tính cực tiểu tích lũy ngược (reverse cumulative minimum):
với \(i = m-1, \dots, 1\), rồi ánh xạ về ban đầu và lấy \(q_i = \min(1.0, \exp(\ln q_i))\). Ở quy mô \(m = 10^7\) cặp và \(\alpha = 0.05\), Bonferroni đòi hỏi \(p_{(1)} \le 5 \times 10^{-9}\), trong khi nếu tồn tại \(10{,}000\) cặp liên kết thật (\(k^* = 10{,}000\)), BH-FDR chỉ đòi hỏi \(p_{(10{,}000)} \le \frac{10{,}000}{10^7} \times 0.05 = 5 \times 10^{-5}\)—một bước nhảy độ mạnh \(10{,}000\times\) trong khi vẫn khống chế tỷ lệ sai sót kỳ vọng \(\le 5\%\).
2.3 Khai phá Tập Hữu ích Cao (HUIM) & Mẫu Tuần tự (SPM / HUSPM)#
Khai phá nhị phân 0/1 coi một chiếc túi nilon $0.10 ngang hàng với một máy pha cà phê $2,500. Khai phá Tập Hữu ích Cao (High-Utility Itemset Mining — HUIM) tích hợp đồng thời số lượng nội tại \(\operatorname{qty}(i, T_t) \in \mathbb{N}\) và biên lợi nhuận đơn vị ngoại tại \(\pi_i \in \mathbb{R}\):
- Vì sao Apriori Thất bại: Hữu ích \(u(X)\) không có tính phản đơn điệu (
non-anti-monotonic): một tập cha \(Y \supset X\) có thể xuất hiện trong ít giỏ hơn nhưng cộng thêm mặt hàng biên lợi nhuận cao nên có thể đạt \(u(Y) > u(X)\) hoặc \(u(Y) < u(X)\). Cắt tỉa trực tiếp theo \(u(X)\) sẽ làm mất nghiệm tối ưu! -
Cận trên Đóng hướng xuống (
TWU& Định lýTWDC; Liu, Liao, & Choudhary, PAKDD 2005):
Định nghĩa Hữu ích Giao dịch (Transaction Utility) \(\operatorname{TU}(T_t) = \sum_{i \in T_t} u(i, T_t)\) và Hữu ích Gia quyền Giao dịch (Transaction-Weighted Utilization):\[\operatorname{TWU}(X) := \sum_{T_t \supseteq X,\, T_t \in \mathcal{D}} \operatorname{TU}(T_t).\]Định lý (
Transaction-Weighted Downward Closure — TWDC): Khi mọi biên lợi nhuận không âm (\(\pi_i \ge 0\)), với mọi \(X \subseteq Y \subseteq \mathcal{I}\) ta luôn có:\[u(X) \le \operatorname{TWU}(X) \qquad \text{và} \qquad \operatorname{TWU}(Y) \le \operatorname{TWU}(X).\]Chứng minh: (i) Với mọi \(T_t \supseteq X\) và \(\pi_i \ge 0\), \(u(X, T_t) = \sum_{i \in X} u(i, T_t) \le \sum_{i \in T_t} u(i, T_t) = \operatorname{TU}(T_t)\); cộng trên các \(T_t \supseteq X\) thu được \(u(X) \le \operatorname{TWU}(X)\). (ii) Vì \(X \subseteq Y \implies \{T_t : Y \subseteq T_t\} \subseteq \{T_t : X \subseteq T_t\}\) và mọi \(\operatorname{TU}(T_t) \ge 0\), suy ra \(\operatorname{TWU}(Y) \le \operatorname{TWU}(X)\). \(\blacksquare\)
NhờTWDC, nếu \(\operatorname{TWU}(X) < \text{minutil}\), ta cắt tỉa an toàn cả \(X\) lẫn toàn bộ tập cha của nó. -
Tiến hóa Thuật toán HUIM Một pha SOTA:
HUI-Miner(Liu & Qu, CIKM 2012): Loại bỏ pha tạo ứng viên tốn kém của Two-Phase nhờ cấu trúc utility-list(tid, iutil, rutil), trong đórutil(remaining utility) chỉ cộng hữu ích các phần tử xếp sau \(X\) trong \(T_t\), cho cận trên chặt hơn nhiều \(u(X) + \sum \text{rutil} \ll \operatorname{TWU}(X)\).FHM(Fournier-Viger et al., ISMIS 2014): Bổ sung ma trận đồng xuất hiệnEUCS(Estimated Utility Co-occurrence Structure), bỏ qua tới 95% phép nối utility-list vô ích.EFIM(Zida, Fournier-Viger, Lin, Wu, & Tseng, MICAI 2015 / KAIS 2016): Kết hợp chiếu cơ sở dữ liệu, gộp giao dịch giống nhau (HTM), mảng đếm nhanhFAC, và hai cận trên cực chặt Local Utility và Sub-tree Utility, giảm thời gian và RAM hàng chục đến hàng trăm lần trên nhật ký bán lẻ thực tế; các biến thể 2024–2025 mở rộng sang Top-\(k\) HUIM (không cần đoánminutil),iHUIMtăng dần cho dòng sự kiện, và xử lý lợi nhuận âm (loss-leader promos).
- Mở rộng Sang Chuỗi Tuần tự (
SPM&HUSPM): Khi thứ tự thời gian quan trọng (bước nhấp chuột trong phiên hoặc mua lặp theo tuần),SPADE(Zaki, 2001) vàPrefixSpan(Pei et al., 2001) khai phá mẫu tuần tự không gian ứng viên nhỏ, cònHUSPMkết hợp trọng số lợi nhuận qua cận trên Sequence-Weighted Utilization (SWU) và Prefix/Remaining Sequence Utility.
2.4 Cầu nối Kiến trúc 2026: Từ Bảng Đồng xuất hiện Rời rạc đến Neural & Generative Retrieval#
Chứng minh Đại số Chính xác: Prod2Vec / Item2Vec \(\equiv\) Phân rã Ma trận \(\ln\operatorname{Lift}\) Dịch chuyển#
Cầu nối giữa phân tích giỏ hàng cổ điển và học biểu diễn dày (dense embeddings) không phải trực giác kinh nghiệm, mà là một đẳng thức đại số chính xác chứng minh bởi Levy & Goldberg (NeurIPS 2014):
Xét mô hình Skip-Gram with Negative Sampling (SGNS) huấn luyện vector mặt hàng \(\mathbf{w}_i \in \mathbb{R}^d\) và vector ngữ cảnh \(\mathbf{c}_j \in \mathbb{R}^d\) trên tập giỏ hàng (hoặc chuỗi phiên), lấy \(k_{\text{neg}}\) mẫu âm cho mỗi cặp đồng xuất hiện dương \((i, j)\) theo phân phối đơn biến \(P_{\mathcal{D}}(j) = \frac{\#(j)}{\lvert\mathcal{C}\rvert}\) (với \(\#(i,j)\) là số lần cặp \((i,j)\) xuất hiện trong cửa sổ giỏ hàng và \(\lvert\mathcal{C}\rvert\) là tổng số cặp ngữ cảnh). Đặt \(z = \mathbf{w}_i^\top \mathbf{c}_j\) và \(\sigma(z) = (1 + e^{-z})^{-1}\). Kỳ vọng hàm mục tiêu cục bộ cho cặp \((i, j)\) là:
Lấy đạo hàm riêng theo \(z\) và sử dụng đồng nhất thức \(\frac{d}{dz}\ln \sigma(z) = 1 - \sigma(z)\) cùng \(\frac{d}{dz}\ln \sigma(-z) = -\sigma(z)\), tại điểm tối ưu tự do bậc đủ lớn (\(d\) đủ rộng):
Rút tỷ số \(\frac{1 - \sigma(z)}{\sigma(z)} = e^{-z}\) ta có ngay:
Lấy logarit tự nhiên hai vế thu được đẳng thức kinh điển:
Ý nghĩa Kỹ thuật: Lift(i, j) trong MBA chính là \(\exp(\operatorname{PMI}(i, j))\)! Khi Prod2Vec (Grbovic et al., KDD 2015) và Item2Vec (Barkan & Koenigstein, IEEE MLSP 2016 — bỏ qua thứ tự trong giỏ hàng, window = full basket) tối ưu SGNS trên giỏ hàng, chúng đang thực hiện ngầm một phép phân rã ma trận hạng thấp có trọng số lên ma trận \(\ln\operatorname{lift}(i,j) - \ln k_{\text{neg}}\). Nhờ chiếu vào không gian \(\mathbb{R}^d\), hai mặt hàng đuôi dài chưa từng xuất hiện chung trực tiếp vẫn thừa hưởng lân cận ngữ nghĩa thông qua các mặt hàng trung gian! (Chú ý quan trọng: phép kẹp \(\text{PPMI} = \max(\text{PMI}, 0)\) hoặc SPPMI xóa sạch vùng âm \(\operatorname{PMI} < 0\), tức làm mất tín hiệu sản phẩm thay thế—nên trong sản xuất luôn cần tách riêng cơ chế phát hiện thay thế bằng \(\operatorname{Zhang} < 0\) hoặc đồ thị co-view!)
Tiến hóa Kiến trúc Truy xuất 2024–2026: Session GNN \(\to\) Two-Tower + HNSW \(\to\) Generative / Diffusion Bundles#
- Session Graph Neural Networks (
SR-GNN\(\to\)GCE-GNN\(\to\) Siêu đồ thị 2024–2026):
Hành vi duyệt web trong phiên mua sắm thường lặp vòng, quay lui để so sánh—vượt ngoài mô hình tuyến tính.SR-GNN(Wu et al., AAAI 2019) dựng đồ thị có hướng \(\mathcal{G}_s\) cho phiên hiện tại và truyền thông điệp qua Gated GNN để ghép sở thích toàn phiên (soft-attention) với ý định tức thời (\(v_n\)).GCE-GNN(Wang et al., SIGIR 2020) nâng cấp thành kiến trúc đồ thị kép kết hợp đồ thị phiên cục bộ và đồ thị chuyển tiếp toàn cục tổng hợp từ toàn bộ tập phiên (tổng quát hóa trực tiếp ma trận đồng xuất hiện thành truyền thông điệp đa bước). Giai đoạn 2024–2026 mở rộng sang Hypergraph Neural Networks (DHCN,COTREC) mô hình hóa đồng xuất hiện \(n\)-ngôi của cả giỏ hàng, SSL tương phản cho phiên thưa, và suy giảm cạnh theo thời gian. - Two-Tower Neural Retrieval + Hiệu chỉnh Thiên kiến Phổ biến +
HNSWANN:
Phát triển từ hệ thống hai tầng của Covington, Adams, & Sargin (RecSys 2016), Yi et al. (RecSys 2019, Google) tách Tháp Người dùng/Ngữ cảnh \(f_\theta(x_u) \in \mathbb{R}^d\) khỏi Tháp Mặt hàng/Đa phương thức \(g_\phi(x_i) \in \mathbb{R}^d\). Vì huấn luyện softmax theo lô (in-batch negatives) lấy mẫu mặt hàng phổ biến tỷ lệ với xác suất \(q_i\), mô hình chưa hiệu chỉnh sẽ phạt quá nặng hàng bán chạy; trừ đi \(\ln q_i\) (ước lượng trực tuyến bằng mảng băm tần suất) khôi phục độ hiệu chuẩn tích vô hướng. Vector \(g_\phi(x_i)\) được lập chỉ mục ngoại tuyến vào cấu trúc đồ thị phân tầngHNSW(Malkov & Yashunin, IEEE TPAMI 2020), đạt tốc độ truy hồi dưới mili-giây ở độ phức tạp \(\mathcal{O}(\log N)\) với \(>95\%\) recall@k trên \(10^8\)–\(10^9\) SKUs. - Truy xuất Sinh & Tổng hợp Giỏ hàng Khuếch tán (2025–2026):
TIGER(Rajput et al., NeurIPS 2023) đề xuất Semantic IDs quaRQ-VAE(Residual-Quantized VAE), lượng tử hóa embedding liên tục thành bộ mã rời rạc từ thô đến tinh \((c_1, c_2, c_3, c_4)\) để Transformer tự hồi quy sinh trực tiếp mã sản phẩm mà không cần chỉ mục ANN ngoài.- Quy mô Công nghiệp 2025–2026:
OneRec-V1 / V2&OneReason(Kuaishou, 2025–2026) thay thế tầng truy xuất–xếp hạng nối tầng bằng mô hình MoE sinh thống nhất (V2 chuyển sang decoder-only lười quy mô 8B tham số, cắt giảm 94% chi phí tính toán so với V1 và tinh chỉnh phần thưởng DPO/RL; OneReason bổ sung lập luận chuỗi suy nghĩ CoT gắn nhãn mặt hàng 3 cấp);TBGRecall(Alibaba, 08/2025) dự báo phiên kế tiếp (Next Session Prediction);GenRec(JD App, SIGIR 2026 & Netflix GenRec, 08/2026) tối ưu theo trang vàGRPO-SR. - Tổng hợp Giỏ hàng Không Thứ tự (
DPE-Rec; Ma et al., 10/2026,arXiv:2610.34700): Khắc phục thiên kiến trái-sang-phải của mô hình tự hồi quy trên các gói hàng không có thứ tự (unordered bundles) bằng Mô hình Ngôn ngữ Khuếch tán hai chiều (Diffusion LM), kết hợpGRPOnhận biết nhánh ngữ nghĩa (semantic-fork-aware GRPO) để giữ đa dạng gói hàng và chưng cất quỹ đạo giả (pseudo-trajectory distillation) cho giải mã song song nhiều token. Trong sản xuất, lớp giải mã luôn bị khóa vào cây tiền tố (trie) Semantic ID hợp lệ của danh mục và lọc qua tồn kho DuckDB/Polars + bộ kiểm định biên lợi nhuận HUIM/Fisher để chống bịa đặt SKU và bẫy giảm giá âm biên.
Ma trận Lựa chọn Kiến trúc 5 Hệ hình (2026 Commerce & DSAI Stack)#
| Hệ hình | Động cơ Toán học / Thuật toán Cốt lõi | Khả năng Xử lý Cold-Start / Đuôi dài | Khả năng Diễn giải & Bảo chứng Thống kê | Chi phí Tính toán & Độ trễ Phục vụ | Vai trò Chính trong Thương mại 2026 |
|---|---|---|---|---|---|
| SSPD + HUIM (Thống kê Chuẩn) | Fisher chính xác + BH-FDR (\(q\)-value) + Webb SSI / EFIM |
Yếu khi cặp có 0 đồng xuất hiện | Cao nhất: \(p/q\)-value chính xác, kiểm toán biên lợi nhuận/TWU |
Batch cực nhanh trên Polars/DuckDB/Rust; tra cứu \(O(1)\) | Luật bán chéo độ tin cậy cao, kiểm toán biên gói hàng, hàng rào bảo vệ kinh doanh |
Prod2Vec / Item2Vec |
SGNS (\(\equiv\) phân rã \(\ln\operatorname{Lift} - \ln k_{\text{neg}}\)) | Trung bình (làm mịn qua lân cận đồng xuất hiện) | Trung bình (lân cận cosine) | Huấn luyện rất nhanh & phục vụ HNSW | Baseline truy xuất gọn nhẹ, đặc trưng tương đồng, khởi tạo Semantic ID |
Session GNN (SR-GNN, GCE-GNN) |
Truyền thông điệp đồ thị phiên cục bộ + toàn cục / siêu đồ thị | Trung bình (lan truyền cấu trúc đồ thị) | Thấp–Trung bình (trọng số attention) | Huấn luyện GPU vừa phải; suy luận đồ thị thời gian thực | Gợi ý bước nhấp kế tiếp & thêm giỏ hàng phiên ẩn danh |
Two-Tower + HNSW |
Mã hóa kép + softmax hiệu chỉnh \(\ln q_i\) + đồ thị lân cận ANN | Mạnh (nhờ đặc trưng văn bản/ảnh đa phương thức) | Thấp | Dưới mili-giây (< 5 ms) trên \(10^8\) SKUs |
Xương sống Truy xuất Ứng viên Giai đoạn 1 quy mô công nghiệp |
| Generative / Diffusion Bundles | RQ-VAE Semantic IDs + Autoregressive / Diffusion LM + DPO/GRPO |
Mạnh (Semantic IDs nội dung + suy luận LLM) | Thấp–Trung bình (CoT ở OneReason) | Huấn luyện nặng; phục vụ lượng tử hóa/chưng cất (DPE-Rec) |
Tổng hợp trang & hoàn thiện gói sản phẩm đa mục nhất quán |
Kiến trúc Pipeline MBA Production Đầu–Cuối Chống Rò rỉ & Bảo vệ Biên Lợi nhuận#
Ngân sách Độ trễ, Thông lượng, Bộ nhớ & Ranh giới Thất bại (Production Budgets & Boundaries):
- Tầng Dữ liệu Batch (
Data & Control Plane— chạy hàng đêm/giờ bằng Polars 2.0 + NumPy/BLAS): Thời gian tối đa< 15 phútcho \(10^7\) giỏ hàng trên nút 64 GB RAM; dữ liệu chuỗi lưu qua ArrowStringView+mmapgiữ đỉnh RAM< 12 GB; ma trận đồng xuất hiện chỉ tính trên tập từ vựng ứng viên \(M_f\) (nếu \(M_f > 20{,}000\), chuyển sang tích thưa CSR hoặc phân mảnh theo danh mục để ma trận \(M_f \times M_f\)float64không vượt quá3.2 GB). - Tầng Phục vụ Trực tuyến (
Serving Plane— Checkout Cart API): Ngân sách SLA< 40 ms p99(< 5 mstra cứu bảng luật đã hiệu chuẩn trong Redis/in-memory hash +< 12 msHNSWfallback cho SKU đuôi dài +< 10 mskiểm tra tồn kho thời gian thực & áp dụng logic lọc trùng giỏ). - Cơ chế Backpressure, Ranh giới Lỗi & Rollback Tự động: Nếu
Control Planephát hiện \(0\) luật đạt ngưỡng \(q \le \alpha\) sau sự kiện phân bố bất thường (vd. gãy đường ống ETL hoặc thay đổi mã SKU), hoặc bộ theo dõi Response Distribution Charts (RDC) trực tuyến cảnh báo tỷ lệ hủy/bỏ giỏ tăng đột biến vượt ngân sách lỗi (error budget), hệ thống từ chối quảng bá bảng luật mới và tự động chuyển mạch ngay về nhánh Fallback An toàn (gợi ý cùng danh mục giới hạn phổ biến + giữ bản snapshot bảng luật ổn định gần nhất) kèm cảnh báo PagerDuty.
Trụ cột 3 — Case Studies Thực tế, Bẫy Vận hành & Anti-Patterns Trong Python Khoa học Dữ liệu (Industry Cases, Failure Modes & Defensive Engineering)#
3.1 Nghiên cứu Tình huống Thực tế về Giỏ hàng & Sản phẩm Bổ trợ (Real-Product Basket & Complementarity Cases)#
1. Instacart — Vòng lặp Mua lại Thói quen vs. Bổ trợ Theo Phiên#
- Quy mô & Thiên kiến Chuối (
"3 Million Instacart Orders, Open Sourced", Jeremy Stanley, Instacart Tech Blog, 2017): Trong hơn 3 triệu đơn hàng bách hóa trực tuyến, ~41% tổng số giao dịch mua là mua lại (reorders). Hai sản phẩm dẫn đầu tuyệt đối là Bananas và Bag of Organic Bananas với tỷ lệ mua lại 70%–85%—tạo ra giai thoại "Going Bananas Benchmark" trong cộng đồng Kaggle (một mô hình ngây thơ gợi ý Chuối cho mọi giỏ hàng vẫn đạt điểm F1/Precision thô khá cao!). - Tách Đôi Kiến trúc Thành Hai Bài toán Khác biệt (Instacart Engineering Blog):
- "Buy It Again" (Dự báo Mua lại): Định khung là bài toán phân loại/xếp hạng nhị phân bằng GBDT (LightGBM/XGBoost) trên các đặc trưng RFM, số ngày kể từ đơn trước, chu kỳ tiêu thụ cá nhân hóa và thứ tự
add_to_cart_orderlịch sử. - "Pairings" & Truy xuất Ngữ cảnh Tập trung: Với bài toán bổ trợ trong cùng một giỏ, Instacart chuyển từ đếm đồng mua tĩnh sang pipeline đa tầng (truy xuất \(\to\) xếp hạng \(\to\) tái xếp hạng trên cả ô tự nhiên và tài trợ) sử dụng mô hình chuỗi dạng BERT trên sự kiện trong phiên (vd. thêm bột bánh pancake \(\to\) xem thịt xông khói \(\to\) thêm trứng \(\to\) suy ra "ý định bữa sáng"). Trong nghiên cứu học thuật,
Triple2Vecvà phiên bản phục vụ thời gian thực qua chỉ mục ANNRTT2Vecmô hình hóa bộ ba \((user, item_i, item_j)\) nhằm bóc tách độ hợp bổ trợ giữa hai sản phẩm khỏi sở thích riêng của người dùng.
- "Buy It Again" (Dự báo Mua lại): Định khung là bài toán phân loại/xếp hạng nhị phân bằng GBDT (LightGBM/XGBoost) trên các đặc trưng RFM, số ngày kể từ đơn trước, chu kỳ tiêu thụ cá nhân hóa và thứ tự
2. Walmart — FP-Growth Phân tán Đa kênh & Tách Biệt Mô hình Thay thế#
- Mở rộng quy mô Đa kênh (
Walmart Global Tech Blog): Apriori/FP-Growth đơn nút (mlxtend) sụp đổ khi hợp nhất nhật ký POS tại siêu thị truyền thống với đơn hàng trực tuyến. Kỹ thuật Walmart sử dụngpyspark.ml.fpm.FPGrowthtrên cộtArrayType(StringType), áp dụng lọc ngưỡng hỗ trợ sớm và phân vùng thực thi hợp lý để kiềm chế chi phí shuffle. - Giải mã Sứ mệnh Mua sắm (
Shopping Mission Decoding; Yuan et al., Springer): Giỏ bách hóa lớn mang tính toàn diện chứ không rời rạc. Hệ thống giải mã nhiệm vụ mua sắm tiềm ẩn từ giỏ hàng dở dang thay vì cộng đồng xuất hiện từng cặp rời. - Động cơ Thay thế Tách Rời (
Walmart Global Tech, 2021): Khi một mặt hàng hết tồn kho (out-of-stock), Walmart tuyệt đối không dùng lại mô hình bổ trợ mà vận hành riêng một mạng học sâu thay thế đánh giá ~100 đặc trưng thời gian thực (dung tích đóng gói, đơn giá, thương hiệu, loại hàng, lịch sử chấp nhận/từ chối của người chọn hàng và khách hàng)—chứng minh sản phẩm thay thế và sản phẩm bổ trợ mang hai hàm mục tiêu đối nghịch nhau.
3. Amazon — "Also Bought" vs. "Frequently Bought Together" (FBT) & P-Companion#
- Hai Bề mặt UI, Hai Hàm Mục tiêu Khác nhau (
Smith & Linden, IEEE Internet Computing 2017;McAuley et al., SIGIR/KDD 2015): Carousel "Customers Who Bought This Item Also Bought" là dải khám phá rộng (trộn lẫn bổ trợ, nâng cấp và hàng mua chung chéo phiên), trong khi widgetFrequently Bought Together (FBT)ngay tại trang sản phẩm ("Add all three to Cart") yêu cầu độ khớp bổ trợ cực khít, không dư thừa và đúng chiều. McAuley et al. (2015) chứng minh trên đồ thị sản phẩm Amazon rằng đồng xem ("Also Viewed") tương quan chặt với hàng thay thế (khách so sánh các lựa chọn cạnh tranh), còn đồng mua ("Also Bought" / "Bought Together") nghiêng về hàng bổ trợ. P-Companion(Hao et al., Amazon Science, CIKM 2020): Được thiết kế ở quy mô hàng trăm triệu SKU để sửa đúng 3 thất bại kinh điển của FBT truyền thống: (1) Đồng mua \(\neq\) Bổ trợ (nhãn giám sát từ xa bị nhiễu); (2) Bất đối xứng Có hướng (\(\text{Điện thoại} \to \text{Ốp lưng}\) rất cao nhưng \(\text{Ốp lưng} \to \text{Điện thoại}\) gần0); (3) Bẫy Dư thừa Đa dạng (gợi ý 3 hộp bóng tennis giống nhau cạnh vợt tennis là vô ích; widget cần 1 hộp bóng + 1 bao vợt + 1 băng trán). Giải pháp kết hợp Graph Attention Network (GAT) trên đồ thị hành vi sản phẩm (xử lý cold-start), Bộ dự báo Loại sản phẩm Encoder–Decoder (dự báo các loại hàng bổ trợ phân biệt), và Transfer Metric Learning chiếu embedding truy vấn vào từng không gian con loại sản phẩm đích.
4. Target, DoorDash & Tesco/Dunnhumby — Trạng thái Phiên, GenAI Trọng số Thuộc tính & Trí nhớ Chuỗi Dọc#
- Target (
Target Tech Blog):Target AutoComplete (TAC)định khung gợi ý giỏ hàng như bài toán tự hoàn thành tuần tự trên giỏ lũy tích có suy giảm theo độ mới (recency weighting, ví dụ sữa \(\to\) chế phẩm sữa; sữa + trứng \(\to\) làm bánh/bữa sáng). Ở kiến trúc gói hàng, Target tách rành mạch "sản phẩm dẫn dắt (driver)" (ghế ô tô trẻ em, TV) khỏi "sản phẩm đi kèm (go-together)" (tấm lót bảo vệ ghế, giá treo tường). Với hàng gia dụng & điện tử thưa dữ liệu, mô hìnhGRAM(GenAI-based Related Accessory Model) dùng LLM để học trọng số thuộc tính đặc thù từng ngành hàng (ưu tiên màu/chất liệu cho gối trang trí vs. chuẩn cổng kết nối/kích thước cho phụ kiện điện tử) kèm rào chắn đa dạng. - DoorDash (
DoorDash Engineering Blog): Widget Checkout Aisles dùng xếp hạng đa nhiệm Mixture-of-Experts qua phễuimpression -> click -> add-to-cart -> checkout. Để phá băng cold-start ngành tạp hóa, DoorDash dùng LLM suy luận khẩu vị tạp hóa từ lịch sử đặt món nhà hàng; đặc biệt tính năng trí nhớ tác tửAsk DoorDashghi nhớ mặt hàng thiết yếu định kỳ giúp đạt tỷ lệ chuyển đổi tương đối vào giỏ thanh toán cao hơn ~24%. - Tesco / Dunnhumby: Các nghiên cứu trên bộ dữ liệu Dunnhumby Complete Journey chỉ ra 70%–80% giỏ hàng bách hóa mang tính lặp lại thói quen so với 20%–30% khám phá, thúc đẩy kiến trúc lai giữa
LightGCNkết hợp suy giảm thời gian hàm mũ, hiệu chuẩn mùa vụ Bayes và trợ lý lập thực đơn theo tồn kho thực tế.
3.2 Khung Định hình Bài toán ML & Thác Chỉ số Vận hành (ML Problem Framing Cases & Metric Cascade)#
Khả năng định hình bài toán (problem framing)—chuyển mục tiêu kinh doanh thành hàm mất mát, nhãn huấn luyện và bộ chỉ số trực tuyến—là yếu tố phân định giữa mô hình chỉ thắng trên Kaggle và mô hình tạo giá trị P&L thực thụ:
- Netflix — Cá nhân hóa Ảnh bìa & Độ Hài lòng Đa mục tiêu vs. Clickbait (
Chandrashekar et al., Dec 2017;Gomez-Uribe & Hunt, ACM TOMIS 2015):
Tối ưu thuần cho tỷ lệ nhấp CTR hay lượt nhấn phát ngay lập tức tạo ra vòng lặp clickbait (ảnh đại diện giật gân kéo người xem rồi khiến họ thoát ngay sau vài giây, làm tăng tỷ lệ hủy gói). Netflix dùng Contextual Bandits tối ưu Take Fraction \(= \frac{\text{Qualified Plays}}{\text{Impressions}}\) (lượt xem đạt ngưỡng thời lượng tối thiểu kết hợp quy tắc đại diện nội dung), kiểm chứng ngoại tuyến trước qua Counterfactual Replay trên lưu lượng thăm dò ngẫu nhiên. Hệ thống gợi ý đóng góp ~80% tổng giờ xem và tiết kiệm >$1B/năm nhờ giữ chân thuê bao dài hạn. - Uber — Dự báo Phần dư (
DeeprETA) & Điều phối Thị trường Chuỗi (Uber Engineering Blog):
Thay vì ép mạng nơ-ron học lại bản đồ đường đi từ tọa độ GPS thuần,DeeprETAđặt ML làm bộ hiệu chỉnh phần dư trên động cơ tìm đường ngắn nhất C++ tất định (Dijkstra / Contraction Hierarchies):\[\text{Final ETA} = Y_{\text{route}} + \widehat{R}_{\text{DeeprETA}}, \qquad R = \text{Actual Arrival Time} - Y_{\text{route}}.\]Nhờ kế thừa tiên nghiệm vật lý tuyến đường và tra cứu embedding không gian \(O(1)\) qua transformer tuyến tính,DeeprETAđạt độ trễ chỉ vài mili-giây ở lưu lượng QPS cao nhất toàn Uber. Song song, bài toán ghép cuốc không thể tham lam theo khoảng cách ngắn nhất (vì dễ đẩy tài xế vào vùng hẻo lánh chết cung 15 phút sau), mà phải định khung bằng MDP / Reinforcement Learning đa chân trời kết hợp Dynamic Pricing (Surge) theo độ co giãn cung–cầu trên lưới lục giác không gian. - Booking.com — 6 Bài học từ 150 Mô hình ML Thành công (
Bernardi, Mavridis, & Estevez, ACM KDD 2019):
Chỉ số ngoại tuyến (AUC, Precision, RMSE) thường xuyên không phản ánh được tác động thương mại trong thử nghiệm A/B trực tuyến (RCT) và chỉ nên xem là "bài kiểm tra sức khỏe tối thiểu" (health check). Thêm một vài mili-giây độ trễ suy luận có thể ăn mòn hoàn toàn lợi ích độ chính xác; và vì nhãn đặt phòng/hủy phòng đến chậm, kỹ sư dùng Biểu đồ Phân phối Phản hồi (Response Distribution Charts — RDC) không giám sát để phát hiện trôi mô hình trước khi có nhãn, coi RCT thiết kế chặt chẽ là trọng tài cuối cùng. - Stripe Radar / Shield — Chi phí Sai số Bất đối xứng & Nhãn Gian lận Trễ 30–90 Ngày (
Stripe Engineering Blog):
Tỷ lệ gian lận trực tuyến chỉ khoảng ~0.1% (1/1,000giao dịch). Chặn nhầm khách hàng thật (False Positive, phải giữ ngưỡng trần ~0.1% tỷ lệ chặn giả) gây mất doanh thu và khách hàng rời bỏ vĩnh viễn—thường đắt hơn nhiều so với phí bồi hoàn (False Negative), tương ứng trực tiếp ngưỡng Bayes \(\tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\) từ Trụ cột 1! Đồng thời, ngân hàng phát hành thẻ mất 30–90 ngày mới báo cáo hoàn tiền (chargeback): huấn luyện trên giao dịch mới nhất sẽ đầu độc nhãn gian lận chưa lộ thành "hợp lệ". Stripe giải quyết bằng cửa sổ trưởng thành nhãn kết hợp mạng DNN đa nhánh kiểu ResNeXt xử lý 1,000+ đặc trưng xuyên mạng lưới trong< 100 ms, cắt giảm thời gian tái huấn luyện >85%. - Airbnb — Thị trường Hai Phía Giới hạn Công suất (
Grbovic & Cheng, KDD 2018;Haldar et al., KDD 2019;Journey Ranker, KDD 2023):
Khác với hàng hóa số không cạnh tranh, một căn hộ Airbnb chỉ bán được một lần cho mỗi khoảng ngày và đòi hỏi đồng thuận song phương (khách đặt + chủ nhà duyệt). Tối ưu thuần CTR khiến lưu lượng dồn vào chủ nhà siêu sao dẫn tới hàng loạt từ chối và hủy đặt phòng. Airbnb đưa trực tiếp lệnh từ chối của chủ nhà làm mẫu âm cứng (hard negatives), thiết kế mạng đa nhiệm dự báo đồng thời xác suất nhấp, xác suất chủ nhà chấp nhận, đặt phòng thành công, đánh giá 5 sao và phạt rủi ro khiếu nại CS, đồng thời xác thực nhanh qua interleaving trước khi chạy A/B booking kéo dài nhiều tuần.
Bảng Thác Chỉ số Vận hành 4 Tầng (4-Stage Production Metric Cascade)#
| Hệ thống / Miền | 1. Ngôi sao Bắc Đẩu Kinh doanh | 2. Chỉ số Động lực Vận hành (KPI) |
3. Hàm Mất mát & Chỉ số Ngoại tuyến | 4. Rào chắn Trực tuyến & Ngân sách Độ trễ |
|---|---|---|---|---|
| Netflix Artwork / Recs | Giữ chân hội viên dài hạn & LTV thuê bao | Số giờ xem chất lượng; giảm tỷ lệ rời bỏ | Phần thưởng bandit theo Take Fraction (xem \(\ge\) ngưỡng thời lượng); Replay phản thực tế | Tỷ lệ thoát sớm (clickbait detector), độ đa dạng danh mục; < 50 ms phục vụ UI |
| Uber DeeprETA & Dispatch | Tổng giá trị đặt chuyến & thanh khoản toàn thành phố | Số chuyến hoàn tất/giờ; tỷ lệ sử dụng tài xế | MAE / Huber trên phần dư ETA (\(ATA - Y_{\text{route}}\)); phần thưởng MDP đa bước | Đuôi sai số ETA p95/p99, tỷ lệ chạy rỗng, độ giật giá surge; vài mili-giây (QPS đỉnh) |
| Booking.com Travel ML | Số đơn đặt phòng ròng thực nhận & độ hài lòng | Tỷ lệ chuyển đổi ròng sau khi trừ hủy phòng | Log-loss / AUC / RMSE (chỉ dùng làm kiểm tra sức khỏe tối thiểu) | RDC không giám sát, tỷ lệ hủy; ngân sách độ trễ nghiêm ngặt |
| Stripe Radar / Shield | Giá trị giao dịch bảo vệ ròng trừ gian lận & churn | Tỷ lệ chargeback (\(\downarrow\)) tại trần chặn nhầm cố định | BCE có trọng số chi phí trên nhãn 30–90 ngày trưởng thành | Trần tỷ lệ chặn nhầm ~0.1%, tỷ lệ tranh chấp mạng lưới thẻ; < 100 ms p99 |
| Airbnb Search Ranking | Tăng trưởng & niềm tin thị trường hai phía | Số đêm lưu trú hoàn tất không tranh chấp | Đa nhiệm: \(P(\text{Click}), P(\text{Host Accept}), P(\text{Book}), P(\text{5-Star}), -P(\text{CS Issue})\) | Tỷ lệ chủ nhà từ chối, tỷ lệ hủy, thanh khoản chủ nhà mới; interleaving + RCT |
Retail Basket / FBT [Pattern] |
Biên lợi nhuận gộp gia tăng ròng & repeat LTV | Số đơn vị gia tăng mỗi giỏ (UPT) & tỷ lệ đính kèm | Log-loss có hướng + Zhang / Kulc + CATE uplift | Tỷ lệ ăn mòn (cannibalization), bỏ giỏ, khiếu nại hàng thay thế; < 40–100 ms Cart API |
3.3 Sáu Lỗi Thất bại Kinh điển trong Production MBA & Biện pháp Khắc phục (Six Production MBA Failure Modes)#
- Bẫy Phổ biến Chuối & Thiên lệch Tần suất Nền (
The "Banana Popularity Trap"):
Các mặt hàng thiết yếu như chuối, túi nilon hay nước suối (\(P \approx 0.20\text{–}0.35\)) tự động đạtSupportvàConfidencecao dù gần như độc lập (\(\operatorname{lift} \approx 1.0, \operatorname{Zhang} \approx 0.0\)), đẩy trôi các cặp ngách biên lợi nhuận cao (mỳ ý thủ công + dầu nấm truffle).
Khắc phục: Áp dụng bộ đôi null-invariantKulc+IRkết hợpZhangbị chặn trên \([-1, 1]\), đồng thời tái xếp hạng bằng biên lợi nhuận gia tăng kỳ vọng thực \((\Pr(B \mid A) - \Pr(B)) \times \pi_B\) để giáng hạng hàng thiết yếu biên thấp. - Ảo giác Đa kiểm định & Bùng nổ
LiftĐuôi dài (Multiple-Testing Illusion):
Kiểm định đồng thời \(10^8\) cặp trên danh mục lớn ở ngưỡng \(\alpha = 0.05\) hoặc xếp hạng theo \(\operatorname{lift}\) thô khi \(\sigma(A)=2, \sigma(B)=3\) làm tràn ngập bảng gợi ý bằng nhiễu ngẫu nhiên có \(p > 0.05\).
Khắc phục: Chia tách thời gian (trainkhai phá \(\to\)holdoutkiểm chứng), tính xác suất chính xác Fisher trong không gian log (math.lgamma+ truy hồi +LogSumExp) tránh mất thứ hạng khi \(p < 10^{-308}\), kiểm soát tỷ lệ sai quaBH-FDR(\(q\)-values) và tỉa tập dư thừa theo Webb SSI. - Nghịch lý Simpson, Nhiễm Hàng Thay thế & Bất đối xứng Có hướng (
Simpson's Paradox, Substitute Contamination & Directional Asymmetry):
Gộp chung giỏ hàng giữa các vùng miền hoặc kênh bán khác nhau có thể đảo ngược hoàn toàn chiều liên kết (Simpson's reversal: cặp dương giả trên tổng thể nhưng bằng 0 hoặc âm ở từng cửa hàng). Tệ hơn, thiếu lọc dấu khiến hệ thống gợi ý Sữa Nhãn B sau khi khách chọn Sữa Nhãn A (gây bực bội và bỏ giỏ), hoặc gợi ý TV $1,200 sau cáp HDMI $12.
Khắc phục: Kiểm định phân tầng theo cụm cửa hàng/sứ mệnh mua sắm; cách ly triệt để cặp thay thế qua \(\operatorname{Zhang} < 0\) (hoặc \(\operatorname{PMI} < 0\) — tuyệt đối không kẹpPPMItrước khi lọc thay thế!) và tách đồ thị co-view khỏi co-buy; chấm điểm có hướng \((P(B \mid A) - P(B)) \times \pi_B\) kết hợp phân loại vai trò Driver vs. Accessory (Target,Amazon P-Companion). - Điểm mù Biên Lợi nhuận, Ăn mòn Doanh số & Thiếu Uplift Nhân quả (
Margin, Cannibalization Blindness & Missing CATE):
Khuyến mãi "Mua A + B giảm 15%" cho những khách hàng vốn dĩ đã định mua cả A lẫn B ở giá nguyên giá làm tăng tỷ lệ chuyển đổi gói ảo trong khi âm thầm đốt lợi nhuận ròng.
Khắc phục: Tích hợpHUIM/TWUngay trong pha khai phá và tối ưu Đóng góp Ròng (Net Contribution):\[\text{Net Contribution} = \Delta\text{Gross Profit}_{\text{Cross-Sell}} - \text{Displaced Margin}_{\text{Cannibalization}} - \text{Promo Cost},\]kết hợp Causal Uplift (CATE) ước lượng \(\hat{\tau}(A, B) = P(\text{buy } B \mid \text{shown}, A) - P(\text{buy } B \mid \text{not shown}, A)\) thay vì \(P(\text{buy } B \mid A)\) tĩnh (sẽ học sâu trong Chương 05). - Khởi động Lạnh Đuôi dài & Trôi Thời gian / Mùa vụ (
Cold Start & Temporal Decay):
Bảng đếm cộng dồn vĩnh viễn coi giỏ hàng cách đây 2 năm ngang hôm nay, gợi ý đồ nướng mùa hè giữa tháng Giêng hoặc bất lực trước SKU mới mở bán (\(\sigma = 0\)).
Khắc phục: Gán trọng số suy giảm hàm mũ \(w(\Delta t) = e^{-\lambda \Delta t}\) + tiên nghiệm mùa vụ Bayes; dự phòng phân cấp danh mục theo co rút Empirical Bayes (SKU -> Brand+Subcategory -> Subcategory -> Category); và chuyển sang GAT (P-Companion), Two-Tower đa phương thức + HNSW, hoặc LLM (Target GRAM). - Rò rỉ Dữ liệu & Sai lệch Huấn luyện–Phục vụ (
Data Leakage & Train–Serve Skew):
Khai phá tập phổ biến và tính \(p\)-value trên cùng một tập dữ liệu (search-space overfitting); nhìn trộm các mặt hàng được thêm vào giỏ sau bước hiện tại trong cộtadd_to_cart_orderkhi huấn luyện mô hình dự báo thời gian thực; hoặc nối giá vốn/tỷ lệ hoàn hàng xảy ra sau khi thanh toán.
Khắc phục: Phân tách theo thời giantrain / holdouttuyệt đối; che mặt nạ nhân quả theoadd_to_cart_order(\(t' \le t\)); và đảm bảo đặc trưng thời điểm (point-in-time parity,Article #15).
3.4 Python / Pandas / NumPy Production Anti-Patterns & Mã nguồn Chuẩn (Anti-Patterns & Defensive Engineering)#
- Mảng Chuỗi
objectvs.categoryvs.ArrowDtype/ Pandas 3.0str:
Kiểuobjecttrong Pandas truyền thống lưu mảng con trỏ 8 byte trỏ tới từngPyUnicodeObjectrời rạc trên heap, ngốn RAM gấp2x–4xvà phá vỡ cache CPU. Trong production: dùngcategorycho cột phân loại độ phân giải thấp (aisle,store_id— giảm RAM5x–100x), và dùngstring[pyarrow](hoặc kiểustrmặc định dựa trên PyArrow của Pandas 3.0) cho chuỗi độ phân giải cao (order_id,sku) để giảm40%–70%RAM và chạy nhân chuỗi C++ vector hóa. - Bẫy Thông lượng
df.iterrows()&df.apply(axis=1):
df.iterrows()đóng hộp một đối tượngpd.Seriesmới cho từng dòng, khiến code chậm hơn phép toán vector hóa NumPy/Arrow/Polars từ100xđến1,000x. Luôn thay bằng phép toán cột,np.where/np.select, nhân ma trận BLAS, hoặc biểu thức Polars/DuckDB. - Bẫy
NaN, Ép kiểu Ngầmint64 -> float64(Va chạm ID \(> 2^{53}\)) & Logic Ba giá trịpd.NA:np.nan == np.nanluôn trả vềFalsetheo chuẩn IEEE-754; luôn kiểm tra bằngpd.isna(x)hoặcnp.isnan(x).- Mảng
int64của NumPy truyền thống không có bit null: chỉ cần xuất hiện mộtNULLsau phépleft join, toàn cột bị ép ngầm sangfloat64. Vìfloat64chỉ có 53 bit định trị (\(2^{53} \approx 9.007 \times 10^{15}\)), các khóatransaction_idhay Snowflake ID64-bitsẽ bị làm tròn và va chạm âm thầm khi join! Luôn dùngInt64(nullable) hoặcint64[pyarrow]với validity bitmap 1-bit. - Dưới
Int64/boolean, phép so sánhpd.NA == pd.NAtrả vềpd.NA(logic Kleene 3 giá trị); đưa vàoifsẽ văngTypeError: boolean value of NA is ambiguous—luôn xử lý qua.fillna(False)hoặcpd.isna().
- Đột biến View Ngầm & Ghim Bộ nhớ
v.base:
Trong NumPy, cắt lát là view (np.shares_memory(a, v) == True), nghĩa là sửavsẽ làm hỏnga, đồng thờivnhỏ xíu vẫn giữ toàn bộ mảnganhiều GB trong RAM quav.base. Luôn kiểm tra quyền sở hữu và gọi.copy()khi cần ngắt liên kết bộ nhớ. Pandas 3.0 ép buộc Copy-on-Write (CoW) giúp triệt tiêu hoàn toàn đột biến dây chuyền ngoài ý muốn. - Tính Không Kết hợp Dấu phẩy Động & Bẫy
PYTHONHASHSEED:
Theo chuẩn IEEE-754, \((a + b) + c \neq a + (b + c)\); chạy cộng song song không cố định thứ tự làm trôi kết quả ở chữ số thập phân cuối—hãy tích lũy ởfloat64, dùngmath.fsum, sắp thứ tự khóa trước khi gộp phân tán và dùngnp.isclose/pytest.approx. Nghiêm trọng hơn: từ Python 3.3 (PEP 456), hàm dựng sẵnhash(sku)được trộn muối ngẫu nhiên (PYTHONHASHSEED) mỗi lần khởi động tiến trình! Dùnghash(key) % 10để chia tập train/test hoặc phân mảnh dữ liệu sẽ cho ra tập chia khác nhau hoàn toàn sau mỗi lần chạy. Luôn dùng hàm băm tất định nhưhashlib.blake2b(digest_size=8)(có sẵn trong stdlib) hoặcxxhash.xxh3_64_intdigest.
Đoạn mã Chuẩn Hóa Kỹ thuật Phòng vệ (Defensive Engineering Reference Snippet)#
Đoạn mã dưới đây minh họa chuẩn AUTHORING_STANDARDS.md (type hints đầy đủ, docstring rõ ràng, sinh ngẫu nhiên tất định qua np.random.default_rng, zero scipy/sklearn, chạy trực tiếp trên Python >=3.10 với numpy và pandas):
from __future__ import annotations
import hashlib
import math
from typing import Sequence
import numpy as np
import pandas as pd
def deterministic_bucket(entity_id: str, n_buckets: int = 100) -> int:
"""Assign a cross-process deterministic bucket in [0, n_buckets).
Uses BLAKE2b (64-bit digest) instead of Python's salted built-in hash(),
guaranteeing identical cohort splits regardless of PYTHONHASHSEED or OS.
"""
if n_buckets <= 0:
raise ValueError("n_buckets must be positive")
digest = hashlib.blake2b(entity_id.encode("utf-8"), digest_size=8).digest()
return int.from_bytes(digest, byteorder="big", signed=False) % n_buckets
def safe_margin_rollup(
orders_df: pd.DataFrame,
promo_ids: Sequence[int],
seed: int = 42,
) -> tuple[pd.DataFrame, float]:
"""Compute vectorized basket margins without int64->float64 corruption or view pins."""
rng = np.random.default_rng(seed)
df = orders_df.copy()
# Preserve 64-bit integer IDs even when null values occur during left joins
df["transaction_id"] = df["transaction_id"].astype("Int64")
df["is_promo"] = df["transaction_id"].isin(promo_ids).fillna(False)
# Vectorized conditional pricing (replaces slow df.iterrows() / apply(axis=1))
unit_margin = df["unit_margin"].to_numpy(dtype=np.float64, copy=False)
qty = df["quantity"].to_numpy(dtype=np.float64, copy=False)
discount_factor = np.where(df["is_promo"].to_numpy(), 0.90, 1.00)
line_profit = unit_margin * qty * discount_factor
# Compensated float64 summation prevents catastrophic cancellation / order drift
df["net_profit"] = line_profit
total_profit = math.fsum(line_profit.tolist())
# Detach small slice from large backing array to prevent v.base memory leak
sample_idx = rng.choice(len(df), size=min(5, len(df)), replace=False)
detached_sample = df.iloc[sample_idx].copy()
return detached_sample, total_profit
Trụ cột 4 — Thực hành Lab 01 & Kiểm định Chất lượng Chống Rò rỉ (Hands-On Industrial Lab 01 & Leakage-Proof Evaluation Rubric)#
Bài thực hành đồng hành tại labs/lab-01-market-basket-analysis/ triển khai trọn vẹn hệ thống mba_lab từ nguyên lý gốc—biến mọi định lý ở Trụ cột 1, thuật toán thống kê ở Trụ cột 2 và hàng rào phòng vệ ở Trụ cột 3 thành mã nguồn Python kiểm chứng được bằng 16 kiểm thử tự động pytest.
4.1 Kiến trúc Gói mba_lab & Tương thích Môi trường Host#
labs/lab-01-market-basket-analysis/
├── pyproject.toml
├── README.md
├── src/
│ └── mba_lab/
│ ├── __init__.py
│ ├── synthetic_retail.py
│ ├── fpgrowth.py
│ ├── rules_and_significance.py
│ └── memory_benchmark.py
├── scripts/
│ └── run_lab_demo.py
└── tests/
└── test_mba_lab.py
Hợp đồng Phụ thuộc (pyproject.toml):
- Khai báo
name = "mba-lab",version = "0.1.0",requires-python = ">=3.10", và chỉ địnhdependencies = ["numpy>=1.26", "pandas>=2.0"]. - Tuyệt đối
0import hoặc phụ thuộc vàoscipy,scikit-learnhaymlxtend: Thiết kế tự chủ hoàn toàn này tránh triệt để lỗi xung đột ABI nhị phân (nhưAttributeError: _ARRAY_API not foundkhi bảnscipycũ gặpnumpy 2.x), đồng thời buộc học viên làm chủ thuật toán Fisher không gian log (math.lgamma+ hệ thức truy hồi \(O(1)\) +LogSumExp) và 2-scan FP-Growth từ đầu thay vì gọi hộp đen. - Gói
polars>=1.0được đặt trong[project.optional-dependencies](polars) và chỉ kích hoạt khi phát hiện quahas_polars(). Các kiểm thửpytest(dev = ["pytest>=8.0", "ruff>=0.4"]) được cấu hình vớitestpaths = ["tests"],pythonpath = ["src"],addopts = "-v".
4.2 Hướng dẫn Từng bước Qua 4 Mô-đun Cốt lõi#
Bước 1: Đo kiểm Bố cục Bộ nhớ, View/Stride & Phép nhân BLAS (src/mba_lab/memory_benchmark.py)#
Mô-đun đo lường định lượng lý thuyết ở §1.3 thông qua hai dataclass bất biến:
MemoryAndSpeedResult: lưubackend_name,n_elements,theoretical_payload_bytes,measured_object_bytes,bytes_per_element,elapsed_ms,throughput_melems_per_sec,checksum.ViewAuditResult: lưuslice_is_view,transpose_is_view,fancy_index_is_copy,non_contiguous_reshape_is_copy,broadcast_strides.
Các hàm chính học viên cần kiểm chứng:
estimate_python_float_list_bytes(values: list[float]) -> int: Cộngsys.getsizeof(values)(khungPyListObject56 B+ mảng con trỏob_item) với tổngsys.getsizeof(v)cho từngPyFloatObject(24 Bmỗi phần tử).benchmark_vector_scale_and_sum(n_elements: int = 500_000, repeats: int = 3, seed: int = 42) -> list[MemoryAndSpeedResult]: Sinh vector tất địnhx,wbằngnp.random.default_rng(seed)và tính \(\sum_{i=0}^{n-1} (1.75 x_i + 0.25 w_i)\) qua các engine"python_list_float","pandas_dataframe_float64","numpy_float64_contiguous", và tùy chọn"polars_series_float64"(nếuhas_polars()làTrue), kiểm chứngchecksumđồng nhất và tỷ sốbytes_per_element\(> 3\times\) giữa CPython và NumPy.benchmark_cooccurrence_engines(basket_matrix_uint8: np.ndarray, repeats: int = 3) -> list[MemoryAndSpeedResult]: So sánh tính ma trận đồng xuất hiện \(C = B^\top B \in \mathbb{R}^{M \times M}\) bằng"python_nested_basket_loops","pandas_dataframe_dot","numpy_blas_matmul"(x64.T @ x64trên mảngC_CONTIGUOUSfloat64giải phóng GIL), và tùy chọn"polars_cooccurrence".audit_numpy_views_and_strides() -> ViewAuditResult: Dùngnp.shares_memoryxác nhận trêna = np.arange(24, dtype=np.float64).reshape(4, 6)rằnga[:, ::2]vàa.Tlà zero-copy view,a[[0, 2], :]vàa.T.reshape(-1)buộc cấp phát bản sao mới, cònnp.broadcast_arrays(np.ones((3, 1)), np.ones((1, 4)))sinh rabroadcast_strides == (0, 0).
Bước 2: Sinh Dữ liệu Bán lẻ Có Cấu trúc & Tách mẫu Thời gian (src/mba_lab/synthetic_retail.py)#
Đóng gói đặc tả SKU qua ItemSpec (item_id, sku, category, unit_price, unit_margin, role) và tập dữ liệu qua RetailDataset (transactions, item_specs, transaction_df, planted_complements, planted_substitutes, staple_skus):
generate_synthetic_retail_baskets(n_transactions: int = 4000, n_long_tail_skus: int = 40, seed: int = 42) -> RetailDataset: Sử dụngnp.random.default_rng(seed)(bất biến trướcPYTHONHASHSEED) để gieo chính xác các tình huống thực tế ở §3.3:- 3 mặt hàng "Banana Trap" phổ biến, biên thấp:
"banana","plastic_bag","mineral_water"(unit_margintrong[0.15, 0.35], xác suất biên ~0.25–0.35độc lập nhau để \(\text{Lift} \approx 1.0, \text{Zhang} \approx 0.0\)). - 5 cụm bổ trợ biên lợi nhuận cao:
("pasta_artisan", "truffle_oil"),("espresso_maker", "espresso_beans"),("espresso_beans", "coffee_filter"),("gaming_laptop", "usb_c_dock"),("pancake_mix", "maple_syrup")với biên phụ kiện từ $4.50 đến $18.00 và \(\text{Zhang} \gg 0\). - 2 cặp thay thế loại trừ lẫn nhau:
("whole_milk_brand_a", "whole_milk_brand_b")và("laundry_pod_alpha", "laundry_pod_beta")với \(\operatorname{Zhang} < -0.25\). n_long_tail_skusmã đuôi dài Zipfian ("tail_sku_000", ...) tạo cặp nhiễu thưa.- Bảng
transaction_dfxuất đủ 8 cột["transaction_id", "timestamp_idx", "sku", "category", "quantity", "unit_price", "unit_margin", "line_profit"], trong đó các cột ID và số lượng giữ nguyên kiểu nguyênint64không chứaNaN.
- 3 mặt hàng "Banana Trap" phổ biến, biên thấp:
temporal_train_holdout_split(dataset: RetailDataset, train_fraction: float = 0.5) -> tuple[list[frozenset[str]], list[frozenset[str]]]: Cắt tạisplit_idx = int(len(dataset.transactions) * train_fraction), giữ nguyên thứ tự thời gian và đảm bảotrainvớiholdouthoàn toàn tách rời nhau.baskets_to_binary_matrix(transactions: Sequence[Collection[str]], vocab: Sequence[str] | None = None) -> tuple[np.ndarray, list[str]]: Sinh ma trận C-contiguousdtype=np.uint8hình dạng(N, M).
Bước 3: Khai phá FP-Growth 2-Quét, Đối chiếu Apriori & Cận trên TWU (src/mba_lab/fpgrowth.py)#
Định nghĩa FPNode (item, count, parent, children, node_link), FrequentItemset (items, support_count, support), và FPTreeSummary (n_transactions, min_support_count, f_list, n_tree_nodes, compression_ratio):
resolve_min_support_count(...)chuẩn hóa ngưỡng đếm tối thiểu \(\sigma_{\min}\).mine_frequent_itemsets_fpgrowth(...)thực hiện đúng 2 lượt quét (f_listsắp giảm dần theo(-count, item), cây tiền tố liên kếtnode_link, cơ sở mẫu điều kiện lấy trọng số theonode.count, đường tắt đơn nhánh) và trả về danh sáchFrequentItemsetsắp xếp tất định.build_fpgrowth_summary(...)tính toáncompression_ratio = total_filtered_items / max(n_tree_nodes, 1).mine_frequent_itemsets_apriori(...)cài đặt Apriori theo từng tầng làm bộ đối chứng chuẩn xác (ground-truth cross-check) cho FP-Growth.compute_twu_and_exact_utility(transaction_df: pd.DataFrame, itemsets: Sequence[frozenset[str]]) -> dict[frozenset[str], tuple[float, float]]: Gom nhóm theotransaction_idtính \(\operatorname{TU}(T_t) = \sum \text{line\_profit}\) và trả về{itemset: (u(X), TWU(X))}, đảm bảo bất biến \(u(X) \le \operatorname{TWU}(X)\) khi lợi nhuận không âm.
Bước 4: Kiểm định Fisher Log-Space, Hiệu chỉnh BH-FDR & Cách ly Hàng Thay thế (src/mba_lab/rules_and_significance.py)#
Định nghĩa FisherExactResult (log_p_value, neg_log10_p, p_value, odds_ratio) và AssociationRule gồm đầy đủ 22 trường (antecedent, consequent, n_transactions, support_antecedent_count, support_consequent_count, support_both_count, support, confidence, lift, leverage, conviction, zhang, kulczynski, imbalance_ratio, log_p_value, p_value, q_value, holm_p_value, consequent_margin, expected_incremental_margin, is_significant, is_substitute):
log_binom(n, k)vàlogsumexp_1d(log_values)xử lý an toàn mọi biên.fisher_exact_right_tail(k, count_a, count_b, n_total) -> FisherExactResult: Tính \(\ln p_{\text{right}}(k)\) qualog_binom+ truy hồi \(O(1)\) +logsumexp_1d, giữ ổn định ngay cả khi \(p < 10^{-308}\).benjamini_hochberg_logvàholm_bonferroni_log: Tínhq_valuevàholm_p_valuetrong không gian log hỗ trợ tham sốtotal_hypothesescho toàn không gian tìm kiếm.compute_rule_metrics(...): Trả về từ điển 8 thước đo ("support","confidence","lift","leverage","conviction","zhang","kulczynski","imbalance_ratio"), xử lýmath.infchoconvictionkhi ngoại lệ bằng 0.extract_and_test_rules(frequent_itemsets, eval_transactions, ...): Lọc ứng viênmin_confidencechỉ trên tậptraintrước khi kiểm định nghiêm ngặt trêneval_transactions(holdout) (giữ nguyên tổng số giả thuyết \(m\) choBH-FDR/Holm thay vì co rút hậu chọn lọc), tính biên lợi nhuận gia tăng kỳ vọng thựcexpected_incremental_margin = (confidence - support_consequent) * consequent_margin, gánis_significant = (q_value <= alpha) and (zhang > 0.0),is_substitute = (zhang < 0.0), và sắp theo(q_value, log_p_value, -expected_incremental_margin, -zhang, ...).find_substitute_pairs(transactions, min_marginal_support=0.01, max_zhang=-0.25): Dùngbaskets_to_binary_matrixvà phép nhân ma trận BLASX_f64.T @ X_f64quét toàn bộ cặp có tần suất biên đạt ngưỡng—kể cả cặp có 0 lần đồng xuất hiện mà FP-Growth bỏ qua—trả về các cặp thay thế cózhang <= max_zhang.
Bước 5: Thực thi Một lệnh CLI (scripts/run_lab_demo.py)#
Từ thư mục gốc của Lab 01 (labs/lab-01-market-basket-analysis/), chạy kịch bản trình diễn:
python scripts/run_lab_demo.py --n-transactions 4000 --train-fraction 0.5 --min-support 0.02 --min-confidence 0.15 --alpha 0.05 --n-bench 200000 --seed 42
Tập lệnh chấp nhận đủ 8 tham số CLI (--n-transactions, --train-fraction, --min-support, --min-confidence, --alpha, --n-bench, --seed, --json-out) và xuất ra 4 khối báo cáo chuẩn hóa:
[1] Memory & Vectorization Benchmark: So sánh byte/phần tử, thông lượng và checksum giữapython_list_float,pandas,numpy(vàpolarsnếu có), cùngViewAuditResultvà thời gian tính \(B^\top B\) BLAS.[2] Worked 6-Transaction Textbook Cross-Check: Khẳng định cả FP-Growth và Apriori đều tìm ra đúng 15 tập phổ biến ở \(\sigma_{\min} = 2\) khớp §1.4.[3] Leakage-Free Synthetic Retail MBA (Train Mine -> Holdout Fisher + BH-FDR): Báo cáo kích thướctrain/holdout, tỷ lệ nén cây FP-Tree, top luật bổ trợ có ý nghĩa thống kê sắp theoq_valuevàexpected_incremental_margin, đồng thời chứng minh các mặt hàng Chuối/Túi nilon cózhanggần0và bị giáng hạng về lợi nhuận gia tăng.[4] Substitute Pair Quarantine (Negative Zhang via Vectorized B^T B): Liệt kê các cặp thay thế bị cách ly ở ngưỡngzhang < -0.25.
4.3 Danh mục Kiểm định Chống Rò rỉ & Bộ 16 Kiểm thử Tự động (pytest Contract)#
Bảng Kiểm tra Bắt buộc Trước khi Nghiệm thu (Anti-Leakage & Acceptance Checklist)#
- [ ] Tách tập Thời gian Tuyệt đối & Lọc
min_confidenceChỉ trêntrain:temporal_train_holdout_splitđược gọi trước mọi bước đếmf_list, dựng cây FP-Tree; ứng viênmin_confidenceđược lọc và đóng băng trêntraintrước khi kiểm định Fisher + BH-FDR trênholdout(giữ nguyên mẫu số \(m\));len(train) + len(holdout) == Nvới hai tập chỉ số giao bằng rỗng. - [ ] Lõi Tham chiếu Sạch & Rào chắn AST Chỉ Bảo mật (
Security-Only AST Deserialization Ban): Lõimba_labcài đặt từ gốc bằng Python>=3.10+numpy+pandas(không phụ thuộcscipy/scikit-learn/mlxtend); bộ kiểm thử quét AST toàn bộsrc/,scripts/,tests/cấm tuyệt đối các import giải tuần tự hóa nguy hiểm (pickle,_pickle,cPickle,joblib,cloudpickle,dill,shelve,marshal). - [ ] Ổn định Số học Dưới ngưỡng
1e-308: Hàmfisher_exact_right_tailtrả vềlog_p_valuehữu hạn vàneg_log10_p > 300.0cho các cặp liên kết cực mạnh mà không gặpOverflowErrorhay mất thứ tựq_value. - [ ] Kiểm soát Đa kiểm định & Thanh lọc Thay thế: Mọi luật gắn nhãn
is_significant=Truebắt buộc thỏa đồng thờiq_value <= 0.05(BH-FDR) vàzhang > 0.0(0% hàng thay thế lọt vào bảng gợi ý). - [ ] Chống Bẫy Chuối & Bẫy Số nguyên: Cột
transaction_id,timestamp_idx,quantitytrongtransaction_dfgiữ nguyêninteger dtypevới0giá trịNaN; luật trỏ tới"banana","plastic_bag","mineral_water"bị các cặp phụ kiện biên cao vượt mặt theo biên lợi nhuận gia tăng kỳ vọng thựcexpected_incremental_margin = (Pr(B|A) - Pr(B)) * m_B. - [ ] Tất cả
16/16kiểm thửpytestđạt 100% không bỏ qua (skip) hay nới lỏng khẳng định (assertion).
Hợp đồng 16 Kiểm thử Bắt buộc (tests/test_mba_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Kiểm chứng |
|---|---|---|
| 1 | test_toy_example_fpgrowth_matches_apriori_exact_15_itemsets |
Chạy cả mine_frequent_itemsets_fpgrowth và mine_frequent_itemsets_apriori trên dữ liệu mẫu 6 giỏ (min_support_count=2); kiểm tra đúng 15 tập (5 cỡ 1, 7 cỡ 2, 3 cỡ 3) khớp nhau 100%. |
| 2 | test_fpgrowth_apriori_equivalence_on_synthetic_sample |
Lấy 300 giỏ tổng hợp (seed=7), chạy cả hai thuật toán (min_support=0.05, max_len=3), khẳng định tập (items, support_count) trùng khớp tuyệt đối. |
| 3 | test_fpgrowth_tree_compression_summary |
Kiểm tra build_fpgrowth_summary tạo f_list giảm dần tất định và compression_ratio >= 1.0. |
| 4 | test_interestingness_measures_and_zhang_bounds |
Kiểm chứng giá trị chính xác trên mẫu ({d}->{b}: conf==1.0, lift==1.2, conv==math.inf, zhang==0.25, kulczynski==0.7, imbalance_ratio==0.6; {d}->{e}: zhang==-1.0) và lưới thuộc tính zhang in [-1, 1], kulczynski, imbalance_ratio in [0, 1]. |
| 5 | test_fisher_exact_reference_values_and_no_underflow |
Kiểm tra chuẩn "Lady Tasting Tea" ((4,4,4,8)->1/70, (3,4,4,8)->17/70, (0,4,4,8)->1.0) VÀ trường hợp cực trị (5000, 5500, 5500, 100000) đạt math.isfinite(log_p_value), log_p_value < -750.0, neg_log10_p > 300.0, p_value == 0.0 không lỗi tràn. |
| 6 | test_bh_fdr_and_holm_monotonicity_and_total_hypotheses |
Đối chiếu tính tay BH-FDR \(q\)-values & Holm step-down, khẳng định q <= holm từng phần tử và \(q\) tăng khi tăng total_hypotheses. |
| 7 | test_temporal_split_zero_leakage_and_determinism |
Gọi generate_synthetic_retail_baskets(..., seed=42) hai lần ra kết quả y hệt; kiểm tra phân tách len(train) + len(holdout) == N và cột ID của transaction_df đạt pd.api.types.is_integer_dtype. |
| 8 | test_end_to_end_pipeline_recovers_complements_and_rejects_substitutes |
Chạy pipeline đầy đủ (n=4000, train_fraction=0.5, min_support=0.02, alpha=0.05), xác nhận các cặp bổ trợ gieo sẵn đạt q_value <= 0.05, zhang > 0.2 còn find_substitute_pairs bắt được cặp thay thế ở zhang <= -0.25. |
| 9 | test_banana_trap_margin_demotion |
Khẳng định các mặt hàng thiết yếu có hỗ trợ biên >= 0.20 nhưng bất kỳ luật nào gợi ý chúng đều xếp dưới các cặp phụ kiện biên lợi nhuận cao theo expected_incremental_margin. |
| 10 | test_twu_downward_closure_invariant |
Kiểm tra compute_twu_and_exact_utility giữ đúng \(u(X) \le \operatorname{TWU}(X)\) và \(\operatorname{TWU}(X \cup \{i\}) \le \operatorname{TWU}(X)\). |
| 11 | test_memory_benchmark_bytes_and_checksum_parity |
Chạy benchmark_vector_scale_and_sum(n_elements=20_000, repeats=1), xác nhận python_list_float.bytes_per_element > 3.0 * numpy_float64_contiguous.bytes_per_element và checksum khớp (pytest.approx(..., rel=1e-6)). |
| 12 | test_cooccurrence_blas_matches_python_loops |
Chạy benchmark_cooccurrence_engines trên ma trận (200, 15), khẳng định tổng ma trận BLAS \(X^\top X\) khớp tuyệt đối vòng lặp Python và Pandas. |
| 13 | test_numpy_views_and_broadcast_zero_stride |
Xác nhận audit_numpy_views_and_strides() trả về slice_is_view=True, transpose_is_view=True, fancy_index_is_copy=True, non_contiguous_reshape_is_copy=True, và broadcast_strides == (0, 0). |
| 14 | test_cli_demo_script_runs_cleanly |
Gọi scripts/run_lab_demo.py --n-transactions 600 --n-bench 10000 qua subprocess.run, kiểm tra returncode == 0 và có đủ 4 khối báo cáo chuẩn. |
| 15 | test_train_only_min_confidence_preserves_bh_m_and_incremental_margin |
Xác nhận lọc min_confidence diễn ra chỉ trên train trước kiểm định holdout (giữ nguyên tổng số giả thuyết \(m\) của BH-FDR) và kiểm chứng công thức biên lợi nhuận gia tăng thực (confidence - Pr(B)) * consequent_margin. |
| 16 | test_security_ast_no_unsafe_deserialization |
Quét AST toàn bộ tệp .py trong src/, scripts/, tests/ bảo đảm 0 lệnh import giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA & Bài tập Đánh giá Năng lực (Curated Reading List & Mastery Exercises)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong 2024–2026 (Curated SOTA Reading List)#
- Wolpert, D. H. (1996). "The Lack of A Priori Distinctions Between Learning Algorithms." Neural Computation, 8(7), 1341–1390.
Vì sao quan trọng: Đặt nền móng toán học cho Định lý No-Free-Lunch, bác bỏ ngộ nhận "thuật toán vạn năng" và giải thích vì sao thiết kế thiên kiến quy nạp (\(\mathcal{H}\)) khớp cấu trúc dữ liệu là chìa khóa thành công của ML. - Han, J., Pei, J., & Yin, Y. (2000). "Mining Frequent Patterns without Candidate Generation." Proceedings of ACM SIGMOD 2000, pp. 1–12.
Vì sao quan trọng: Phát minh cây tiền tốFP-Treevà phương phápFP-Growth2 lượt quét, triệt tiêu bùng nổ ứng viên \(C_k\) của Apriori trên dữ liệu giao dịch dày. - Hämäläinen, W., & Webb, G. I. (2019). "A Tutorial on Statistically Sound Pattern Discovery." Data Mining and Knowledge Discovery, 33, 325–377 (kế thừa Webb 2007 &
SSI2010).
Vì sao quan trọng: Hệ thống hóa kiểm định chính xác Fisher/siêu bội, hiệu chỉnh đa kiểm địnhBH-FDR/Holm, tập tự đủ (SSI), và cơ chế chia tậptrain/holdoutđể loại bỏ phát hiện giả trên dữ liệu đuôi dài. - Zida, S., Fournier-Viger, P., Lin, J. C.-W., Wu, C.-W., & Tseng, V. S. (2016). "EFIM: A Fast and Memory Efficient Algorithm for High-Utility Itemset Mining." Knowledge and Information Systems (tiếp nối MICAI 2015).
Vì sao quan trọng: Đưa bài toán đồng xuất hiện nhị phân sang tối ưu lợi nhuận thực (HUIM) qua cận trên cục bộ/cây con cực chặt và kỹ thuật gộp giao dịchHTM. - Hao, J., et al. (2020) — "P-Companion: A Principled Framework for Diversified Complementary Product Recommendation" (Amazon Science, ACM CIKM 2020), đọc song hành cùng Levy, O., & Goldberg, Y. (2014) — "Neural Word Embedding as Implicit Matrix Factorization" (NeurIPS 2014).
Vì sao quan trọng: Chứng minh mối liên hệ đại số chính xác \(\mathbf{w}_i^\top \mathbf{c}_j = \ln\operatorname{lift}(i, j) - \ln k_{\text{neg}}\) nối MBA rời rạc sangProd2Vec/Item2Vec, và minh họa kiến trúc công nghiệp giải quyết đồng thời hướng, đa dạng hóa và cold-start bằng GAT + Transfer Metric Learning. - Apache Arrow
StringView/ PyCapsule Specification + Polars 2.0 (10/2026) + Ma, P., et al. (10/2026) — "DPE-Rec: Diversity-Preserving and Efficient Diffusion Language Model Recommendation for Bundle Construction" (arXiv:2610.34700).
Vì sao quan trọng: Kết nối hạ tầng xử lý cột zero-copy thế hệ 2026 (ArrowStringView, streaming tràn đĩa mặc định trong Polars 2.0,abi3tPython 3.15) với frontier tổng hợp gói sản phẩm không thứ tự bằng Diffusion LM + GRPO bảo toàn đa dạng.
5.2 Sáu Bài tập Đánh giá Năng lực (Graded Mastery Exercises)#
Nhóm A — Chứng minh Toán học & Suy diễn Nguyên lý (40%)#
-
Bài tập 1 (20% — Ngưỡng Quyết định Bayes Bất đối xứng & Ứng dụng Gian lận):
Cho hàm mất mát nhị phân bất đối xứng \(L(0, 1) = C_{\text{FP}} > 0\), \(L(1, 0) = C_{\text{FN}} > 0\), \(L(0,0) = L(1,1) = 0\).- Chứng minh từ nguyên lý tối thiểu hóa rủi ro điều kiện rằng bộ phân loại tối ưu Bayes dự báo \(\hat{y}=1\) khi và chỉ khi \(\eta(x) = P(Y=1 \mid X=x) \ge \tau^* = \frac{C_{\text{FP}}}{C_{\text{FP}} + C_{\text{FN}}}\).
- Áp dụng vào hệ thống Stripe Radar: Giả sử tỷ lệ gian lận thực \(P(Y=1) = 0.001\), một giao dịch gian lận bỏ sót gây tổn thất trực tiếp + phí chargeback tổng cộng 180 USD (\(C_{\text{FN}}\)), còn chặn nhầm một khách hàng hợp lệ gây mất biên lợi nhuận ngay + mất LTV dài hạn tổng cộng 720 USD (\(C_{\text{FP}}\)). Tính ngưỡng \(\tau^*\). Nếu một mô hình học sâu có xác suất đầu ra chưa hiệu chuẩn (phóng đại xác suất lên gấp \(3\times\) ở vùng đuôi dương), việc dùng trực tiếp \(\tau^*\) trên điểm thô sẽ vi phạm ràng buộc trần chặn nhầm ~0.1% như thế nào?
-
Bài tập 2 (20% — Chứng minh Thước đo Zhang & Phản ví dụ Hàng Thay thế):
- Cho \(p_A \in (0, 1)\), \(p_B \in (0, 1]\), \(\alpha = \hat{P}(B \mid A)\) và \(\beta = \hat{P}(B \mid \neg A)\). Chứng minh đầy đủ \(\operatorname{Zhang}(A \to B) = \frac{\alpha - \beta}{\max(\alpha, \beta)} \in [-1, 1]\) trên cả ba chế độ (\(\alpha > \beta\), \(\alpha = \beta\), \(\alpha < \beta\)).
- Xây dựng một cơ sở dữ liệu bán lẻ bằng số cụ thể gồm \(N = 100{,}000\) giỏ hàng cho hai thương hiệu viên nén cà phê Espresso loại trừ nhau hoàn toàn (\(p_A = p_B = 0.02\), \(\sigma(A \cup B) = 0\)). Tính chính xác
Support,Confidence,Lift,Leverage,Conviction,Kulczynski,Imbalance Ratio, vàZhang. Giải thích vì sao một pipeline chỉ lọc bằngLeveragehoặcPPMIsẽ bỏ sót hoàn toàn cặp cạnh tranh này.
Nhóm B — Kỹ thuật Hệ thống & Đo kiểm Bộ nhớ (35%)#
-
Bài tập 3 (17.5% — Gỡ lỗi 3 Lỗi Kinh điển Trong Script Pandas/NumPy Cũ):
Một kỹ sư mới vào nghề viết đoạn code sau cho pipeline bán lẻ và gặp ba sự cố nghiêm trọng trong production:python11 dòngimport numpy as np import pandas as pd def buggy_prep(raw_orders: pd.DataFrame, prices: np.ndarray) -> tuple[pd.DataFrame, np.ndarray]: # Bug A: left join introduces a missing order_id in a 64-bit Snowflake ID column (> 2^53) df = raw_orders.merge(pd.DataFrame({"sku": ["a"], "tax": [0.1]}), on="sku", how="outer") # Bug B: keeps a tiny 16-element view slicing a 4 GB float64 buffer alive top_prices = prices[:16] # Bug C: non-deterministic split across workers and runs df["is_holdout"] = df["sku"].apply(lambda s: (hash(str(s)) % 10) >= 8) return df, top_pricesHãy: (i) Chẩn đoán cơ chế phần cứng/CPython/IEEE-754 gây ra từng lỗi
Bug A,Bug B,Bug C; (ii) Viết lại hàmfixed_prepchuẩn mực sử dụngInt64/int64[pyarrow],.copy()(kiểm chứng quanp.shares_memory), vàhashlib.blake2b(digest_size=8), kèm một bài testpytesttái hiện và kiểm chứng cả 3 lỗi đều đã được khắc phục. -
Bài tập 4 (17.5% — Thực nghiệm Stride, Cache Line & C-Order vs. F-Order):
Mở rộng mô-đunmba_lab.memory_benchmark(trên bản sao cục bộ hoặc nhánh bài tập của bạn) bằng hàmbenchmark_axis_strides(rows: int = 8000, cols: int = 8000)tạo hai ma trậnfloat64giống hệt nhau về giá trị:mat_c(order='C') vàmat_f(order='F'). Đo thời gian cộng dồn theoaxis=0vàaxis=1trên cả hai bố cục. Giải thích định lượng độ chênh lệch độ trễ quan sát được thông qua công thức bước nhảy byte \(s_k\), kích thước dòng cache64 B, bộ nạp trước phần cứng, và độ rộng thanh ghi AVX2/AVX-512.
Nhóm C — Thiết kế Kiến trúc Production & Phân tích Lỗi (25%)#
-
Bài tập 5 (12.5% — Thiết kế Kiến trúc Checkout Add-On Dưới SLA
< 40 msp99):
Thiết kế kiến trúc đầu–cuối cho dịch vụ gợi ý "Thêm vào giỏ tại quầy thanh toán" cho một siêu thị tạp hóa trực tuyến Đông Nam Á có500,000SKUs và50 triệuđơn hàng/năm, ràng buộc độ trễ phục vụ trực tuyến< 40 msp99. Trong bản thiết kế (kèm sơ đồ luồng dữ liệu), hãy chỉ rõ giải pháp kỹ thuật để phòng vệ đồng thời trước: (a) Bẫy phổ biến Chuối/Túi nilon; (b) Nghịch lý Simpson giữa cửa hàng đại siêu thị và cửa hàng tiện lợi; (c) Ăn mòn biên lợi nhuận khuyến mãi (cannibalization); và (d) Cold-start cho 2,000 SKU mới ra mắt mỗi tháng. -
Bài tập 6 (12.5% — Chẩn đoán Pipeline Khai phá Thất bại Trên A/B Test):
Một đội ngũ khoa học dữ liệu khai phá luật kết hợp trên toàn bộ1 triệugiỏ hàng của tháng trước (\(M = 10{,}000\) SKUs), lọc theomin_support = 0.001,min_confidence = 0.25, và giữ lại mọi cặp cóp_value <= 0.05từ kiểm định \(\chi^2\). Khi đưa 200 cặp top đầu lên A/B test trực tuyến, 80% thất bại hoặc gây sụt giảm tỷ lệ chuyển đổi. Hãy chỉ ra ít nhất 4 sai lầm thống kê và thiết kế thực nghiệm trong quy trình trên, sau đó thiết kế lại quy trình chuẩn xác sử dụng Temporal Split-Sample, Exact Fisher (\(\ln p\)),BH-FDR,Zhang > 0, và CATE Uplift.
5.3 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh toán học chặt chẽ không nhảy bước; xử lý triệt để tràn số dưới chuẩn trong không gian log (log_p_value hữu hạn, không mất xếp hạng khi \(p < 10^{-308}\)); tách tập thời gian tuyệt đối chống rò rỉ xác minh qua assert tất định; phân tích chính xác bước nhảy byte / dòng cache 64 B / v.base; kiến trúc production cân bằng chặt chẽ độ trễ < 40 ms, biên lợi nhuận, cách ly hàng thay thế và cơ chế rollback an toàn. |
| Senior Standard | 75–89% | Triển khai thuật toán đúng và bộ kiểm thử chạy qua toàn bộ, nhưng còn thiếu sót nhỏ ở các biên nâng cao (ví dụ quên truyền total_hypotheses khi hiệu chỉnh không gian tìm kiếm lớn, chưa kiểm tra np.shares_memory cho v.base, hoặc giải thích Roofline/CATE chưa định lượng rõ). |
| Needs Remediation | < 75% | Để xảy ra dưới chuẩn p = 0.0 gây sụp thứ hạng, gộp chung train + holdout trước khi kiểm định Fisher (rò rỉ hậu chọn lọc), dùng df.iterrows() hoặc hash() mặc định trong đường dẫn dữ liệu, hoặc để hàng thay thế (\(\text{Zhang} < 0\)) / bẫy Chuối lọt vào tập gợi ý cuối cùng. |
1. Memory Layout & SIMD Benchmark (n = 200,000 phần tử float64)
2. Ma trận Đồng xuất hiện C = BᵀB & Kiểm chứng 6 Giỏ hàng
3. Top Luật Bổ trợ Holdout (Fisher Log-Space + BH-FDR q ≤ 0.05 + Margin Ranking)
Khai phá 57 tập từ train=2000,
kiểm định trên holdout=2000 (60 luật ứng viên →
22 luật đạt ý nghĩa).
Nhóm Banana Trap (banana, plastic_bag, mineral_water) bị đẩy xuống đáy bảng theo biên lợi nhuận kỳ vọng.
| Luật A → B | Supp | Conf | Zhang | ln p (Fisher) | q-value (BH-FDR) | Exp. Margin |
|---|---|---|---|---|---|---|
{usb_c_dock} → {gaming_laptop} |
0.040 | 0.870 | +0.987 | -250.1 | 1.81e-108 | $147.43 |
{coffee_filter, espresso_beans} → {espresso_maker} |
0.028 | 0.377 | +0.946 | -96.3 | 6.75e-42 | $31.37 |
{espresso_beans} → {espresso_maker} |
0.037 | 0.368 | +0.971 | -140.6 | 5.22e-61 | $30.56 |
{coffee_filter} → {espresso_maker} |
0.028 | 0.302 | +0.931 | -82.3 | 5.89e-36 | $24.29 |
{gaming_laptop} → {usb_c_dock} |
0.040 | 0.792 | +0.992 | -250.1 | 1.81e-108 | $13.43 |
{pasta_artisan} → {truffle_oil} |
0.058 | 0.720 | +0.982 | -285.7 | 1.23e-123 | $6.18 |
{coffee_filter, espresso_maker} → {espresso_beans} |
0.028 | 1.000 | +0.925 | -133.8 | 4.32e-58 | $5.85 |
{coffee_filter, mineral_water} → {espresso_beans} |
0.022 | 0.833 | +0.904 | -86.6 | 9.52e-38 | $4.76 |
4. Cách ly Cặp Thay thế (Negative Zhang) & Bất biến TWU (HUIM)
Top Cặp Thay thế Bị Cách ly (BᵀB)
-
whole_milk_brand_a ↔ whole_milk_brand_bZhang = -0.8990 -
laundry_pod_alpha ↔ laundry_pod_betaZhang = -0.8481 -
pancake_mix ↔ whole_milk_brand_bZhang = -0.4563 -
gaming_laptop ↔ pancake_mixZhang = -0.3976 -
espresso_maker ↔ pancake_mixZhang = -0.3307
Kiểm chứng Cận trên TWU: u(X) ≤ TWU(X)
-
{banana}u = $366.08 ≤ TWU = $26235.55 -
{gaming_laptop, usb_c_dock}u = $32472.00 ≤ TWU = $33837.87 -
{espresso_beans, espresso_maker}u = $16544.50 ≤ TWU = $19276.27
02-track-1-data-science-and-ai/part-01-math-stats-and-causal/labs/lab-01-market-basket-analysis
[build-system]
requires = ["setuptools>=61.0"]
build-backend = "setuptools.build_meta"
[project]
name = "mba-lab"
version = "0.1.0"
description = "Market Basket Analysis, Statistically Sound Pattern Discovery, High-Utility Pruning, and Memory Architecture Lab (T1-P1-U01)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.0",
]
[project.optional-dependencies]
polars = ["polars>=1.0"]
dev = ["pytest>=8.0", "ruff>=0.4"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["src"]
addopts = "-v"
[tool.ruff]
line-length = 100
target-version = "py310"
"""Market Basket Analysis, Statistically Sound Pattern Discovery, and Memory Architecture Lab."""
from __future__ import annotations
from mba_lab.fpgrowth import (
FPNode,
FPTreeSummary,
FrequentItemset,
build_fpgrowth_summary,
compute_twu_and_exact_utility,
mine_frequent_itemsets_apriori,
mine_frequent_itemsets_fpgrowth,
resolve_min_support_count,
)
from mba_lab.memory_benchmark import (
MemoryAndSpeedResult,
ViewAuditResult,
audit_numpy_views_and_strides,
benchmark_cooccurrence_engines,
benchmark_vector_scale_and_sum,
estimate_python_float_list_bytes,
has_polars,
)
from mba_lab.rules_and_significance import (
AssociationRule,
FisherExactResult,
benjamini_hochberg_log,
compute_rule_metrics,
extract_and_test_rules,
find_substitute_pairs,
fisher_exact_right_tail,
holm_bonferroni_log,
log_binom,
logsumexp_1d,
)
from mba_lab.synthetic_retail import (
ItemSpec,
RetailDataset,
baskets_to_binary_matrix,
generate_synthetic_retail_baskets,
temporal_train_holdout_split,
)
__all__ = [
"AssociationRule",
"FPNode",
"FPTreeSummary",
"FisherExactResult",
"FrequentItemset",
"ItemSpec",
"MemoryAndSpeedResult",
"RetailDataset",
"ViewAuditResult",
"audit_numpy_views_and_strides",
"baskets_to_binary_matrix",
"benchmark_cooccurrence_engines",
"benchmark_vector_scale_and_sum",
"benjamini_hochberg_log",
"build_fpgrowth_summary",
"compute_rule_metrics",
"compute_twu_and_exact_utility",
"estimate_python_float_list_bytes",
"extract_and_test_rules",
"find_substitute_pairs",
"fisher_exact_right_tail",
"generate_synthetic_retail_baskets",
"has_polars",
"holm_bonferroni_log",
"log_binom",
"logsumexp_1d",
"mine_frequent_itemsets_apriori",
"mine_frequent_itemsets_fpgrowth",
"resolve_min_support_count",
"temporal_train_holdout_split",
]
"""Synthetic retail basket generator, temporal splitting, and binary matrix encoding."""
from __future__ import annotations
from collections.abc import Collection, Sequence
from dataclasses import dataclass
import numpy as np
import pandas as pd
@dataclass(frozen=True, slots=True)
class ItemSpec:
"""Catalog specification for a single retail SKU."""
item_id: int
sku: str
category: str
unit_price: float
unit_margin: float
role: str # "staple" | "anchor" | "complement" | "substitute" | "long_tail"
@dataclass(frozen=True, slots=True)
class RetailDataset:
"""Deterministic retail basket dataset with planted causal/margin structure."""
transactions: list[frozenset[str]]
item_specs: dict[str, ItemSpec]
transaction_df: pd.DataFrame
planted_complements: tuple[tuple[str, str], ...]
planted_substitutes: tuple[tuple[str, str], ...]
staple_skus: tuple[str, ...]
_STAPLE_PROBS: tuple[tuple[str, str, float, float, float], ...] = (
("banana", "produce", 1.20, 0.22, 0.34),
("plastic_bag", "checkout", 0.50, 0.15, 0.30),
("mineral_water", "beverages", 1.50, 0.32, 0.26),
)
_PLANTED_COMPLEMENTS: tuple[tuple[str, str], ...] = (
("pasta_artisan", "truffle_oil"),
("espresso_maker", "espresso_beans"),
("espresso_beans", "coffee_filter"),
("gaming_laptop", "usb_c_dock"),
("pancake_mix", "maple_syrup"),
)
_PLANTED_SUBSTITUTES: tuple[tuple[str, str], ...] = (
("whole_milk_brand_a", "whole_milk_brand_b"),
("laundry_pod_alpha", "laundry_pod_beta"),
)
_CORE_SPECS: tuple[tuple[str, str, float, float, str], ...] = (
("banana", "produce", 1.20, 0.22, "staple"),
("plastic_bag", "checkout", 0.50, 0.15, "staple"),
("mineral_water", "beverages", 1.50, 0.32, "staple"),
("pasta_artisan", "pantry", 6.50, 2.20, "anchor"),
("truffle_oil", "pantry", 24.00, 9.50, "complement"),
("espresso_maker", "appliances", 420.00, 95.00, "anchor"),
("espresso_beans", "coffee", 18.00, 6.50, "complement"),
("coffee_filter", "coffee", 12.00, 4.80, "complement"),
("gaming_laptop", "electronics", 1450.00, 180.00, "anchor"),
("usb_c_dock", "electronics", 65.00, 18.00, "complement"),
("pancake_mix", "breakfast", 5.50, 1.90, "anchor"),
("maple_syrup", "breakfast", 16.00, 6.20, "complement"),
("whole_milk_brand_a", "dairy", 4.20, 1.10, "substitute"),
("whole_milk_brand_b", "dairy", 4.40, 1.25, "substitute"),
("laundry_pod_alpha", "household", 14.50, 4.20, "substitute"),
("laundry_pod_beta", "household", 15.00, 4.50, "substitute"),
)
_TAIL_CATEGORIES: tuple[str, ...] = (
"snacks",
"bakery",
"personal_care",
"beverages",
"pantry",
)
def _build_catalog(
n_long_tail_skus: int, rng: np.random.Generator
) -> tuple[dict[str, ItemSpec], list[tuple[str, float]]]:
"""Build deterministic SKU specs and Zipfian tail sampling probabilities."""
item_specs: dict[str, ItemSpec] = {}
for item_id, (sku, category, price, margin, role) in enumerate(_CORE_SPECS):
item_specs[sku] = ItemSpec(
item_id=item_id,
sku=sku,
category=category,
unit_price=price,
unit_margin=margin,
role=role,
)
tail_probs: list[tuple[str, float]] = []
base_id = len(_CORE_SPECS)
for idx in range(n_long_tail_skus):
sku = f"tail_sku_{idx:03d}"
category = _TAIL_CATEGORIES[idx % len(_TAIL_CATEGORIES)]
unit_price = round(float(rng.uniform(2.0, 14.0)), 2)
unit_margin = round(float(unit_price * rng.uniform(0.20, 0.35)), 2)
prob = min(0.015, 0.015 / ((idx + 1) ** 0.75))
item_specs[sku] = ItemSpec(
item_id=base_id + idx,
sku=sku,
category=category,
unit_price=unit_price,
unit_margin=unit_margin,
role="long_tail",
)
tail_probs.append((sku, prob))
return item_specs, tail_probs
def _sample_single_basket(
rng: np.random.Generator,
tail_probs: Sequence[tuple[str, float]],
staple_skus: tuple[str, ...],
) -> frozenset[str]:
"""Sample one non-empty retail basket with independent staples, complements, and substitutes."""
basket: set[str] = set()
# 1. Independent high-prevalence, low-margin staples ("Banana Trap")
for sku, _, _, _, prob in _STAPLE_PROBS:
if rng.random() < prob:
basket.add(sku)
# 2. Complementary anchor -> accessory clusters
if rng.random() < 0.08:
basket.add("pasta_artisan")
if rng.random() < 0.72:
basket.add("truffle_oil")
elif rng.random() < 0.015:
basket.add("truffle_oil")
if rng.random() < 0.055:
basket.add("espresso_maker")
if rng.random() < 0.78:
basket.add("espresso_beans")
elif rng.random() < 0.06:
basket.add("espresso_beans")
if "espresso_beans" in basket:
if rng.random() < 0.68:
basket.add("coffee_filter")
elif rng.random() < 0.02:
basket.add("coffee_filter")
if rng.random() < 0.055:
basket.add("gaming_laptop")
if rng.random() < 0.76:
basket.add("usb_c_dock")
elif rng.random() < 0.01:
basket.add("usb_c_dock")
if rng.random() < 0.085:
basket.add("pancake_mix")
if rng.random() < 0.72:
basket.add("maple_syrup")
elif rng.random() < 0.015:
basket.add("maple_syrup")
# 3. Mutually exclusive substitute pairs (high exclusivity -> Zhang << 0)
if rng.random() < 0.24:
draw = rng.random()
if draw < 0.50:
basket.add("whole_milk_brand_a")
elif draw < 0.995:
basket.add("whole_milk_brand_b")
else:
basket.add("whole_milk_brand_a")
basket.add("whole_milk_brand_b")
if rng.random() < 0.18:
draw = rng.random()
if draw < 0.52:
basket.add("laundry_pod_alpha")
elif draw < 0.995:
basket.add("laundry_pod_beta")
else:
basket.add("laundry_pod_alpha")
basket.add("laundry_pod_beta")
# 4. Zipfian long-tail items (independent low rates)
for sku, prob in tail_probs:
if rng.random() < prob:
basket.add(sku)
# Guarantee non-empty basket without perturbing staple independence when tail SKUs exist.
if not basket:
if tail_probs:
filler_idx = int(rng.integers(0, len(tail_probs)))
basket.add(tail_probs[filler_idx][0])
else:
filler_idx = int(rng.integers(0, len(staple_skus)))
basket.add(staple_skus[filler_idx])
return frozenset(basket)
def generate_synthetic_retail_baskets(
n_transactions: int = 4000,
n_long_tail_skus: int = 40,
seed: int = 42,
) -> RetailDataset:
"""Generate a deterministic retail basket dataset with planted complements, substitutes, and staples.
Args:
n_transactions: Number of chronological baskets to simulate (>= 10).
n_long_tail_skus: Number of low-frequency Zipfian long-tail SKUs (>= 0).
seed: Seed passed to ``numpy.random.default_rng`` for full determinism.
Returns:
A ``RetailDataset`` containing baskets, SKU metadata, and line-item DataFrame.
"""
if n_transactions < 10:
raise ValueError(f"n_transactions must be >= 10, got {n_transactions}.")
if n_long_tail_skus < 0:
raise ValueError(f"n_long_tail_skus must be >= 0, got {n_long_tail_skus}.")
rng = np.random.default_rng(seed)
staple_skus = tuple(sku for sku, *_ in _STAPLE_PROBS)
item_specs, tail_probs = _build_catalog(n_long_tail_skus, rng)
transactions: list[frozenset[str]] = []
tx_ids: list[int] = []
ts_indices: list[int] = []
skus: list[str] = []
categories: list[str] = []
quantities: list[int] = []
unit_prices: list[float] = []
unit_margins: list[float] = []
line_profits: list[float] = []
for tid in range(n_transactions):
basket = _sample_single_basket(rng, tail_probs, staple_skus)
transactions.append(basket)
# Sort items deterministically so row order and RNG calls are PYTHONHASHSEED-invariant.
for sku in sorted(basket):
spec = item_specs[sku]
if spec.role in ("staple", "long_tail"):
qty = int(rng.integers(1, 4)) if rng.random() < 0.25 else 1
else:
qty = 1
tx_ids.append(tid)
ts_indices.append(tid)
skus.append(sku)
categories.append(spec.category)
quantities.append(qty)
unit_prices.append(spec.unit_price)
unit_margins.append(spec.unit_margin)
line_profits.append(round(qty * spec.unit_margin, 6))
transaction_df = pd.DataFrame(
{
"transaction_id": np.asarray(tx_ids, dtype=np.int64),
"timestamp_idx": np.asarray(ts_indices, dtype=np.int64),
"sku": pd.Series(skus, dtype="object"),
"category": pd.Series(categories, dtype="object"),
"quantity": np.asarray(quantities, dtype=np.int64),
"unit_price": np.asarray(unit_prices, dtype=np.float64),
"unit_margin": np.asarray(unit_margins, dtype=np.float64),
"line_profit": np.asarray(line_profits, dtype=np.float64),
}
)
return RetailDataset(
transactions=transactions,
item_specs=item_specs,
transaction_df=transaction_df,
planted_complements=_PLANTED_COMPLEMENTS,
planted_substitutes=_PLANTED_SUBSTITUTES,
staple_skus=staple_skus,
)
def temporal_train_holdout_split(
dataset: RetailDataset,
train_fraction: float = 0.5,
) -> tuple[list[frozenset[str]], list[frozenset[str]]]:
"""Chronologically partition baskets into non-overlapping train and holdout splits.
Args:
dataset: RetailDataset whose ``transactions`` are ordered chronologically.
train_fraction: Fraction of earliest transactions assigned to training, in (0, 1).
Returns:
Tuple ``(train_transactions, holdout_transactions)`` with zero index overlap.
"""
if not (0.0 < train_fraction < 1.0):
raise ValueError(f"train_fraction must lie strictly in (0, 1), got {train_fraction}.")
n_total = len(dataset.transactions)
if n_total < 2:
raise ValueError(f"Need at least 2 transactions to split, got {n_total}.")
split_idx = int(n_total * train_fraction)
if split_idx < 1 or split_idx >= n_total:
raise ValueError(
f"train_fraction={train_fraction} yields empty partition for {n_total} transactions."
)
return list(dataset.transactions[:split_idx]), list(dataset.transactions[split_idx:])
def baskets_to_binary_matrix(
transactions: Sequence[Collection[str]],
vocab: Sequence[str] | None = None,
) -> tuple[np.ndarray, list[str]]:
"""Encode transactions into a C-contiguous binary ``uint8`` incidence matrix.
Args:
transactions: Sequence of transaction item collections.
vocab: Optional fixed SKU vocabulary order. Defaults to sorted unique items.
Returns:
Tuple ``(matrix, resolved_vocab)`` where ``matrix`` has shape
``(len(transactions), len(resolved_vocab))`` and ``dtype=np.uint8``.
"""
if vocab is None:
unique_items: set[str] = set()
for basket in transactions:
unique_items.update(basket)
resolved_vocab = sorted(unique_items)
else:
resolved_vocab = list(vocab)
n_rows = len(transactions)
n_cols = len(resolved_vocab)
matrix = np.zeros((n_rows, n_cols), dtype=np.uint8)
if n_rows == 0 or n_cols == 0:
return np.ascontiguousarray(matrix, dtype=np.uint8), resolved_vocab
item_to_col = {sku: idx for idx, sku in enumerate(resolved_vocab)}
for row_idx, basket in enumerate(transactions):
for sku in basket:
col_idx = item_to_col.get(sku)
if col_idx is not None:
matrix[row_idx, col_idx] = 1
return np.ascontiguousarray(matrix, dtype=np.uint8), resolved_vocab
"""2-Scan FP-Growth, Apriori ground-truth cross-check, and HUIM TWU utility bounds."""
from __future__ import annotations
import functools
import itertools
import math
import operator
from collections import defaultdict
from collections.abc import Collection, Sequence
from dataclasses import dataclass
import numpy as np
import pandas as pd
@dataclass(slots=True)
class FPNode:
"""Prefix-tree node storing item identity, branch count, parent, children, and header link."""
item: str | None
count: int
parent: FPNode | None
children: dict[str, FPNode]
node_link: FPNode | None = None
@dataclass(frozen=True, slots=True)
class FrequentItemset:
"""Frequent pattern with absolute support count and relative support ratio."""
items: frozenset[str]
support_count: int
support: float
@dataclass(frozen=True, slots=True)
class FPTreeSummary:
"""Global FP-Tree compression diagnostics and canonical descending f_list."""
n_transactions: int
min_support_count: int
f_list: tuple[tuple[str, int], ...]
n_tree_nodes: int
compression_ratio: float
@dataclass(slots=True)
class _BuiltFPTree:
"""Internal container for a constructed FP-Tree and its header chains."""
root: FPNode
f_list: list[tuple[str, int]]
header_heads: dict[str, FPNode]
n_tree_nodes: int
total_filtered_items: int
def resolve_min_support_count(
n_transactions: int,
min_support: float | None = None,
min_support_count: int | None = None,
) -> int:
"""Resolve minimum absolute support count from either absolute count or relative ratio."""
if n_transactions < 1:
raise ValueError(f"n_transactions must be >= 1, got {n_transactions}.")
if min_support_count is not None:
resolved = int(min_support_count)
if not (1 <= resolved <= n_transactions):
raise ValueError(
f"min_support_count must lie in [1, {n_transactions}], got {min_support_count}."
)
return resolved
if min_support is None or not (0.0 < min_support <= 1.0):
raise ValueError(f"min_support must lie in (0, 1], got {min_support}.")
return max(1, math.ceil(min_support * n_transactions))
def _build_fp_tree(
weighted_transactions: Sequence[tuple[Collection[str], int]],
min_support_count: int,
) -> _BuiltFPTree:
"""Execute the 2-scan FP-Tree build over deduplicated weighted transactions."""
item_counts: dict[str, int] = defaultdict(int)
for items, weight in weighted_transactions:
if weight <= 0:
continue
for item in items:
item_counts[item] += weight
frequent_items = {
item: count for item, count in item_counts.items() if count >= min_support_count
}
root = FPNode(item=None, count=0, parent=None, children={})
if not frequent_items:
return _BuiltFPTree(
root=root,
f_list=[],
header_heads={},
n_tree_nodes=0,
total_filtered_items=0,
)
f_list = sorted(frequent_items.items(), key=lambda kv: (-kv[1], kv[0]))
order_rank = {item: idx for idx, (item, _) in enumerate(f_list)}
header_heads: dict[str, FPNode] = {}
header_tails: dict[str, FPNode] = {}
n_tree_nodes = 0
total_filtered_items = 0
for items, weight in weighted_transactions:
if weight <= 0:
continue
ordered = [item for item in items if item in frequent_items]
if not ordered:
continue
ordered.sort(key=lambda item: order_rank[item])
total_filtered_items += len(ordered) * weight
curr = root
for item in ordered:
child = curr.children.get(item)
if child is None:
child = FPNode(item=item, count=weight, parent=curr, children={})
curr.children[item] = child
n_tree_nodes += 1
if item not in header_heads:
header_heads[item] = child
header_tails[item] = child
else:
header_tails[item].node_link = child
header_tails[item] = child
else:
child.count += weight
curr = child
return _BuiltFPTree(
root=root,
f_list=f_list,
header_heads=header_heads,
n_tree_nodes=n_tree_nodes,
total_filtered_items=total_filtered_items,
)
def _extract_single_path(root: FPNode) -> list[FPNode] | None:
"""Return path nodes if the FP-Tree consists of a single unbranched chain, else None."""
path: list[FPNode] = []
curr = root
while True:
n_children = len(curr.children)
if n_children == 0:
return path
if n_children > 1:
return None
curr = next(iter(curr.children.values()))
path.append(curr)
def _mine_fp_tree(
tree: _BuiltFPTree,
suffix: frozenset[str],
min_support_count: int,
max_len: int | None,
results: dict[frozenset[str], int],
) -> None:
"""Recursively mine frequent patterns from an FP-Tree using bottom-up prefix projections."""
if not tree.f_list:
return
if max_len is not None and len(suffix) >= max_len:
return
single_path = _extract_single_path(tree.root)
if single_path is not None:
max_combo_len = len(single_path)
if max_len is not None:
max_combo_len = min(max_combo_len, max_len - len(suffix))
for r in range(1, max_combo_len + 1):
for combo in itertools.combinations(single_path, r):
pattern = suffix | frozenset(node.item for node in combo if node.item is not None)
support_count = min(node.count for node in combo)
if support_count >= min_support_count:
results[pattern] = support_count
return
for item, total_count in reversed(tree.f_list):
new_suffix = suffix | frozenset((item,))
results[new_suffix] = total_count
if max_len is not None and len(new_suffix) >= max_len:
continue
cond_patterns: list[tuple[tuple[str, ...], int]] = []
node = tree.header_heads.get(item)
while node is not None:
prefix_items: list[str] = []
anc = node.parent
while anc is not None and anc.item is not None:
prefix_items.append(anc.item)
anc = anc.parent
if prefix_items:
cond_patterns.append((tuple(prefix_items), node.count))
node = node.node_link
if cond_patterns:
cond_tree = _build_fp_tree(cond_patterns, min_support_count)
if cond_tree.f_list:
_mine_fp_tree(cond_tree, new_suffix, min_support_count, max_len, results)
def _format_sorted_itemsets(
raw_counts: dict[frozenset[str], int],
n_transactions: int,
) -> list[FrequentItemset]:
"""Convert raw itemset counts into deterministically sorted FrequentItemset records."""
itemsets = [
FrequentItemset(
items=items,
support_count=count,
support=count / n_transactions,
)
for items, count in raw_counts.items()
]
itemsets.sort(key=lambda fs: (len(fs.items), -fs.support_count, tuple(sorted(fs.items))))
return itemsets
def mine_frequent_itemsets_fpgrowth(
transactions: Sequence[Collection[str]],
min_support: float | None = 0.05,
min_support_count: int | None = None,
max_len: int | None = None,
) -> list[FrequentItemset]:
"""Mine all frequent itemsets using 2-scan FP-Growth without candidate generation.
Args:
transactions: Sequence of transaction item collections.
min_support: Relative minimum support ratio in (0, 1] when ``min_support_count`` is None.
min_support_count: Explicit minimum transaction count overriding ``min_support``.
max_len: Optional maximum itemset cardinality (>= 1).
Returns:
Deterministically sorted list of ``FrequentItemset``.
"""
if max_len is not None and max_len < 1:
raise ValueError(f"max_len must be >= 1 when provided, got {max_len}.")
baskets = [frozenset(t) for t in transactions]
n_transactions = len(baskets)
min_cnt = resolve_min_support_count(n_transactions, min_support, min_support_count)
weighted = [(basket, 1) for basket in baskets]
global_tree = _build_fp_tree(weighted, min_cnt)
raw_counts: dict[frozenset[str], int] = {}
_mine_fp_tree(global_tree, frozenset(), min_cnt, max_len, raw_counts)
return _format_sorted_itemsets(raw_counts, n_transactions)
def build_fpgrowth_summary(
transactions: Sequence[Collection[str]],
min_support: float | None = 0.05,
min_support_count: int | None = None,
) -> FPTreeSummary:
"""Build the global FP-Tree and return its prefix-compression diagnostics."""
baskets = [frozenset(t) for t in transactions]
n_transactions = len(baskets)
min_cnt = resolve_min_support_count(n_transactions, min_support, min_support_count)
weighted = [(basket, 1) for basket in baskets]
global_tree = _build_fp_tree(weighted, min_cnt)
compression_ratio = global_tree.total_filtered_items / max(global_tree.n_tree_nodes, 1)
return FPTreeSummary(
n_transactions=n_transactions,
min_support_count=min_cnt,
f_list=tuple(global_tree.f_list),
n_tree_nodes=global_tree.n_tree_nodes,
compression_ratio=compression_ratio,
)
def mine_frequent_itemsets_apriori(
transactions: Sequence[Collection[str]],
min_support: float | None = 0.05,
min_support_count: int | None = None,
max_len: int | None = None,
) -> list[FrequentItemset]:
"""Mine frequent itemsets via level-wise Apriori with downward-closure pruning.
Used as a ground-truth reference cross-check against FP-Growth.
"""
if max_len is not None and max_len < 1:
raise ValueError(f"max_len must be >= 1 when provided, got {max_len}.")
baskets = [frozenset(t) for t in transactions]
n_transactions = len(baskets)
min_cnt = resolve_min_support_count(n_transactions, min_support, min_support_count)
item_masks: dict[str, int] = defaultdict(int)
for tid, basket in enumerate(baskets):
bit = 1 << tid
for item in basket:
item_masks[item] |= bit
l1_items = sorted(
item for item, mask in item_masks.items() if mask.bit_count() >= min_cnt
)
if not l1_items:
return []
raw_counts: dict[frozenset[str], int] = {}
prev_level: list[tuple[str, ...]] = []
for item in l1_items:
cnt = item_masks[item].bit_count()
raw_counts[frozenset((item,))] = cnt
prev_level.append((item,))
k = 2
while prev_level and (max_len is None or k <= max_len):
prev_set = set(prev_level)
candidates: list[tuple[str, ...]] = []
n_prev = len(prev_level)
for i in range(n_prev):
left = prev_level[i]
for j in range(i + 1, n_prev):
right = prev_level[j]
if left[:-1] != right[:-1]:
break
cand = left + (right[-1],)
# Downward-closure check: all (k-1)-subsets must be frequent.
if all((cand[:idx] + cand[idx + 1 :]) in prev_set for idx in range(k)):
candidates.append(cand)
if not candidates:
break
next_level: list[tuple[str, ...]] = []
for cand in candidates:
combined_mask = functools.reduce(
operator.and_, (item_masks[item] for item in cand)
)
cnt = combined_mask.bit_count()
if cnt >= min_cnt:
raw_counts[frozenset(cand)] = cnt
next_level.append(cand)
prev_level = next_level
k += 1
return _format_sorted_itemsets(raw_counts, n_transactions)
def compute_twu_and_exact_utility(
transaction_df: pd.DataFrame,
itemsets: Sequence[frozenset[str]],
) -> dict[frozenset[str], tuple[float, float]]:
"""Compute exact utility ``u(X)`` and Transaction-Weighted Utilization ``TWU(X)``.
Args:
transaction_df: Line-item DataFrame containing ``transaction_id``, ``sku``,
and ``line_profit``.
itemsets: Candidate itemsets to evaluate.
Returns:
Mapping ``{itemset: (exact_utility, twu)}`` satisfying ``u(X) <= TWU(X)``
whenever all line profits are non-negative.
"""
required_cols = {"transaction_id", "sku", "line_profit"}
missing = required_cols - set(transaction_df.columns)
if missing:
raise ValueError(f"transaction_df missing required columns: {sorted(missing)}")
if not itemsets:
return {}
tx_item_profits: dict[int, dict[str, float]] = defaultdict(lambda: defaultdict(float))
tids = transaction_df["transaction_id"].to_numpy(dtype=np.int64).tolist()
skus = transaction_df["sku"].tolist()
profits = transaction_df["line_profit"].to_numpy(dtype=np.float64).tolist()
for tid, sku, profit in zip(tids, skus, profits):
tx_item_profits[tid][sku] += float(profit)
tx_utility: dict[int, float] = {}
sku_to_tids: dict[str, set[int]] = defaultdict(set)
for tid, item_map in tx_item_profits.items():
tx_utility[tid] = math.fsum(item_map.values())
for sku in item_map:
sku_to_tids[sku].add(tid)
all_tids = sorted(tx_utility.keys())
results: dict[frozenset[str], tuple[float, float]] = {}
for itemset in itemsets:
if not itemset:
results[itemset] = (0.0, float(math.fsum(tx_utility[t] for t in all_tids)))
continue
sorted_items = sorted(itemset)
tid_sets = [sku_to_tids.get(sku) for sku in sorted_items]
if any(ts is None or len(ts) == 0 for ts in tid_sets):
results[itemset] = (0.0, 0.0)
continue
matching_tids = sorted(set.intersection(*(ts for ts in tid_sets if ts is not None)))
if not matching_tids:
results[itemset] = (0.0, 0.0)
continue
exact_terms: list[float] = []
twu_terms: list[float] = []
for tid in matching_tids:
item_map = tx_item_profits[tid]
for sku in sorted_items:
exact_terms.append(item_map[sku])
twu_terms.append(tx_utility[tid])
results[itemset] = (float(math.fsum(exact_terms)), float(math.fsum(twu_terms)))
return results
"""Association rule interestingness metrics, exact log-space Fisher tests, and FDR control."""
from __future__ import annotations
import functools
import itertools
import math
import operator
from collections import defaultdict
from collections.abc import Collection, Mapping, Sequence
from dataclasses import dataclass
import numpy as np
from mba_lab.fpgrowth import FrequentItemset
from mba_lab.synthetic_retail import baskets_to_binary_matrix
@dataclass(frozen=True, slots=True)
class FisherExactResult:
"""Result of a one-sided right-tail Fisher hypergeometric exact test in log space."""
log_p_value: float
neg_log10_p: float
p_value: float
odds_ratio: float
@dataclass(frozen=True, slots=True)
class AssociationRule:
"""Scored and statistically tested directed association rule A -> B."""
antecedent: frozenset[str]
consequent: frozenset[str]
n_transactions: int
support_antecedent_count: int
support_consequent_count: int
support_both_count: int
support: float
confidence: float
lift: float
leverage: float
conviction: float
zhang: float
kulczynski: float
imbalance_ratio: float
log_p_value: float
p_value: float
q_value: float
holm_p_value: float
consequent_margin: float
expected_incremental_margin: float
is_significant: bool
is_substitute: bool
def log_binom(n: int, k: int) -> float:
"""Compute natural logarithm of binomial coefficient C(n, k) via math.lgamma."""
if n < 0:
raise ValueError(f"n must be >= 0, got {n}.")
if k < 0 or k > n:
return -math.inf
if k == 0 or k == n:
return 0.0
return math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
def logsumexp_1d(log_values: Sequence[float]) -> float:
"""Compute log(sum(exp(x))) stably, handling empty or all-(-inf) sequences."""
if not log_values:
return -math.inf
max_val = max(log_values)
if max_val == -math.inf:
return -math.inf
if max_val == math.inf:
return math.inf
shifted_sum = math.fsum(math.exp(v - max_val) for v in log_values if v > -math.inf)
return max_val + math.log(shifted_sum)
def fisher_exact_right_tail(
k: int,
count_a: int,
count_b: int,
n_total: int,
) -> FisherExactResult:
"""Evaluate exact right-tail Fisher hypergeometric test purely via stdlib log-gamma & LSE.
Tests enrichment ``Pr(X >= k | H0)`` without ``scipy`` and without ``float64``
underflow for extreme co-occurrences (``p < 1e-308``).
"""
if n_total < 1:
raise ValueError(f"n_total must be >= 1, got {n_total}.")
if not (0 <= count_a <= n_total) or not (0 <= count_b <= n_total):
raise ValueError(
f"Marginal counts must lie in [0, {n_total}]; got count_a={count_a}, count_b={count_b}."
)
k_min = max(0, count_a + count_b - n_total)
k_max = min(count_a, count_b)
if not (k_min <= k <= k_max):
raise ValueError(
f"Observed overlap k={k} outside valid hypergeometric support [{k_min}, {k_max}]."
)
a_cell = k
b_cell = count_a - k
c_cell = count_b - k
d_cell = n_total - count_a - count_b + k
bc_prod = b_cell * c_cell
ad_prod = a_cell * d_cell
if bc_prod == 0:
odds_ratio = math.inf if ad_prod > 0 else 0.0
else:
odds_ratio = ad_prod / bc_prod
if k == k_min:
return FisherExactResult(
log_p_value=0.0,
neg_log10_p=0.0,
p_value=1.0,
odds_ratio=odds_ratio,
)
ell = (
log_binom(count_a, k)
+ log_binom(n_total - count_a, count_b - k)
- log_binom(n_total, count_b)
)
log_probs = [ell]
for x in range(k, k_max):
ell += (
math.log(count_a - x)
+ math.log(count_b - x)
- math.log(x + 1)
- math.log(n_total - count_a - count_b + x + 1)
)
log_probs.append(ell)
log_p = min(0.0, logsumexp_1d(log_probs))
neg_log10_p = 0.0 if log_p == 0.0 else -log_p / math.log(10.0)
p_value = 1.0 if log_p == 0.0 else min(1.0, math.exp(log_p))
return FisherExactResult(
log_p_value=log_p,
neg_log10_p=neg_log10_p,
p_value=p_value,
odds_ratio=odds_ratio,
)
def _resolve_hypothesis_count(n_tested: int, total_hypotheses: int | None) -> int:
if total_hypotheses is None:
return n_tested
if total_hypotheses < 1:
raise ValueError(f"total_hypotheses must be >= 1 when provided, got {total_hypotheses}.")
return max(int(total_hypotheses), n_tested)
def benjamini_hochberg_log(
log_p_values: Sequence[float],
total_hypotheses: int | None = None,
) -> list[float]:
"""Compute exact step-up BH-FDR q-values in log-space, returning values in original order."""
n_tested = len(log_p_values)
if n_tested == 0:
return []
m = _resolve_hypothesis_count(n_tested, total_hypotheses)
cleaned_log_p: list[float] = []
for lp in log_p_values:
if math.isnan(lp) or lp > 1e-12:
raise ValueError(f"Invalid log_p_value encountered: {lp}.")
cleaned_log_p.append(min(0.0, float(lp)))
sorted_indices = sorted(range(n_tested), key=lambda idx: cleaned_log_p[idx])
log_m = math.log(m)
log_q_sorted = [0.0] * n_tested
running_min = 0.0
for rank_0 in range(n_tested - 1, -1, -1):
rank_1 = rank_0 + 1
orig_idx = sorted_indices[rank_0]
cand_log_q = log_m - math.log(rank_1) + cleaned_log_p[orig_idx]
running_min = min(running_min, cand_log_q)
log_q_sorted[rank_0] = running_min
q_values = [0.0] * n_tested
for rank_0, orig_idx in enumerate(sorted_indices):
lq = log_q_sorted[rank_0]
q_values[orig_idx] = 1.0 if lq >= 0.0 else min(1.0, math.exp(lq))
return q_values
def holm_bonferroni_log(
log_p_values: Sequence[float],
total_hypotheses: int | None = None,
) -> list[float]:
"""Compute exact step-down Holm-Bonferroni FWER adjusted p-values in log-space."""
n_tested = len(log_p_values)
if n_tested == 0:
return []
m = _resolve_hypothesis_count(n_tested, total_hypotheses)
cleaned_log_p: list[float] = []
for lp in log_p_values:
if math.isnan(lp) or lp > 1e-12:
raise ValueError(f"Invalid log_p_value encountered: {lp}.")
cleaned_log_p.append(min(0.0, float(lp)))
sorted_indices = sorted(range(n_tested), key=lambda idx: cleaned_log_p[idx])
log_adj_sorted = [0.0] * n_tested
running_max = -math.inf
for rank_0, orig_idx in enumerate(sorted_indices):
multiplier = m - rank_0
cand_log_adj = min(0.0, math.log(multiplier) + cleaned_log_p[orig_idx])
running_max = max(running_max, cand_log_adj)
log_adj_sorted[rank_0] = min(0.0, running_max)
adjusted = [0.0] * n_tested
for rank_0, orig_idx in enumerate(sorted_indices):
la = log_adj_sorted[rank_0]
adjusted[orig_idx] = 1.0 if la >= 0.0 else min(1.0, math.exp(la))
return adjusted
def compute_rule_metrics(
count_a: int,
count_b: int,
count_ab: int,
n_total: int,
) -> dict[str, float]:
"""Compute the 8 objective interestingness metrics for a rule A -> B."""
if n_total < 1:
raise ValueError(f"n_total must be >= 1, got {n_total}.")
if not (0 <= count_a <= n_total) or not (0 <= count_b <= n_total):
raise ValueError("count_a and count_b must lie in [0, n_total].")
k_min = max(0, count_a + count_b - n_total)
k_max = min(count_a, count_b)
if not (k_min <= count_ab <= k_max):
raise ValueError(f"count_ab={count_ab} outside valid range [{k_min}, {k_max}].")
p_a = count_a / n_total
p_b = count_b / n_total
p_ab = count_ab / n_total
support = p_ab
confidence = p_ab / p_a if count_a > 0 else 0.0
lift = p_ab / (p_a * p_b) if (count_a > 0 and count_b > 0) else 0.0
leverage = p_ab - (p_a * p_b)
if count_a == 0:
conviction = 1.0 - p_b
elif count_ab == count_a:
conviction = math.inf if count_b < n_total else 1.0
else:
conviction = (1.0 - p_b) / (1.0 - confidence)
zhang_num = p_ab - (p_a * p_b)
zhang_denom = max(p_ab * (1.0 - p_a), p_a * (p_b - p_ab))
if zhang_denom <= 1e-15:
zhang = 0.0
else:
zhang = max(-1.0, min(1.0, zhang_num / zhang_denom))
if count_a == 0 and count_b == 0:
kulczynski = 0.0
else:
term_a = (p_ab / p_a) if count_a > 0 else 0.0
term_b = (p_ab / p_b) if count_b > 0 else 0.0
kulczynski = max(0.0, min(1.0, 0.5 * (term_a + term_b)))
union_prob = p_a + p_b - p_ab
if union_prob <= 1e-15:
imbalance_ratio = 0.0
else:
imbalance_ratio = max(0.0, min(1.0, abs(p_a - p_b) / union_prob))
return {
"support": float(support),
"confidence": float(confidence),
"lift": float(lift),
"leverage": float(leverage),
"conviction": float(conviction),
"zhang": float(zhang),
"kulczynski": float(kulczynski),
"imbalance_ratio": float(imbalance_ratio),
}
def extract_and_test_rules(
frequent_itemsets: Sequence[FrequentItemset],
eval_transactions: Sequence[Collection[str]],
item_margins: Mapping[str, float] | None = None,
min_confidence: float = 0.1,
alpha: float = 0.05,
total_hypotheses: int | None = None,
single_consequent: bool = True,
filter_significant_only: bool = False,
train_transactions: Sequence[Collection[str]] | None = None,
) -> list[AssociationRule]:
"""Generate candidate rules from train frequent itemsets and test them on unseen baskets.
Train ``min_confidence`` filtering is applied strictly on the training split (via
``train_transactions`` when provided, otherwise from train ``support_count`` inside
``frequent_itemsets``) BEFORE generating candidate rules for holdout Fisher exact
testing and BH-FDR correction, ensuring the hypothesis count ``m`` is never shrunk
post-selection on ``eval_transactions``. Expected incremental margin is computed as
the true incremental lift margin ``(Pr(B | A) - Pr(B)) * m_B``.
"""
if not eval_transactions:
raise ValueError("eval_transactions must be non-empty.")
if not (0.0 <= min_confidence <= 1.0):
raise ValueError(f"min_confidence must lie in [0, 1], got {min_confidence}.")
if not (0.0 < alpha < 1.0):
raise ValueError(f"alpha must lie in (0, 1), got {alpha}.")
eval_baskets = [frozenset(t) for t in eval_transactions]
n_eval = len(eval_baskets)
def _build_count_fn(baskets: list[frozenset[str]]):
masks_map: dict[str, int] = defaultdict(int)
for tid, basket in enumerate(baskets):
bit = 1 << tid
for item in basket:
masks_map[item] |= bit
cache: dict[frozenset[str], int] = {}
def _get_count(subset: frozenset[str]) -> int:
cached = cache.get(subset)
if cached is not None:
return cached
masks = [masks_map.get(item, 0) for item in subset]
if not masks or any(m == 0 for m in masks):
cnt = 0
else:
cnt = functools.reduce(operator.and_, masks).bit_count()
cache[subset] = cnt
return cnt
return _get_count
get_eval_count = _build_count_fn(eval_baskets)
train_itemset_counts: dict[frozenset[str], int] = {
fs.items: fs.support_count for fs in frequent_itemsets
}
get_train_count = (
_build_count_fn([frozenset(t) for t in train_transactions])
if train_transactions is not None
else None
)
def _passes_train_min_confidence(
antecedent: frozenset[str], full_items: frozenset[str], full_train_count: int
) -> bool:
if min_confidence <= 0.0:
return True
if get_train_count is not None:
c_tr_a = get_train_count(antecedent)
if c_tr_a <= 0:
return False
return (get_train_count(full_items) / c_tr_a) >= min_confidence
c_tr_a = train_itemset_counts.get(antecedent)
if c_tr_a is None:
# Antecedent support unavailable on train; keep candidate unfiltered to avoid holdout peeking.
return True
if c_tr_a <= 0:
return False
return (full_train_count / c_tr_a) >= min_confidence
candidate_pairs_set: set[tuple[frozenset[str], frozenset[str]]] = set()
for fs in frequent_itemsets:
if len(fs.items) < 2:
continue
sorted_items = sorted(fs.items)
if single_consequent:
for item in sorted_items:
consequent = frozenset((item,))
antecedent = fs.items - consequent
if _passes_train_min_confidence(antecedent, fs.items, fs.support_count):
candidate_pairs_set.add((antecedent, consequent))
else:
for r in range(1, len(sorted_items)):
for cons_tuple in itertools.combinations(sorted_items, r):
consequent = frozenset(cons_tuple)
antecedent = fs.items - consequent
if _passes_train_min_confidence(antecedent, fs.items, fs.support_count):
candidate_pairs_set.add((antecedent, consequent))
candidate_pairs = sorted(
candidate_pairs_set,
key=lambda pair: (tuple(sorted(pair[0])), tuple(sorted(pair[1]))),
)
surviving: list[tuple[frozenset[str], frozenset[str], int, int, int, dict[str, float], FisherExactResult]] = []
for antecedent, consequent in candidate_pairs:
c_a = get_eval_count(antecedent)
c_b = get_eval_count(consequent)
c_ab = get_eval_count(antecedent | consequent)
metrics = compute_rule_metrics(c_a, c_b, c_ab, n_eval)
fisher_res = fisher_exact_right_tail(c_ab, c_a, c_b, n_eval)
surviving.append((antecedent, consequent, c_a, c_b, c_ab, metrics, fisher_res))
if not surviving:
return []
log_p_values = [item[6].log_p_value for item in surviving]
q_values = benjamini_hochberg_log(log_p_values, total_hypotheses=total_hypotheses)
holm_values = holm_bonferroni_log(log_p_values, total_hypotheses=total_hypotheses)
rules: list[AssociationRule] = []
for idx, (antecedent, consequent, c_a, c_b, c_ab, metrics, fisher_res) in enumerate(surviving):
q_val = q_values[idx]
holm_val = holm_values[idx]
if item_margins is None:
cons_margin = float(len(consequent))
else:
cons_margin = float(math.fsum(item_margins.get(sku, 1.0) for sku in consequent))
p_b = c_b / n_eval
exp_inc_margin = (metrics["confidence"] - p_b) * cons_margin
is_sig = (q_val <= alpha) and (metrics["zhang"] > 0.0)
is_sub = metrics["zhang"] < 0.0
if filter_significant_only and not is_sig:
continue
rules.append(
AssociationRule(
antecedent=antecedent,
consequent=consequent,
n_transactions=n_eval,
support_antecedent_count=c_a,
support_consequent_count=c_b,
support_both_count=c_ab,
support=metrics["support"],
confidence=metrics["confidence"],
lift=metrics["lift"],
leverage=metrics["leverage"],
conviction=metrics["conviction"],
zhang=metrics["zhang"],
kulczynski=metrics["kulczynski"],
imbalance_ratio=metrics["imbalance_ratio"],
log_p_value=fisher_res.log_p_value,
p_value=fisher_res.p_value,
q_value=q_val,
holm_p_value=holm_val,
consequent_margin=cons_margin,
expected_incremental_margin=exp_inc_margin,
is_significant=is_sig,
is_substitute=is_sub,
)
)
rules.sort(
key=lambda r: (
r.q_value,
r.log_p_value,
-r.expected_incremental_margin,
-r.zhang,
tuple(sorted(r.antecedent)),
tuple(sorted(r.consequent)),
)
)
return rules
def find_substitute_pairs(
transactions: Sequence[Collection[str]],
min_marginal_support: float = 0.01,
max_zhang: float = -0.25,
) -> list[tuple[str, str, float]]:
"""Detect mutually exclusive or negatively associated SKU pairs via vectorized B^T B.
Scans all frequent item pairs—including zero co-occurrence pairs invisible to
FP-Growth—and returns ``[(sku_a, sku_b, min_directional_zhang), ...]``.
"""
if not transactions:
raise ValueError("transactions must be non-empty.")
if not (0.0 < min_marginal_support <= 1.0):
raise ValueError(
f"min_marginal_support must lie in (0, 1], got {min_marginal_support}."
)
if not (-1.0 <= max_zhang <= 1.0):
raise ValueError(f"max_zhang must lie in [-1, 1], got {max_zhang}.")
mat_u8, vocab = baskets_to_binary_matrix(transactions)
n_total, n_items = mat_u8.shape
if n_items < 2:
return []
x64 = np.ascontiguousarray(mat_u8, dtype=np.float64)
cooc = x64.T @ x64
diag = np.diag(cooc)
min_count = max(1, math.ceil(min_marginal_support * n_total))
freq_indices = [idx for idx in range(n_items) if round(diag[idx]) >= min_count]
substitutes: list[tuple[str, str, float]] = []
for pos_i in range(len(freq_indices)):
i = freq_indices[pos_i]
c_i = round(diag[i])
for pos_j in range(pos_i + 1, len(freq_indices)):
j = freq_indices[pos_j]
c_j = round(diag[j])
c_ij = round(cooc[i, j])
z_ij = compute_rule_metrics(c_i, c_j, c_ij, n_total)["zhang"]
z_ji = compute_rule_metrics(c_j, c_i, c_ij, n_total)["zhang"]
min_zhang = min(z_ij, z_ji)
if min_zhang <= max_zhang:
substitutes.append((vocab[i], vocab[j], float(min_zhang)))
substitutes.sort(key=lambda item: (item[2], item[0], item[1]))
return substitutes
"""CPython vs. NumPy/Pandas/Polars memory layout benchmarks, BLAS matmul, and stride audits."""
from __future__ import annotations
import sys
import time
from collections.abc import Callable
from dataclasses import dataclass
import numpy as np
import pandas as pd
@dataclass(frozen=True, slots=True)
class MemoryAndSpeedResult:
"""Measured footprint, runtime latency, throughput, and checksum for one execution backend."""
backend_name: str
n_elements: int
theoretical_payload_bytes: int
measured_object_bytes: int
bytes_per_element: float
elapsed_ms: float
throughput_melems_per_sec: float
checksum: float
@dataclass(frozen=True, slots=True)
class ViewAuditResult:
"""Audit flags verifying NumPy zero-copy views, forced copies, and stride=0 broadcasting."""
slice_is_view: bool
transpose_is_view: bool
fancy_index_is_copy: bool
non_contiguous_reshape_is_copy: bool
broadcast_strides: tuple[int, int]
def has_polars() -> bool:
"""Safely probe whether optional ``polars`` dependency is importable."""
try:
import polars # noqa: F401
return True
except ImportError:
return False
def estimate_python_float_list_bytes(values: list[float]) -> int:
"""Estimate total heap memory (bytes) of a Python ``list[float]``.
Sums ``sys.getsizeof(values)`` (the 56-byte ``PyListObject`` header plus the
8-byte-per-slot ``ob_item`` pointer array) and ``sys.getsizeof(v)`` for each
heap-allocated 24-byte ``PyFloatObject``.
"""
return sys.getsizeof(values) + sum(sys.getsizeof(v) for v in values)
def _time_callable(fn: Callable[[], float], repeats: int) -> tuple[float, float]:
"""Measure best elapsed seconds across ``repeats`` invocations and return ``(best_sec, result)``."""
best_sec = float("inf")
last_val = 0.0
for _ in range(repeats):
start = time.perf_counter()
last_val = fn()
elapsed = time.perf_counter() - start
best_sec = min(best_sec, elapsed)
return max(best_sec, 1e-9), float(last_val)
def benchmark_vector_scale_and_sum(
n_elements: int = 500_000,
repeats: int = 3,
seed: int = 42,
) -> list[MemoryAndSpeedResult]:
"""Benchmark ``sum(1.75 * x + 0.25 * w)`` and RAM footprint across Python, Pandas, NumPy, and optional Polars."""
if n_elements < 1:
raise ValueError(f"n_elements must be >= 1, got {n_elements}.")
if repeats < 1:
raise ValueError(f"repeats must be >= 1, got {repeats}.")
rng = np.random.default_rng(seed)
x = np.ascontiguousarray(rng.normal(0.0, 1.0, size=n_elements), dtype=np.float64)
w = np.ascontiguousarray(rng.normal(0.0, 1.0, size=n_elements), dtype=np.float64)
n_scalars = 2 * n_elements
theoretical_bytes = n_scalars * 8
results: list[MemoryAndSpeedResult] = []
# 1. Pure-Python boxed list[float] loop
x_list = x.tolist()
w_list = w.tolist()
py_bytes = estimate_python_float_list_bytes(x_list) + estimate_python_float_list_bytes(w_list)
def _run_python() -> float:
total = 0.0
for xi, wi in zip(x_list, w_list):
total += 1.75 * xi + 0.25 * wi
return total
py_sec, py_sum = _time_callable(_run_python, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="python_list_float",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=py_bytes,
bytes_per_element=py_bytes / n_scalars,
elapsed_ms=py_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / py_sec,
checksum=py_sum,
)
)
# 2. Pandas DataFrame float64 columns
df = pd.DataFrame({"x": x, "w": w})
pd_bytes = int(df.memory_usage(index=True, deep=True).sum())
def _run_pandas() -> float:
return float((1.75 * df["x"] + 0.25 * df["w"]).sum())
pd_sec, pd_sum = _time_callable(_run_pandas, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="pandas_dataframe_float64",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=pd_bytes,
bytes_per_element=pd_bytes / n_scalars,
elapsed_ms=pd_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / pd_sec,
checksum=pd_sum,
)
)
# 3. Contiguous NumPy float64 SIMD reduction
np_bytes = int(sys.getsizeof(x) + sys.getsizeof(w))
def _run_numpy() -> float:
return float(np.sum(1.75 * x + 0.25 * w))
np_sec, np_sum = _time_callable(_run_numpy, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="numpy_float64_contiguous",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=np_bytes,
bytes_per_element=np_bytes / n_scalars,
elapsed_ms=np_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / np_sec,
checksum=np_sum,
)
)
# 4. Optional Polars Series
if has_polars():
import polars as pl
s_x = pl.Series("x", x)
s_w = pl.Series("w", w)
pl_bytes = int(s_x.estimated_size() + s_w.estimated_size())
def _run_polars() -> float:
return float((1.75 * s_x + 0.25 * s_w).sum())
pl_sec, pl_sum = _time_callable(_run_polars, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="polars_series_float64",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=pl_bytes,
bytes_per_element=pl_bytes / n_scalars,
elapsed_ms=pl_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / pl_sec,
checksum=pl_sum,
)
)
return results
def benchmark_cooccurrence_engines(
basket_matrix_uint8: np.ndarray,
repeats: int = 3,
) -> list[MemoryAndSpeedResult]:
"""Benchmark exact pairwise co-occurrence matrix ``C = B^T B`` across execution engines."""
if basket_matrix_uint8.ndim != 2:
raise ValueError(
f"basket_matrix_uint8 must be 2D, got shape {basket_matrix_uint8.shape}."
)
n_rows, n_cols = basket_matrix_uint8.shape
if n_rows < 1 or n_cols < 1:
raise ValueError(f"basket_matrix_uint8 must be non-empty, got shape {basket_matrix_uint8.shape}.")
if repeats < 1:
raise ValueError(f"repeats must be >= 1, got {repeats}.")
n_elements = int(basket_matrix_uint8.size)
theoretical_bytes = n_elements
results: list[MemoryAndSpeedResult] = []
# 1. Pure-Python nested basket loops
baskets = [tuple(np.flatnonzero(row).tolist()) for row in basket_matrix_uint8]
py_bytes = sys.getsizeof(baskets) + sum(
sys.getsizeof(b) + sum(sys.getsizeof(elem) for elem in b) for b in baskets
)
def _run_py_cooc() -> float:
cooc = [[0] * n_cols for _ in range(n_cols)]
for items in baskets:
n_active = len(items)
for i_idx in range(n_active):
u = items[i_idx]
row_u = cooc[u]
row_u[u] += 1
for j_idx in range(i_idx + 1, n_active):
v = items[j_idx]
row_u[v] += 1
cooc[v][u] += 1
return float(sum(sum(row) for row in cooc))
py_sec, py_chk = _time_callable(_run_py_cooc, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="python_nested_basket_loops",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=py_bytes,
bytes_per_element=py_bytes / n_elements,
elapsed_ms=py_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / py_sec,
checksum=py_chk,
)
)
# 2. Pandas DataFrame matrix multiplication
df = pd.DataFrame(basket_matrix_uint8.astype(np.float64))
pd_bytes = int(df.memory_usage(index=True, deep=True).sum())
def _run_pd_cooc() -> float:
cooc_df = df.T @ df
return float(cooc_df.to_numpy().sum())
pd_sec, pd_chk = _time_callable(_run_pd_cooc, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="pandas_dataframe_dot",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=pd_bytes,
bytes_per_element=pd_bytes / n_elements,
elapsed_ms=pd_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / pd_sec,
checksum=pd_chk,
)
)
# 3. Contiguous NumPy BLAS matmul (X^T @ X)
x64 = np.ascontiguousarray(basket_matrix_uint8, dtype=np.float64)
np_bytes = int(sys.getsizeof(x64))
def _run_np_cooc() -> float:
cooc = x64.T @ x64
return float(np.sum(cooc))
np_sec, np_chk = _time_callable(_run_np_cooc, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="numpy_blas_matmul",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=np_bytes,
bytes_per_element=np_bytes / n_elements,
elapsed_ms=np_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / np_sec,
checksum=np_chk,
)
)
# 4. Optional Polars co-occurrence engine
if has_polars():
import polars as pl
pl_df = pl.DataFrame(
{f"c{idx}": x64[:, idx] for idx in range(n_cols)}
)
pl_bytes = int(pl_df.estimated_size())
def _run_pl_cooc() -> float:
arr = pl_df.to_numpy()
return float(np.sum(arr.T @ arr))
pl_sec, pl_chk = _time_callable(_run_pl_cooc, repeats)
results.append(
MemoryAndSpeedResult(
backend_name="polars_cooccurrence",
n_elements=n_elements,
theoretical_payload_bytes=theoretical_bytes,
measured_object_bytes=pl_bytes,
bytes_per_element=pl_bytes / n_elements,
elapsed_ms=pl_sec * 1000.0,
throughput_melems_per_sec=(n_elements / 1e6) / pl_sec,
checksum=pl_chk,
)
)
return results
def audit_numpy_views_and_strides() -> ViewAuditResult:
"""Programmatically verify NumPy view aliasing, forced copies, and stride=0 broadcasting."""
a = np.arange(24, dtype=np.float64).reshape(4, 6)
sl = a[:, ::2]
tr = a.T
fancy = a[[0, 2], :]
non_contig_flat = tr.reshape(-1)
xb, yb = np.broadcast_arrays(np.ones((3, 1)), np.ones((1, 4)))
return ViewAuditResult(
slice_is_view=bool(np.shares_memory(a, sl)),
transpose_is_view=bool(np.shares_memory(a, tr)),
fancy_index_is_copy=not bool(np.shares_memory(a, fancy)),
non_contiguous_reshape_is_copy=not bool(np.shares_memory(a, non_contig_flat)),
broadcast_strides=(int(xb.strides[1]), int(yb.strides[0])),
)
"""End-to-end CLI verification demo for Lab 01: Market Basket Analysis & DS Python Memory Architecture."""
from __future__ import annotations
import argparse
import json
import math
import sys
from dataclasses import asdict
from pathlib import Path
from typing import Any
try:
import mba_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from mba_lab.fpgrowth import (
build_fpgrowth_summary,
compute_twu_and_exact_utility,
mine_frequent_itemsets_apriori,
mine_frequent_itemsets_fpgrowth,
)
from mba_lab.memory_benchmark import (
audit_numpy_views_and_strides,
benchmark_cooccurrence_engines,
benchmark_vector_scale_and_sum,
has_polars,
)
from mba_lab.rules_and_significance import (
compute_rule_metrics,
extract_and_test_rules,
find_substitute_pairs,
)
from mba_lab.synthetic_retail import (
baskets_to_binary_matrix,
generate_synthetic_retail_baskets,
temporal_train_holdout_split,
)
TOY_TEXTBOOK_TRANSACTIONS: tuple[frozenset[str], ...] = (
frozenset({"a", "b", "c", "e"}),
frozenset({"a", "b", "d"}),
frozenset({"b", "c", "e"}),
frozenset({"a", "b", "c", "f"}),
frozenset({"a", "c", "e"}),
frozenset({"b", "d"}),
)
def _sanitize_json_value(value: Any) -> Any:
"""Convert non-JSON-native types (frozenset, float inf/nan) safely."""
if isinstance(value, float):
if math.isinf(value):
return "inf" if value > 0 else "-inf"
if math.isnan(value):
return "nan"
return value
if isinstance(value, (frozenset, set, tuple)):
return [_sanitize_json_value(v) for v in (sorted(value) if isinstance(value, (frozenset, set)) else value)]
if isinstance(value, list):
return [_sanitize_json_value(v) for v in value]
if isinstance(value, dict):
return {str(k): _sanitize_json_value(v) for k, v in value.items()}
return value
def _format_rule_items(items: frozenset[str]) -> str:
return "{" + ", ".join(sorted(items)) + "}"
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for the Market Basket Analysis lab demonstration."""
parser = argparse.ArgumentParser(
description="Run Lab 01: Memory Benchmarks, FP-Growth/Apriori Cross-Check, Holdout Fisher+BH-FDR, and Substitute Quarantine."
)
parser.add_argument("--n-transactions", type=int, default=4000)
parser.add_argument("--train-fraction", type=float, default=0.5)
parser.add_argument("--min-support", type=float, default=0.02)
parser.add_argument("--min-confidence", type=float, default=0.15)
parser.add_argument("--alpha", type=float, default=0.05)
parser.add_argument("--n-bench", type=int, default=200000)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--json-out", type=str, default=None)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Run all four sections of the Lab 01 demonstration and optional JSON export."""
args = parse_args(argv)
# Generate synthetic retail baskets once so both Section 1 (cooc) and Section 3/4 share data.
dataset = generate_synthetic_retail_baskets(
n_transactions=args.n_transactions,
seed=args.seed,
)
basket_matrix_u8, vocab = baskets_to_binary_matrix(dataset.transactions)
# [1] Memory & Vectorization Benchmark
print("=" * 80)
print("[1] Memory & Vectorization Benchmark")
print("=" * 80)
print(f"Optional polars installed: {has_polars()}")
vec_results = benchmark_vector_scale_and_sum(
n_elements=args.n_bench, repeats=3, seed=args.seed
)
print(f"Vector scale-and-sum (n_elements={args.n_bench}, 2 float64 arrays):")
for res in vec_results:
mb = res.measured_object_bytes / (1024 * 1024)
print(
f" - {res.backend_name:26s} | {res.bytes_per_element:6.2f} B/elem | "
f"{mb:7.3f} MB | {res.elapsed_ms:8.3f} ms | "
f"{res.throughput_melems_per_sec:8.2f} M elems/s | chk={res.checksum:.6f}"
)
view_audit = audit_numpy_views_and_strides()
print(
"NumPy View & Stride Audit: "
f"slice_is_view={view_audit.slice_is_view}, "
f"transpose_is_view={view_audit.transpose_is_view}, "
f"fancy_index_is_copy={view_audit.fancy_index_is_copy}, "
f"non_contiguous_reshape_is_copy={view_audit.non_contiguous_reshape_is_copy}, "
f"broadcast_strides={view_audit.broadcast_strides}"
)
cooc_results = benchmark_cooccurrence_engines(basket_matrix_u8, repeats=3)
print(f"Co-occurrence matrix C = B^T B (shape={basket_matrix_u8.shape}, vocab={len(vocab)}):")
for res in cooc_results:
print(
f" - {res.backend_name:26s} | {res.bytes_per_element:6.2f} B/elem | "
f"{res.elapsed_ms:8.3f} ms | chk={res.checksum:.1f}"
)
# [2] Worked 6-Transaction Textbook Cross-Check
print("\n" + "=" * 80)
print("[2] Worked 6-Transaction Textbook Cross-Check")
print("=" * 80)
toy_fp = mine_frequent_itemsets_fpgrowth(TOY_TEXTBOOK_TRANSACTIONS, min_support_count=2)
toy_ap = mine_frequent_itemsets_apriori(TOY_TEXTBOOK_TRANSACTIONS, min_support_count=2)
toy_summary = build_fpgrowth_summary(TOY_TEXTBOOK_TRANSACTIONS, min_support_count=2)
fp_pairs = {(fs.items, fs.support_count) for fs in toy_fp}
ap_pairs = {(fs.items, fs.support_count) for fs in toy_ap}
if fp_pairs != ap_pairs or len(toy_fp) != 15:
raise RuntimeError(
f"Textbook cross-check mismatch: len(fp)={len(toy_fp)}, len(ap)={len(toy_ap)}"
)
size_counts = {k: sum(1 for fs in toy_fp if len(fs.items) == k) for k in (1, 2, 3)}
print(f"f_list (descending): {list(toy_summary.f_list)}")
print(
f"FP-Tree non-root nodes: {toy_summary.n_tree_nodes} | "
f"compression_ratio={toy_summary.compression_ratio:.3f}"
)
print(
f"FP-Growth == Apriori verified: {len(toy_fp)} itemsets "
f"(size-1={size_counts[1]}, size-2={size_counts[2]}, size-3={size_counts[3]})"
)
toy_db_metrics = compute_rule_metrics(count_a=2, count_b=5, count_ab=2, n_total=6)
toy_de_metrics = compute_rule_metrics(count_a=2, count_b=3, count_ab=0, n_total=6)
print(
"Sample metrics: "
f"{{d}}->{{b}} conf={toy_db_metrics['confidence']:.3f}, lift={toy_db_metrics['lift']:.3f}, "
f"zhang={toy_db_metrics['zhang']:.3f}, kulc={toy_db_metrics['kulczynski']:.3f}, "
f"IR={toy_db_metrics['imbalance_ratio']:.3f}; "
f"{{d}}->{{e}} zhang={toy_de_metrics['zhang']:.3f}"
)
# [3] Leakage-Free Synthetic Retail MBA (Train Mine -> Holdout Fisher + BH-FDR)
print("\n" + "=" * 80)
print("[3] Leakage-Free Synthetic Retail MBA (Train Mine -> Holdout Fisher + BH-FDR)")
print("=" * 80)
train_tx, holdout_tx = temporal_train_holdout_split(
dataset, train_fraction=args.train_fraction
)
train_summary = build_fpgrowth_summary(train_tx, min_support=args.min_support)
train_itemsets = mine_frequent_itemsets_fpgrowth(train_tx, min_support=args.min_support)
item_margins = {sku: spec.unit_margin for sku, spec in dataset.item_specs.items()}
all_rules = extract_and_test_rules(
frequent_itemsets=train_itemsets,
eval_transactions=holdout_tx,
item_margins=item_margins,
min_confidence=args.min_confidence,
alpha=args.alpha,
single_consequent=True,
filter_significant_only=False,
)
sig_rules = [r for r in all_rules if r.is_significant]
sig_by_margin = sorted(
sig_rules,
key=lambda r: (
-r.expected_incremental_margin,
r.q_value,
r.log_p_value,
tuple(sorted(r.antecedent)),
tuple(sorted(r.consequent)),
),
)
print(
f"Split sizes: train={len(train_tx)}, holdout={len(holdout_tx)} | "
f"train min_supp_cnt={train_summary.min_support_count} | "
f"FP-Tree nodes={train_summary.n_tree_nodes} (compression={train_summary.compression_ratio:.2f}x)"
)
print(
f"Mined train frequent itemsets={len(train_itemsets)} | "
f"Holdout candidate rules={len(all_rules)} | Significant complements (q<={args.alpha}, zhang>0)={len(sig_rules)}"
)
print("Top significant complementary rules (sorted by expected incremental margin):")
for rule in sig_by_margin[:8]:
print(
f" {_format_rule_items(rule.antecedent)} -> {_format_rule_items(rule.consequent):18s} | "
f"supp={rule.support:.3f} conf={rule.confidence:.3f} zhang={rule.zhang:+.3f} "
f"log_p={rule.log_p_value:8.2f} q={rule.q_value:.3e} exp_margin=${rule.expected_incremental_margin:.2f}"
)
n_total_tx = len(dataset.transactions)
print("Banana Trap diagnostic (high-prevalence staples vs. planted accessories):")
for sku in dataset.staple_skus:
marg_supp = sum(1 for basket in dataset.transactions if sku in basket) / n_total_tx
staple_rules = [r for r in all_rules if r.consequent == frozenset({sku})]
best_q = min((r.q_value for r in staple_rules), default=1.0)
max_exp_m = max((r.expected_incremental_margin for r in staple_rules), default=0.0)
max_z = max((r.zhang for r in staple_rules), default=0.0)
print(
f" - staple={sku:14s} | marginal_supp={marg_supp:.3f} | unit_margin=${item_margins[sku]:.2f} | "
f"cand_rules={len(staple_rules):2d} | min_q={best_q:.3f} | max_zhang={max_z:+.3f} | "
f"max_exp_margin=${max_exp_m:.2f}"
)
twu_targets = [
frozenset({"banana"}),
frozenset({"gaming_laptop", "usb_c_dock"}),
frozenset({"espresso_maker", "espresso_beans"}),
]
twu_map = compute_twu_and_exact_utility(dataset.transaction_df, twu_targets)
print("HUIM Exact Utility u(X) vs. TWU(X) sample:")
for itemset in twu_targets:
exact_u, twu_val = twu_map[itemset]
print(
f" - {_format_rule_items(itemset):34s} | u(X)=${exact_u:10.2f} <= TWU(X)=${twu_val:10.2f}"
)
# [4] Substitute Pair Quarantine (Negative Zhang via Vectorized B^T B)
print("\n" + "=" * 80)
print("[4] Substitute Pair Quarantine (Negative Zhang via Vectorized B^T B)")
print("=" * 80)
substitutes = find_substitute_pairs(
dataset.transactions, min_marginal_support=0.05, max_zhang=-0.25
)
print(
f"Detected frequent substitute pairs (min_marginal_support=0.05, zhang <= -0.25): "
f"{len(substitutes)}"
)
for sku_a, sku_b, min_zhang in substitutes:
role_a = dataset.item_specs[sku_a].role
role_b = dataset.item_specs[sku_b].role
print(
f" - QUARANTINED: ({sku_a}, {sku_b}) | roles=({role_a}, {role_b}) | "
f"min_directional_zhang={min_zhang:+.4f}"
)
if args.json_out is not None:
out_path = Path(args.json_out)
out_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"config": vars(args),
"has_polars": has_polars(),
"vector_benchmarks": [asdict(r) for r in vec_results],
"cooccurrence_benchmarks": [asdict(r) for r in cooc_results],
"view_audit": asdict(view_audit),
"textbook_cross_check": {
"n_itemsets": len(toy_fp),
"size_counts": size_counts,
"f_list": toy_summary.f_list,
"compression_ratio": toy_summary.compression_ratio,
},
"retail_mba": {
"n_train": len(train_tx),
"n_holdout": len(holdout_tx),
"n_frequent_itemsets_train": len(train_itemsets),
"n_candidate_rules_holdout": len(all_rules),
"n_significant_complements": len(sig_rules),
"top_significant_rules": [asdict(r) for r in sig_by_margin[:15]],
"staple_skus": list(dataset.staple_skus),
"twu_sample": {
_format_rule_items(k): {"exact_utility": v[0], "twu": v[1]}
for k, v in twu_map.items()
},
},
"substitute_pairs": [
{"sku_a": a, "sku_b": b, "min_directional_zhang": z}
for a, b, z in substitutes
],
}
out_path.write_text(
json.dumps(_sanitize_json_value(payload), indent=2),
encoding="utf-8",
)
print(f"\nSaved structured JSON report to: {out_path}")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""Comprehensive pytest verification suite for mba_lab (14 locked contract tests)."""
from __future__ import annotations
import ast
import math
import os
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from mba_lab.fpgrowth import (
build_fpgrowth_summary,
compute_twu_and_exact_utility,
mine_frequent_itemsets_apriori,
mine_frequent_itemsets_fpgrowth,
)
from mba_lab.memory_benchmark import (
audit_numpy_views_and_strides,
benchmark_cooccurrence_engines,
benchmark_vector_scale_and_sum,
)
from mba_lab.rules_and_significance import (
benjamini_hochberg_log,
compute_rule_metrics,
extract_and_test_rules,
find_substitute_pairs,
fisher_exact_right_tail,
holm_bonferroni_log,
)
from mba_lab.synthetic_retail import (
generate_synthetic_retail_baskets,
temporal_train_holdout_split,
)
TOY_TRANSACTIONS: tuple[frozenset[str], ...] = (
frozenset({"a", "b", "c", "e"}),
frozenset({"a", "b", "d"}),
frozenset({"b", "c", "e"}),
frozenset({"a", "b", "c", "f"}),
frozenset({"a", "c", "e"}),
frozenset({"b", "d"}),
)
def test_toy_example_fpgrowth_matches_apriori_exact_15_itemsets() -> None:
fp_res = mine_frequent_itemsets_fpgrowth(TOY_TRANSACTIONS, min_support_count=2)
ap_res = mine_frequent_itemsets_apriori(TOY_TRANSACTIONS, min_support_count=2)
assert len(fp_res) == 15
assert sum(1 for fs in fp_res if len(fs.items) == 1) == 5
assert sum(1 for fs in fp_res if len(fs.items) == 2) == 7
assert sum(1 for fs in fp_res if len(fs.items) == 3) == 3
fp_set = {(fs.items, fs.support_count) for fs in fp_res}
ap_set = {(fs.items, fs.support_count) for fs in ap_res}
assert fp_set == ap_set
def test_fpgrowth_apriori_equivalence_on_synthetic_sample() -> None:
dataset = generate_synthetic_retail_baskets(n_transactions=300, seed=7)
fp_res = mine_frequent_itemsets_fpgrowth(
dataset.transactions, min_support=0.05, max_len=3
)
ap_res = mine_frequent_itemsets_apriori(
dataset.transactions, min_support=0.05, max_len=3
)
assert len(fp_res) > 0
fp_set = {(fs.items, fs.support_count) for fs in fp_res}
ap_set = {(fs.items, fs.support_count) for fs in ap_res}
assert fp_set == ap_set
def test_fpgrowth_tree_compression_summary() -> None:
summary = build_fpgrowth_summary(TOY_TRANSACTIONS, min_support_count=2)
assert summary.n_transactions == 6
assert summary.min_support_count == 2
assert summary.f_list == (("b", 5), ("a", 4), ("c", 4), ("e", 3), ("d", 2))
assert summary.n_tree_nodes == 11
assert summary.compression_ratio >= 1.0
dataset = generate_synthetic_retail_baskets(n_transactions=500, seed=11)
synth_summary = build_fpgrowth_summary(dataset.transactions, min_support=0.05)
counts = [cnt for _, cnt in synth_summary.f_list]
assert counts == sorted(counts, reverse=True)
assert synth_summary.compression_ratio >= 1.0
def test_interestingness_measures_and_zhang_bounds() -> None:
db_metrics = compute_rule_metrics(count_a=2, count_b=5, count_ab=2, n_total=6)
assert db_metrics["support"] == pytest.approx(1.0 / 3.0)
assert db_metrics["confidence"] == pytest.approx(1.0)
assert db_metrics["lift"] == pytest.approx(1.2)
assert db_metrics["leverage"] == pytest.approx(1.0 / 18.0)
assert db_metrics["conviction"] == math.inf
assert db_metrics["zhang"] == pytest.approx(0.25)
assert db_metrics["kulczynski"] == pytest.approx(0.7)
assert db_metrics["imbalance_ratio"] == pytest.approx(0.6)
de_metrics = compute_rule_metrics(count_a=2, count_b=3, count_ab=0, n_total=6)
assert de_metrics["zhang"] == pytest.approx(-1.0)
assert de_metrics["conviction"] == pytest.approx(0.5)
n_total = 20
for count_a in range(0, n_total + 1, 4):
for count_b in range(0, n_total + 1, 4):
k_min = max(0, count_a + count_b - n_total)
k_max = min(count_a, count_b)
for count_ab in range(k_min, k_max + 1):
m = compute_rule_metrics(count_a, count_b, count_ab, n_total)
assert -1.0 <= m["zhang"] <= 1.0
assert 0.0 <= m["kulczynski"] <= 1.0
assert 0.0 <= m["imbalance_ratio"] <= 1.0
def test_fisher_exact_reference_values_and_no_underflow() -> None:
res_4 = fisher_exact_right_tail(k=4, count_a=4, count_b=4, n_total=8)
assert res_4.p_value == pytest.approx(1.0 / 70.0, rel=1e-12)
assert res_4.odds_ratio == math.inf
res_3 = fisher_exact_right_tail(k=3, count_a=4, count_b=4, n_total=8)
assert res_3.p_value == pytest.approx(17.0 / 70.0, rel=1e-12)
res_0 = fisher_exact_right_tail(k=0, count_a=4, count_b=4, n_total=8)
assert res_0.p_value == pytest.approx(1.0, rel=1e-12)
assert res_0.log_p_value == pytest.approx(0.0, abs=1e-12)
extreme = fisher_exact_right_tail(
k=5000, count_a=5500, count_b=5500, n_total=100000
)
assert math.isfinite(extreme.log_p_value)
assert extreme.log_p_value < -750.0
assert extreme.neg_log10_p > 300.0
assert extreme.p_value == 0.0
def test_bh_fdr_and_holm_monotonicity_and_total_hypotheses() -> None:
p_vals = [0.001, 0.02, 0.01, 0.50]
log_p = [math.log(p) for p in p_vals]
# Sorted p: (0.001, 0.01, 0.02, 0.50) with m=4
# BH raw multipliers: 4/1*0.001=0.004, 4/2*0.01=0.02, 4/3*0.02=0.026666..., 4/4*0.5=0.5
q_vals = benjamini_hochberg_log(log_p)
assert q_vals == pytest.approx([0.004, 0.08 / 3.0, 0.02, 0.50], rel=1e-12)
# Holm raw multipliers: 4*0.001=0.004, 3*0.01=0.03, 2*0.02=0.04, 1*0.50=0.50
holm_vals = holm_bonferroni_log(log_p)
assert holm_vals == pytest.approx([0.004, 0.04, 0.03, 0.50], rel=1e-12)
for q, h in zip(q_vals, holm_vals):
assert q <= h + 1e-15
q_larger_m = benjamini_hochberg_log(log_p, total_hypotheses=20)
for q_small, q_large in zip(q_vals, q_larger_m):
assert q_large >= q_small - 1e-15
assert q_larger_m[0] == pytest.approx(0.02, rel=1e-12)
def test_temporal_split_zero_leakage_and_determinism() -> None:
ds_a = generate_synthetic_retail_baskets(n_transactions=200, seed=42)
ds_b = generate_synthetic_retail_baskets(n_transactions=200, seed=42)
assert ds_a.transactions == ds_b.transactions
pd.testing.assert_frame_equal(ds_a.transaction_df, ds_b.transaction_df)
train, holdout = temporal_train_holdout_split(ds_a, train_fraction=0.5)
assert len(train) + len(holdout) == len(ds_a.transactions)
assert train == ds_a.transactions[:100]
assert holdout == ds_a.transactions[100:]
df = ds_a.transaction_df
for col in ("transaction_id", "timestamp_idx", "quantity"):
assert pd.api.types.is_integer_dtype(df[col])
assert int(df[col].isna().sum()) == 0
assert bool((df["line_profit"] >= 0.0).all())
def test_end_to_end_pipeline_recovers_complements_and_rejects_substitutes() -> None:
dataset = generate_synthetic_retail_baskets(n_transactions=4000, seed=42)
train_tx, holdout_tx = temporal_train_holdout_split(dataset, train_fraction=0.5)
train_itemsets = mine_frequent_itemsets_fpgrowth(train_tx, min_support=0.02)
item_margins = {sku: spec.unit_margin for sku, spec in dataset.item_specs.items()}
rules = extract_and_test_rules(
frequent_itemsets=train_itemsets,
eval_transactions=holdout_tx,
item_margins=item_margins,
min_confidence=0.15,
alpha=0.05,
single_consequent=True,
filter_significant_only=False,
)
sig_pair_map = {
(r.antecedent, r.consequent): r
for r in rules
if r.is_significant
}
for anc, cons in dataset.planted_complements:
key = (frozenset({anc}), frozenset({cons}))
assert key in sig_pair_map, f"Missing planted complement rule {anc} -> {cons}"
rule = sig_pair_map[key]
assert rule.q_value <= 0.05
assert rule.zhang > 0.2
substitutes = find_substitute_pairs(
dataset.transactions, min_marginal_support=0.01, max_zhang=-0.25
)
sub_pairs_found = {(min(a, b), max(a, b)): z for a, b, z in substitutes}
for s_a, s_b in dataset.planted_substitutes:
pair_key = (min(s_a, s_b), max(s_a, s_b))
assert pair_key in sub_pairs_found, f"Missing planted substitute pair {pair_key}"
assert sub_pairs_found[pair_key] <= -0.25
def test_banana_trap_margin_demotion() -> None:
dataset = generate_synthetic_retail_baskets(n_transactions=4000, seed=42)
n_total = len(dataset.transactions)
for staple in dataset.staple_skus:
marg_support = sum(1 for basket in dataset.transactions if staple in basket) / n_total
assert marg_support >= 0.20
train_tx, holdout_tx = temporal_train_holdout_split(dataset, train_fraction=0.5)
train_itemsets = mine_frequent_itemsets_fpgrowth(train_tx, min_support=0.02)
item_margins = {sku: spec.unit_margin for sku, spec in dataset.item_specs.items()}
rules = extract_and_test_rules(
frequent_itemsets=train_itemsets,
eval_transactions=holdout_tx,
item_margins=item_margins,
min_confidence=0.15,
alpha=0.05,
)
staple_set = set(dataset.staple_skus)
planted_comp_margins = [
r.expected_incremental_margin
for r in rules
if r.is_significant
and any(
r.antecedent == frozenset({a}) and r.consequent == frozenset({b})
for a, b in dataset.planted_complements
)
]
assert len(planted_comp_margins) == len(dataset.planted_complements)
min_planted_margin = min(planted_comp_margins)
staple_consequent_margins = [
r.expected_incremental_margin
for r in rules
if r.consequent.issubset(staple_set)
]
if staple_consequent_margins:
assert max(staple_consequent_margins) < min_planted_margin
def test_twu_downward_closure_invariant() -> None:
dataset = generate_synthetic_retail_baskets(n_transactions=400, seed=19)
candidates = [
frozenset({"espresso_maker"}),
frozenset({"espresso_beans"}),
frozenset({"coffee_filter"}),
frozenset({"espresso_maker", "espresso_beans"}),
frozenset({"espresso_maker", "espresso_beans", "coffee_filter"}),
frozenset({"banana"}),
frozenset({"banana", "plastic_bag"}),
]
twu_map = compute_twu_and_exact_utility(dataset.transaction_df, candidates)
for itemset in candidates:
exact_u, twu_val = twu_map[itemset]
assert exact_u <= twu_val + 1e-9
assert twu_map[frozenset({"espresso_maker", "espresso_beans"})][1] <= (
twu_map[frozenset({"espresso_maker"})][1] + 1e-9
)
assert twu_map[frozenset({"espresso_maker", "espresso_beans"})][1] <= (
twu_map[frozenset({"espresso_beans"})][1] + 1e-9
)
assert twu_map[frozenset({"espresso_maker", "espresso_beans", "coffee_filter"})][1] <= (
twu_map[frozenset({"espresso_maker", "espresso_beans"})][1] + 1e-9
)
assert twu_map[frozenset({"banana", "plastic_bag"})][1] <= (
twu_map[frozenset({"banana"})][1] + 1e-9
)
def test_memory_benchmark_bytes_and_checksum_parity() -> None:
results = benchmark_vector_scale_and_sum(n_elements=20_000, repeats=1, seed=42)
by_name = {r.backend_name: r for r in results}
py_res = by_name["python_list_float"]
np_res = by_name["numpy_float64_contiguous"]
pd_res = by_name["pandas_dataframe_float64"]
assert py_res.bytes_per_element > 3.0 * np_res.bytes_per_element
assert pd_res.checksum == pytest.approx(np_res.checksum, rel=1e-6)
assert py_res.checksum == pytest.approx(np_res.checksum, rel=1e-6)
def test_cooccurrence_blas_matches_python_loops() -> None:
rng = np.random.default_rng(123)
mat_u8 = (rng.random((200, 15)) < 0.25).astype(np.uint8)
results = benchmark_cooccurrence_engines(mat_u8, repeats=1)
by_name = {r.backend_name: r for r in results}
py_chk = by_name["python_nested_basket_loops"].checksum
pd_chk = by_name["pandas_dataframe_dot"].checksum
np_chk = by_name["numpy_blas_matmul"].checksum
assert py_chk == pytest.approx(np_chk, rel=1e-12, abs=1e-9)
assert pd_chk == pytest.approx(np_chk, rel=1e-12, abs=1e-9)
def test_numpy_views_and_broadcast_zero_stride() -> None:
audit = audit_numpy_views_and_strides()
assert audit.slice_is_view is True
assert audit.transpose_is_view is True
assert audit.fancy_index_is_copy is True
assert audit.non_contiguous_reshape_is_copy is True
assert audit.broadcast_strides == (0, 0)
def test_cli_demo_script_runs_cleanly(tmp_path: Path) -> None:
repo_root = Path(__file__).resolve().parents[1]
script_path = repo_root / "scripts" / "run_lab_demo.py"
json_out = tmp_path / "demo_summary.json"
env = os.environ.copy()
src_str = str(repo_root / "src")
env["PYTHONPATH"] = (
f"{src_str}{os.pathsep}{env['PYTHONPATH']}" if "PYTHONPATH" in env else src_str
)
proc = subprocess.run(
[
sys.executable,
str(script_path),
"--n-transactions",
"600",
"--n-bench",
"10000",
"--json-out",
str(json_out),
],
cwd=str(repo_root),
env=env,
capture_output=True,
text=True,
check=False,
)
assert proc.returncode == 0, f"stderr: {proc.stderr}"
assert "[1] Memory & Vectorization Benchmark" in proc.stdout
assert "[2] Worked 6-Transaction Textbook Cross-Check" in proc.stdout
assert "[3] Leakage-Free Synthetic Retail MBA" in proc.stdout
assert "[4] Substitute Pair Quarantine" in proc.stdout
assert json_out.exists()
def test_train_only_min_confidence_preserves_bh_m_and_incremental_margin() -> None:
"""Verify min_confidence filters only on train (preserving BH m) and incremental margin = (P(B|A)-P(B))*m_B."""
from mba_lab.fpgrowth import FrequentItemset
# Train: a (4/10), b (5/10), {a,b} (3/10 -> train conf=0.75); c (4/10), {c,b} (1/10 -> train conf=0.25)
# With min_confidence=0.50: only a->b passes train filter; b->a (3/5=0.60) also passes; c->b & b->c fail.
train_itemsets = [
FrequentItemset(frozenset({"a"}), 4, 0.4),
FrequentItemset(frozenset({"b"}), 5, 0.5),
FrequentItemset(frozenset({"c"}), 4, 0.4),
FrequentItemset(frozenset({"a", "b"}), 3, 0.3),
FrequentItemset(frozenset({"b", "c"}), 1, 0.1),
]
# Holdout: a->b confidence drops to 0.20 (< min_confidence=0.50), b->a drops to 0.25.
# Both MUST survive into holdout testing so BH-FDR m == 2 (not shrunk post-selection on holdout!).
holdout_tx = [
frozenset({"a", "b"}),
frozenset({"a"}),
frozenset({"a"}),
frozenset({"a"}),
frozenset({"a"}),
frozenset({"b"}),
frozenset({"b"}),
frozenset({"b"}),
frozenset({"c"}),
frozenset({"c"}),
]
rules = extract_and_test_rules(
frequent_itemsets=train_itemsets,
eval_transactions=holdout_tx,
item_margins={"a": 10.0, "b": 20.0, "c": 5.0},
min_confidence=0.50,
alpha=0.05,
single_consequent=True,
)
rule_map = {(r.antecedent, r.consequent): r for r in rules}
assert set(rule_map.keys()) == {
(frozenset({"a"}), frozenset({"b"})),
(frozenset({"b"}), frozenset({"a"})),
}
ab = rule_map[(frozenset({"a"}), frozenset({"b"}))]
# Holdout: P(b|a) = 1/5 = 0.20, P(b) = 4/10 = 0.40, m_b = 20.0 -> (0.20 - 0.40) * 20.0 = -4.0
assert ab.confidence == pytest.approx(0.20)
assert ab.expected_incremental_margin == pytest.approx((0.20 - 0.40) * 20.0)
def test_security_ast_no_unsafe_deserialization() -> None:
"""Enforce Security-Only AST Deserialization Ban across src/, scripts/, and tests/."""
forbidden_unsafe_imports = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
lab_root = Path(__file__).resolve().parents[1]
for folder in ("src", "scripts", "tests"):
for py_file in (lab_root / folder).rglob("*.py"):
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top_pkg = alias.name.split(".", 1)[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe import {top_pkg} in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module:
top_pkg = node.module.split(".", 1)[0]
assert top_pkg not in forbidden_unsafe_imports, (
f"Forbidden unsafe from-import {top_pkg} in {py_file}"
)
list[float] chứa 1,000,000 số thực float64 tiêu tốn tối thiểu bao nhiêu byte cho mảng con trỏ và các đối tượng PyFloatObject riêng lẻ trên kiến trúc 64-bit?ob_item chiếm 8 byte và trỏ tới một PyFloatObject 24 byte trên heap (16 B PyObject_HEAD + 8 B double), tổng 32 B/phần tử (gấp 4 lần 8 B/phần tử liên tục của PyArrayObject), chưa tính thêm phân mảnh cấp phát heap.
a = np.arange(24, dtype=np.float64).reshape(4, 6) (C-contiguous). Phép toán nào sau đây buộc NumPy phải cấp phát bộ nhớ mới (copy) thay vì tạo zero-copy view?a.T và a[:, ::2] chỉ chỉnh sửa metadata shape/strides (zero-copy view). broadcast_arrays dùng bước nhảy ảo stride = 0. Ngược lại, fancy indexing luôn trả về bản sao, còn a.T.reshape(-1) phải sao chép vì bộ nhớ sau chuyển vị không còn liên tục.
node_link của mặt hàng tiền tố cuối cùng x, trọng số đếm gán cho mỗi tiền tố tổ tiên trên đường đi về gốc bằng gì?x, số giao dịch thực sự đi qua nút đó chính xác là x.count, nên mọi nút tổ tiên trên đường tiền tố chỉ nhận trọng số đóng góp đúng bằng x.count.
math.lgamma + LogSumExp thay vì giữ giá trị p_value tuyến tính (float64) từ scipy.stats?p_value thường nhỏ hơn 1e-308 và bị làm tròn thành 0.0 trong float64, làm hàng trăm luật đồng hạng nhau khi chạy bước BH-FDR. Không gian log giữ nguyên chính xác \(\ln p\) hữu hạn (ví dụ -250.1 vs -800.4).
HUIM không thể cắt tỉa bằng u(X) < min_util trực tiếp mà phải dùng cận trên Transaction-Weighted Utility \(\operatorname{TWU}(X)\)?X có thể đẩy \(u(X \cup \{i\}) > u(X)\), phá vỡ giả định Apriori. Cận trên \(\operatorname{TWU}(X) = \sum_{T \supseteq X} \operatorname{TU}(T)\) gom toàn bộ tiện ích giao dịch chứa X, nên khi tập nở rộng số giao dịch chứa giảm dần khiến TWU đơn điệu giảm an toàn.
Prod2Vec / SGNS với \(k_{\text{neg}}\) mẫu âm, tích vô hướng hội tụ của vector nhúng \(\mathbf{w}_i^\top \mathbf{c}_j\) tương ứng với đại lượng MBA cổ điển nào?Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chứng minh Ngưỡng Bayes Bất đối xứng & Ứng dụng Stripe Radar 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tại một điểm đặc trưng x bất kỳ, viết rủi ro có điều kiện kỳ vọng cho hai hành động \(\hat{y}=1\) (chặn giao dịch) và \(\hat{y}=0\) (cho qua) theo \(\eta(x) = P(Y=1 \mid X=x)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Hành động \(\hat{y}=1\) chỉ thua lỗ khi \(Y=0\) (chi phí \(C_{\text{FP}}\)), nên rủi ro điều kiện là \((1 - \eta(x)) C_{\text{FP}}\). Hành động \(\hat{y}=0\) chỉ thua lỗ khi \(Y=1\) (chi phí \(C_{\text{FN}}\)), rủi ro là \(\eta(x) C_{\text{FN}}\).
Tiêu chí Đáp án & Số đối chứng
Đặt \((1-\eta(x))C_{\text{FP}} \le \eta(x)C_{\text{FN}} \implies \tau^* = \frac{720}{720+180} = 0.80\). Nếu điểm thô bị phóng đại 3x, xác suất thật \(\eta = 0.27\) bị thổi lên 0.81 >= 0.80 khiến giao dịch hợp lệ bị chặn tràn lan, phá vỡ SLA false-positive ~0.1% — buộc phải hiệu chuẩn (Isotonic / Platt) trước khi áp ngưỡng.
Bài tập 2 — Chứng minh Thước đo Zhang trên 3 Chế độ & Cặp thay thế N = 100,000 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Thay \(p_{AB} = p_A \alpha\) và biến đổi hiệu \(p_B - p_{AB} = (1 - p_A)\beta\) để đưa tử số \(p_{AB} - p_A p_B\) và mẫu số về hàm của \(\alpha\) và \(\beta\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Khi \(\sigma(A)=\sigma(B)=2000, \sigma(A\cup B)=0\) trên \(N=100{,}000\): tính \(p_A=p_B=0.02\), \(p_{AB}=0\), chú ý tử số Leverage chỉ là -0.0004 rất nhỏ.
Tiêu chí Đáp án & Số đối chứng
\(\operatorname{Zhang} = \frac{\alpha - \beta}{\max(\alpha, \beta)}\) đạt +1 khi \(\beta=0\) (khả năng đồng xuất hiện thuần), 0 khi \(\alpha=\beta\), và -1 khi \(\alpha=0\). Với ví dụ viên nén: Support=0, Conf=0, Lift=0, Leverage=-0.0004, Conv=0.98, Kulc=0, IR=0, nhưng Zhang=-1.000 giúp bắt dính ngay cặp cạnh tranh.
Bài tập 3 — Gỡ lỗi 3 Sự cố Pandas/NumPy (Bug A, Bug B, Bug C) 17.5%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Bug A: outer join chèn NaN vào cột int64, khiến Pandas tự ép kiểu sang float64 vốn chỉ chính xác tới \(2^{53}\) (9.007e15) — làm mất bit cuối của Snowflake ID 64-bit.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Bug B: prices[:16] là một view giữ con trỏ base tới toàn bộ vùng nhớ 4 GB ngăn GC giải phóng; Bug C: Python hash(s) thay đổi ngẫu nhiên qua mỗi tiến trình vì PYTHONHASHSEED.
Tiêu chí Đáp án & Số đối chứng
Dùng pd.Int64Dtype() (Int64 nullable) cho ID trước merge; dùng prices[:16].copy() (xác minh not np.shares_memory(top_prices, prices)); và thay hash() bằng int.from_bytes(hashlib.blake2b(str(s).encode(), digest_size=8).digest(), 'little') để chia tập tất định.
Bài tập 4 — Thực nghiệm Bước nhảy C-Order vs. F-Order Trên Ma trận 8000x8000 17.5%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Ma trận float64 (8 B) kích thước (8000, 8000): trong order='C', strides=(64000, 8); trong order='F', strides=(8, 64000).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Dòng cache 64 B chứa được đúng 8 phần tử float64 liên tiếp khi bước nhảy bằng 8 B (tiện cho nạp trước tuần tự & nạp thanh ghi AVX2/AVX-512 4–8 số cùng lúc).
Tiêu chí Đáp án & Số đối chứng
Cộng axis=1 nhanh vượt trội trên mat_c (stride=8 B), còn cộng axis=0 nhanh vượt trội trên mat_f. Khi duyệt ngược chiều stride=64,000 B, mỗi phần tử đọc chỉ dùng 8 B trong dòng cache 64 B (lãng phí 87.5% băng thông DRAM) và mất vector hóa SIMD.
Bài tập 5 — Thiết kế Dịch vụ Gợi ý Checkout Dưới SLA < 40 ms p99 12.5%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tách rõ Đường Nóng Trực tuyến (Online Serving < 40 ms: Two-Tower + HNSW + re-ranking biên lợi nhuận + bộ lọc thay thế tiền tính toán) và Đường Lạnh Ngoại tuyến (DuckDB/Polars + Fisher/BH-FDR/Zhang + CATE uplift).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Để giải quyết 2,000 SKU mới/tháng (cold-start) khi chưa có lịch sử giỏ hàng: dùng thuộc tính nội dung/ảnh + danh mục để đưa vào tháp Item Tower của Two-Tower hoặc GAT chuyển giao như P-Companion.
Tiêu chí Đáp án & Số đối chứng
Đảm bảo 4 chốt chặn: (a) Tính biên lợi nhuận gia tăng kỳ vọng ròng expected_incremental_margin \(= (\Pr(B \mid A) - \Pr(B)) \times m_B\) (loại bỏ xác suất nền của hàng thiết yếu) + ngưỡng Zhang > 0.2; (b) Phân tầng theo kích thước/loại cửa hàng (store_format) chống nghịch lý Simpson; (c) Dùng CATE uplift loại bỏ tự ăn mòn khuyến mãi; (d) Feature fallback từ metadata cho SKU mới + shadow deployment kiểm tra độ trễ.
Bài tập 6 — Chẩn đoán Pipeline Mining Thất bại 80% Trên A/B Test 12.5%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kiểm tra lại chuỗi thời gian dữ liệu: toàn bộ 1 triệu giỏ bị dùng chung cả cho khai phá luật lẫn tính p-value.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Với \(M = 10{,}000\) SKUs, số cặp kiểm định lên tới \(\binom{10000}{2} \approx 5 \times 10^7\). Dùng p <= 0.05 chưa hiệu chỉnh có thể tạo ra ~2.5 triệu dương tính giả.
Tiêu chí Đáp án & Số đối chứng
4 lỗi chính: (1) Rò rỉ hậu chọn lọc (mine & test chung một tập); (2) Không hiệu chỉnh đa kiểm định BH-FDR; (3) Thống kê tiệm cận \(\chi^2\) sai lệch ở đuôi thưa (min_support=0.001) so với Fisher chính xác; (4) Không đo Zhang > 0 / biên lợi nhuận / CATE nên gợi ý cả hàng thay thế và mặt hàng tự mua.